Mr Andersson

How to get $VerbosePreference applied on remote commands

leave a comment »

If you use Write-Verbose in a script executed on a remote computer, you may not get the result you expect.

Example TestRemoteCommand.ps1:

Invoke-Command -ComputerName comp1 -ScriptBlock { 
    Write-Host "hello"
    Write-Verbose "there"
}

The above will only output “hello” and not “there” in the host window.

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
Advertisements

Written by anderssonjohan

November 19, 2009 at 14:25

Posted in scripting

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: