Be warned that the preferences do not get passed to a script block in a parallel pipeline. You must include a $whatifpreference=$using:whatifpreference to pass the whatif value. Assume you get the default.
This is also true if using INVOKE-COMMAND with a script block. It might be very unpleasant if you are not aware of this. Again, assume you get the defaults in a new session. For example, running this from a new session show what looks to be okay using defaults is not okay once defaults are not used.
# save the default session values the very first thing before we change them
if ($null -eq $defPref) { $defPref = $DebugPreference, $VerbosePreference, $InformationPreference, $WarningPreference, $ErrorActionPreference, $WhatIfPreference, $ProgressPreference}
if ($null -eq $nonPref) { $nonPref = 'Continue', 'Continue', 'Continue', 'Stop', 'Stop', $true, 'SilentlyContinue'}
write-host 'Using defaults locally:'
$localPref = $defPref # the defaults here match the defaults there
invoke-command -ComputerName SQLTEST18.DEV.LOCAL -ScriptBlock {
write-host "`$localPref=$($using:localPref)"
$remotePref = $DebugPreference, $VerbosePreference, $InformationPreference, $WarningPreference, $ErrorActionPreference, $WhatIfPreference, $ProgressPreference
write-host "`$remotePref=$remotePref"
}
write-host 'Using non-defaults locally:'
$localPref = $nonPref # the non-defaults here do not match the defaults there
invoke-command -ComputerName SQLTEST18.DEV.LOCAL -ScriptBlock {
write-host "`$localPref=$($using:localPref)"
$remotePref = $DebugPreference, $VerbosePreference, $InformationPreference, $WarningPreference, $ErrorActionPreference, $WhatIfPreference, $ProgressPreference
write-host "`$remotePref=$remotePref"
}
Output:
Using defaults locally:
$localPref=SilentlyContinue SilentlyContinue SilentlyContinue Continue Continue False Continue
$remotePref=SilentlyContinue SilentlyContinue SilentlyContinue Continue Continue False Continue
Using non-defaults locally:
$localPref=Continue Continue Continue Stop Stop True SilentlyContinue
$remotePref=SilentlyContinue SilentlyContinue SilentlyContinue Continue Continue False Continue