PowerShell:将命令行参数从主脚本传递到第二个脚本
PowerShell: pass command line parameter from main script to second script
我有两个 PowerShell 脚本。第一个脚本从命令行获取两个参数并将它们传递给第二个脚本。
Script1.ps1
:
Write-Output ($args)
Write-Output ($args.Length)
. ./Script2.ps1 $args
Script2.ps1
:
Write-Output ($args)
Write-Output ($args.Length)
这样称呼
Script1.ps1 hi script1
Script1.ps1
的输出:
hi
script1
2
Script2.ps1
的输出:
System.Object[]
1
问题:
- 为什么我不能直接在
Script2.ps1
(为空)上使用 $args
?
- 为什么
$args
通过 Script1.ps1
作为单个字符串出现在 Script2.ps1
中?
这在 PowerShell 2.0 中工作正常。
您正在从 PowerShell 中调用第二个脚本。因此,数组 $args
不会扩展为其元素,而是作为单个数组参数传递。使用 splatting 让 PowerShell 将数组元素作为单独的参数传递。
.\Script2.ps1 @args
旁注:不需要使用点源运算符 (.
) 来调用脚本,除非您需要脚本 运行 在与调用它的脚本相同的上下文中.
我有两个 PowerShell 脚本。第一个脚本从命令行获取两个参数并将它们传递给第二个脚本。
Script1.ps1
:
Write-Output ($args)
Write-Output ($args.Length)
. ./Script2.ps1 $args
Script2.ps1
:
Write-Output ($args)
Write-Output ($args.Length)
这样称呼
Script1.ps1 hi script1
Script1.ps1
的输出:
hi script1 2
Script2.ps1
的输出:
System.Object[] 1
问题:
- 为什么我不能直接在
Script2.ps1
(为空)上使用$args
? - 为什么
$args
通过Script1.ps1
作为单个字符串出现在Script2.ps1
中?
这在 PowerShell 2.0 中工作正常。
您正在从 PowerShell 中调用第二个脚本。因此,数组 $args
不会扩展为其元素,而是作为单个数组参数传递。使用 splatting 让 PowerShell 将数组元素作为单独的参数传递。
.\Script2.ps1 @args
旁注:不需要使用点源运算符 (.
) 来调用脚本,除非您需要脚本 运行 在与调用它的脚本相同的上下文中.