In my script I run a command like
[array]$Results = $AllSpamAllowGroups.Email | ForEach-Object {
& gam update group $_ spam_moderation_level moderate
[PSCustomObject]@{
GroupEmail = $_
Error = $LastExitCode
}
}
When I open the results it is
"12"
"45"
"19"
...so on
If I
& gam update group $_ spam_moderation_level moderate | out-null
Then $Results
has good data. But the command doesn't actually do anything.
Do I have to assign it to a trash Variable ?
$IAMTrash = & gam update group $_ spam_moderation_level moderate
Seems like I should not have to do this. (Trash variable also gives good data)
CodePudding user response:
Instead of a "trash variable", the best practice is to assign unwanted output to $null
. This actually discards the output and better communicates your intentions. Piping to Out-Null
works too, but is less efficient.
[array]$Results = $AllSpamAllowGroups.Email | ForEach-Object {
# Makes the command run completely silent (unless it writes to stderr too)
$null = & gam update group $_ spam_moderation_level moderate
# Only this gets captured in $Results
[PSCustomObject]@{
GroupEmail = $_
Error = $LastExitCode
}
}
The disadvantage of this approach is that you don't see what the program is doing. It might output useful logging information or a detailed error description in case of failure. All this is lost using the above code.
To see the command output without letting it "contaminating" your result, you can pipe it to Out-Host
, so it gets written to the console only, but won't get captured:
[array]$Results = $AllSpamAllowGroups.Email | ForEach-Object {
# Command output goes to console only
& gam update group $_ spam_moderation_level moderate | Out-Host
# Only this gets captured in $Results
[PSCustomObject]@{
GroupEmail = $_
Error = $LastExitCode
}
}