如何将-Verbose参数传递给Invoke-Command内部调用的函数?

时间:2016-02-10 09:54:54

标签: powershell powershell-remoting invoke-command

我有以下函数,我试图用详细输出远程调用,但我不知道如何正确传递VerbosePreference?

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

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

问题How to Write-Verbose from Invoke-Command?很好地描述了如果我有一个非功能性的scriptblock,如何编写一些详细的东西:

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

但是,我想传递一个函数并指出详细的首选项。怎么做?

我尝试将该函数与一些内联scriptblock结合使用,但它使该函数根本无法运行:

Invoke-Command -ComputerName computerB -ScriptBlock {$VerbosePreference='Continue'; ${function:TestVerbose}}

1 个答案:

答案 0 :(得分:1)

一种解决方法。存储verbosepreference的当前值,在函数中更改它,然后重置为原始值。

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


}
}