我写了以下代码:
cls
function GetFoo() {
function GetBar() {
$bar = "bar"
$bar
}
$foo = "foo"
$bar = GetBar
$foo
$bar
}
$cred = Get-Credential "firmwide\srabhi_adm"
$result = Invoke-Command -Credential $cred -ComputerName localhost
-ScriptBlock ${function:GetFoo}
Write-Host $result[0]
Write-Host $result[1]
它有效,但我不想在GetBar
中定义GetFoo
。
我可以这样做吗?
cls
function GetBar() {
$bar = "bar"
$bar
}
function GetFoo() {
$foo = "foo"
$bar = GetBar
$foo
$bar
}
$cred = Get-Credential "firmwide\srabhi_adm"
$result = Invoke-Command -Credential $cred -ComputerName localhost
-ScriptBlock ${function:GetFoo; function:GetBar; call GetFoo}
Write-Host $result[0]
Write-Host $result[1]
基本上我选择性地将我想要的函数放在ScriptBlock中,然后调用其中一个。这样我就不必在函数内部定义函数了,我可以通过注入我希望成为ScriptBlock一部分的函数来构造ScriptBlock。
问题是Invoke-Command
只能看到ScriptBlock
里面的东西,它看不到外面定义的功能。如果你真的想 - 你可以在一行中运行所有内容,如下所示:
$result = Invoke-Command -ComputerName localhost -ScriptBlock { function GetBar() { $bar = "bar"; $bar }; function GetFoo() { $foo = "foo"; $bar = GetBar; $foo; $bar }; GetFoo }
但我个人会建议你在脚本中保存函数并使用Invoke-Command
参数调用-FilePath
,如下所示:
$result = Invoke-Command -ComputerName localhost -FilePath "\1.ps1"