“
PowerShell.exe的命令行选项”表明,使用脚本块时应该能够通过添加“-args:”来传递参数。
PowerShell.exe -Command { - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>] }
然而,当我尝试这样做时,出现了以下错误:
-args:该术语“-args”不被识别为命令、函数、脚本文件或可操作程序的名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
我在脚本块中添加了
$MyInvocation | fl
以查看发生了什么,看起来-args只是附加到脚本块中反序列化的命令(因此出现错误,因为-args不是有效的命令)。我还尝试使用
GetNewClosure()和$Using:VariableName,但这些似乎只在调用脚本块时起作用(与我们在此处使用它进行序列化/反序列化命令的方式不同)。
然后,我通过像
deadlydog's answer那样将其包装在一个函数中才能使其正常工作。
$var = "this is a test"
$scriptblock = {
$MyInvocation | fl
function AdminTasks($message){
write-host "hello world: $message"
}
}
Start-Process powershell -ArgumentList '-noexit','-nologo','-noprofile','-NonInteractive','-Command',$scriptblock,"AdminTasks('$var')" -Verb runAs
MyCommand :
$MyInvocation | fl
function AdminTasks($message){
write-host hello world: $message
}
AdminTasks('this is a test')
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 0
OffsetInLine : 0
HistoryId : 1
ScriptName :
Line :
PositionMessage :
PSScriptRoot :
PSCommandPath :
InvocationName :
PipelineLength : 2
PipelinePosition : 1
ExpectingInput : False
CommandOrigin : Runspace
DisplayScriptPosition :
hello world: this is a test
将其用脚本块包装并使用
$args [0]
或
$args [1]
也可以,但请注意,如果在反序列化时出现问题,则可能需要将$var0或$var1用引号括起来,并使用`$来防止$sb被替换为"",因为该变量不存在于调用者的范围内:
$var0 = "hello"
$var1 = "world"
$scriptblock = {
$MyInvocation | fl
$sb = {
write-host $args[0] $args[1]
}
}
Start-Process powershell -ArgumentList '-noexit','-nologo','-noprofile','-NonInteractive','-Command',$scriptblock,"& `$sb $var0 $var1"
&
运算符调用表达式,如您示例中的& $Scriptblock
。 - oɔɯǝɹ