这是我的代码:
$script={
Write-Host "Num Args:" $args.Length;
Write-Host $args[0]
}
Invoke-Command -ScriptBlock $script
当我运行时
powershell.exe .\test.ps1 one two three
我得到了
Num Args: 0
我以为我会得到
Num Args: 3
One
我错过了什么吗?
谢谢
最佳答案
你实际上有两个范围。脚本级别和脚本 block 级别。 $args.Length
和 $args[0]
将在 Invoke-Command
级别具有您所期望的。在脚本 block 内,$args
有另一个作用域。要从命令行一直获取参数到脚本 block 中,您需要从 Invoke-Command -ArgumentList $args
重新传递它们。
关于windows - powershell 传递命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9185124/