3

I have the following function that I am trying to invoke remotely with verbose output, but I don't know how to pass the VerbosePreference correctly?

function TestVerbose()
{
    [CmdletBinding()]
    Param()
    Write-Output "output test"
    Write-Verbose "verbose test"
}

Invoke-Command -ComputerName computerB -ScriptBlock ${function:TestVerbose}

The question How to Write-Verbose from Invoke-Command? nicely describes how to write something verbose if I have a non-function scriptblock:

Invoke-Command -ComputerName computerB {$VerbosePreference='Continue'; Write-Verbose "verbose test"}

However, I would like to pass a function and also indicate verbose preference. How to do that?

I have tried combining the function with some inline scriptblock, but it makes the function not run at all:

Invoke-Command -ComputerName computerB -ScriptBlock {$VerbosePreference='Continue'; ${function:TestVerbose}}
Community
  • 1
  • 1
tholesen
  • 460
  • 5
  • 10

1 Answers1

1

kind of a workaround. store the current value of verbosepreference , change it in your function and then reset to original value.

function TestVerbose()
{
[CmdletBinding()]
Param()
begin
{
    $VerbosePreference_original = $VerbosePreference
    $VerbosePreference = 'continue'
    Write-Verbose ('Begin:Original value of VerbosePreference : {0}' -f $VerbosePreference_original)
    Write-Verbose ('Begin:New value of VerbosePreference : {0}' -f $VerbosePreference)

}

process
{
    Write-Output 'output test'
    Write-Verbose 'output test'
}
end
{

    Write-Verbose ('END:ReSetting value of VerbosePreference to default : {0}' -f $VerbosePreference_original)
    $VerbosePreference = $VerbosePreference_original


}
}
Kiran Reddy
  • 2,836
  • 2
  • 16
  • 20
  • Good suggestion, however it does not directly allow me to pass a parameter determining whether or not to use verbose. I had already thought of adding a custom VerbosePref parameter that could then be used to set the local VerbosePreference, but this seems like a workaround and not a clean solution: `function TestVerbose() { [CmdletBinding()] Param($VerbosePref) if ($VerbosePref) { $VerbosePreference = $VerbosePref } Write-Output "output test" Write-Verbose "verbose test" }` – tholesen Feb 12 '16 at 07:41