I am using trying to use the Set-DistributionGroup
Exchange cmdlet in the following manner:
$Exch_Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeURI -Authentication Kerberos
Import-PSSession $Exch_Session -commandname Set-DistributionGroup -AllowClobber
if (<condition>) {
try {
Set-DistributionGroup @Setparams
}
catch {
<error capture code here...>
}
}
On success and failures, everything works as expected...But during a test run, while trying to change the PrimarySMTPAddress to an invalid value, I get a WARNING (not error) that the new email address doesn't adhere to an e-mail address policy so it will not be changed. But since this is a warning, the try
/catch
doesn't trigger and the entire process wrongly finishes as successful.
I've tried:
-WarningAction Stop
to the command and that does trigger the try/catch, but the error is too generic:
Command execution stopped because the preference variable "WarningPreference" or common parameter is set to Stop.
So I tried to capture the warning to a variable as well as file (to check for later when reporting success or failures), but all the ways I tried to capture failed, even though it continually displayed the warning to the screen.
Set-Distributiongroup @Setparams -WarningVariable cmd_warn
Set-Distributiongroup @Setparams 3> c:\temp\warnings.txt
...
$command = "Set-Distributiongroup @Setparams"
iex $command 3> c:\temp\warnings.txt
But the file and variable are always empty, what am I doing wrong or missed?
You state that you're using Import-PSSession
, which creates an (in-memory) module with proxy functions that transparently call commands of the same name on a remote machine, a concept known as implicit remoting.
Unfortunately, as of Windows PowerShell v5.1 / PowerShell Core 6.2.0-preview.4, the implementation of this feature has a number of problems with respect to preference variables, common parameters, and output streams.
In your specific case, try the following workaround:
Invoke-Command { Set-Distributiongroup @Setparams } -WarningVariable cmd_warn
if ($cmd_warn) { ... } # warning was emitted
Note that the Invoke-Command
call here doesn't itself perform remoting; it is merely a local invocation wrapper that makes the -WarningVariable
common parameter work when applied to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With