的command line options for PowerShell.exe說,你應該使用腳本塊時可以傳遞參數加入-args:
PowerShell.exe -Command { - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>] }
然而,當我嘗試這樣做,我得到以下錯誤:
-args : The term '-args' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
我將$MyInvocation | fl
添加到腳本塊以查看發生了什麼,看起來-args僅附加到腳本塊中的反序列化命令(因此-args不是有效命令)。我也嘗試過使用GetNewClosure() and $Using:VariableName,但是這些只有在腳本塊被調用時才起作用(與我們使用它來序列化/反序列化命令的情況相反)。
我能夠通過將其包裝在deadlydog's answer之類的功能中來使其工作。
$var = "this is a test"
$scriptblock = {
$MyInvocation | fl #Show deserialized commands
function AdminTasks($message){
write-host "hello world: $message"
}
}
Start-Process powershell -ArgumentList '-noexit','-nologo','-noprofile','-NonInteractive','-Command',$scriptblock,"AdminTasks('$var')" -Verb runAs #-WindowStyle Hidden
#Output:
MyCommand :
$MyInvocation | fl #Show deserialized commands
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 #Show deserialized commands
$sb = {
write-host $args[0] $args[1]
}
}
Start-Process powershell -ArgumentList '-noexit','-nologo','-noprofile','-NonInteractive','-Command',$scriptblock,"& `$sb $var0 $var1"
請退後一步,並說明你正在試圖解決的,而不是你所認爲的實際問題作爲解決方案。你爲什麼認爲你需要這個? –
您可以使用'&'運算符調用表達式。像你的例子中的'&$ Scriptblock'一樣。 –
我想開始一個新的PowerShell會話,並在該會話中運行一個腳本塊。該腳本塊將需要包含來自初始會話的局部變量。 – atownson