Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass -Verbose parameter to a function called inside Invoke-Command?

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}}
like image 346
tholesen Avatar asked Apr 25 '26 06:04

tholesen


1 Answers

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


}
}
like image 64
Kiran Avatar answered Apr 27 '26 08:04

Kiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!