PowerShell将命令行参数传递给主脚本到第二个脚本

问题描述 投票:0回答:1

我有两个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的输出:

嗨SCRIPT12

Script2.ps1的输出:

System.Object的[]1

问题:

  1. 为什么我不能直接在$args上使用Script2.ps1(变成null)?
  2. 为什么$args通过Script1.ps1传递为Script2.ps1中的单个字符串?

在PowerShell 2.0中运行正常。

parameter-passing powershell-5.0
1个回答
1
投票

您正在从PowerShell中调用第二个脚本。因此,数组$args不会扩展为其元素,而是作为单个数组参数传递。使用splatting使PowerShell将数组元素作为单独的参数传递。

.\Script2.ps1 @args

旁注:不需要使用点源运算符(.)来调用脚本,除非您需要脚本在与调用脚本相同的上下文中运行。

© www.soinside.com 2019 - 2024. All rights reserved.