我感觉自己错过了某些显而易见的东西,但我就是想不出如何做到这一点。
我有一个ps1脚本,在其中定义了一个函数。它调用该函数,然后尝试在远程使用它:
function foo
{
Param([string]$x)
Write-Output $x
}
foo "Hi!"
Invoke-Command -ScriptBlock { foo "Bye!" } -ComputerName someserver.example.com -Credential someuser@example.com
这个简短的示例脚本会打印 "Hi!",然后崩溃并显示 "The term 'foo' is not recognized as the name of a cmdlet, function, script file, or operable program."。
我理解函数在远程服务器上未被定义,因为它不在 ScriptBlock 中。我可以重新在那里定义它,但我不想这样做。我希望只定义一次函数并在本地或远程都能使用它。有没有好的方法实现这一点?
-ScriptBlock {$function:foo|format-table -auto}
。基本上,任何ScriptBlock
都可以是任何有效的 PowerShell 代码“块”,只要你正确地格式化它(或在每个“行”末尾使用分号),你就应该没问题。例如,早些时候我正在处理measure-command {$x=[xml](get-content file.xml);$x.selectsinglenode("//thing");}
。 - alroc