PowerShell: 使用变量参数的脚本

6
我想从另一个脚本启动script1.ps1,并使用存储在变量中的参数。
``` $para = "-Name name -GUI -desc ""this is the description"" -dryrun" . .\script1.ps1 $para ```
我在script1.ps1中获取到的参数是:
``` args[0]: -Name name -GUI -desc "this is the description" -dryrun ```
这不是我想要的结果。有没有人有解决这个问题的想法?
提示:不确定变量将包含多少个参数和它们的排序方式。
2个回答

7
你需要使用 splatting 操作符。查看powershell团队博客stackoverflow.com
以下是一个例子:
@'
param(
  [string]$Name,
  [string]$Street,
  [string]$FavouriteColor
)
write-host name $name
write-host Street $Street
write-host FavouriteColor $FavouriteColor
'@ | Set-Content splatting.ps1

# you may pass an array (parameters are bound by position)
$x = 'my name','Corner'
.\splatting.ps1 @x

# or hashtable, basically the same as .\splatting -favouritecolor blue -name 'my name'
$x = @{FavouriteColor='blue'
  Name='my name'
}
.\splatting.ps1 @x

在你的情况下,你需要这样调用它:

$para = @{Name='name'; GUI=$true; desc='this is the description'; dryrun=$true}
. .\script1.ps1 @para

我很高兴能够帮助您。如果您对答案感到满意,可以通过接受答案来关闭问题 ;) - stej
展开运算符在哪里?这里没有运算符,这只是PowerShell处理命令的方式...也就是说,这是一种特性,而不是运算符。 - John Leidegren

5

使用 Invoke-Expression 是另一种选择:

$para = '-Name name -GUI -desc "this is the description" -dryrun'
Invoke-Expression -Command ".\script1.ps1 $para"

谢谢,结果最终是一样的,但这是真正简洁美观的变体! - lepi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接