我编写了以下代码:
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
with -FilePath
参数,像这样:
$result = Invoke-Command -ComputerName localhost -FilePath "\1.ps1"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)