How to get $VerbosePreference applied on remote commands
If you use Write-Verbose in a script executed on a remote computer, you may not get the result you expect.
Invoke-Command -ComputerName comp1 -ScriptBlock {
Write-Host "hello"
Write-Verbose "there"
}
I thought I was clever by just passing along the $VerbosePreference value:
Invoke-Command -ComputerName comp1 -ArgumentList $VerbosePreference -ScriptBlock {
param( $VerbosePreference )
Write-Host "hello"
Write-Verbose "there"
}
But, still no luck! Only the statement using Write-Host is included in the output when the command is invoked on the remote computer.
What’s going on here is that the argument sent to the remotely executed script block is converted to an integer, which is the base integral type of the underlying enum type of $VerbosePreference.
So I figured that typing the argument in the param() clause will bind the parameter to the correct data type, and voila, it now works as expected.
Invoke-Command -ComputerName comp1 -ArgumentList $VerbosePreference -ScriptBlock {
param( [System.Management.Automation.ActionPreference] $VerbosePreference )
Write-Host "hello"
Write-Verbose "there"
}
Now you can toggle the verbose output of your remote script using the switch of your local script:
.\TestRemoteCommand.ps1 # Default, or -Verbose:$false .\TestRemoteCommand.ps1 -Verbose