【问题标题】:Passing Named Parameters via an intermediary script通过中间脚本传递命名参数
【发布时间】:2014-03-07 23:28:38
【问题描述】:

我有两个脚本:

Script1.ps1:

param(
[string]$WhoCares = "",
[string]$PassThrough = ""
)

#do a whole bunch of random stuff here...
.\Script2.ps1 $PassThrough

Script2.ps1:

param(
[string]$FirstParameter = "",
[string]$SecondParameter = ""
)

Write-Host "First Parameter is: " $FirstParameter "Second Parmeter is: " $SecondParameter

我的设想是这样的:

Script1.ps1 -WhoCares one -Passthrough "-FirstParameter Test -SecondParameter Test1"

然后看到:

第一个参数是测试第二个参数是测试1

但我看到的是

第一个参数是 -FirstParameter Test -SecondParameter Test1 第二个参数是

也就是说,我要发送到 script2 的参数是作为字符串传入的。如何通过中间脚本传递参数

我不想修改 Script1.ps1 以包含所有可能的参数,因为我使用 Script1 来设置环境、日志记录等。

【问题讨论】:

  • 只需在Script2上使用-PassThru开关,如果您从Script1调用它,它将继承Script1中定义的任何变量。

标签: powershell parameters scripting


【解决方案1】:

我会更改 Script1 以将 Passthrough 参数设置为 Script2:

param(
[string]$WhoCares = "",
[hashtable]$PassThrough = @{}
)

#do a whole bunch of random stuff here...
.\Script2.ps1 @PassThrough

然后将 Passthrough 参数作为哈希表传递给 Script1:

$Passthru =
 @{
   FirstParameter = 'Test'
   SecondParameter = 'Test1'
  }

  Script1.ps1 -WhoCares One -Passthrough $Passthru

【讨论】:

  • 为了清楚起见,我认为 splatting 需要 v3+ iirc。但这绝对是实现这一目标的方法。
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2012-06-19
  • 2017-04-20
  • 2014-01-08
  • 1970-01-01
相关资源
最近更新 更多