powershell传递命令行参数

icn*_*icn 7 windows powershell powershell-2.0

这是我的代码:

$script={
 Write-Host "Num Args:" $args.Length;
  Write-Host $args[0]   
}

Invoke-Command  -ScriptBlock $script
Run Code Online (Sandbox Code Playgroud)

我跑的时候

  powershell.exe .\test.ps1 one two three
Run Code Online (Sandbox Code Playgroud)

我有

Num Args: 0
Run Code Online (Sandbox Code Playgroud)

我以为我会得到

Num Args: 3
One
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

谢谢

And*_*ndi 8

你实际上有两个范围.脚本级别和脚本块级别.$args.Length并且$args[0]会有你所期望的Invoke-Command水平.在脚本块内部还有另一个范围$args.要从命令行获取args一直到脚本块,您需要重新传递它们Invoke-Command -ArgumentList $args.


xcu*_*cud 5

您需要将参数传递给脚本块:

Invoke-Command  -ScriptBlock $script -ArgumentList $args 
Run Code Online (Sandbox Code Playgroud)