6

我想从另一个脚本中启动一个 script1.ps1,并将参数存储在一个变量中。

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

我在 script1.ps1 中得到的参数看起来像:

args[0]: -Name name -GUI -desc "这是描述" -dryrun

所以这不是我想要的。有谁知道如何解决这个问题?
谢谢lepi

PS:不确定变量将包含多少个参数以及它们将如何排名。

4

2 回答 2

7

您需要使用splatting operator。查看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
于 2010-08-02T14:22:48.673 回答
5

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

$para = '-Name name -GUI -desc "this is the description" -dryrun'
Invoke-Expression -Command ".\script1.ps1 $para"
于 2010-08-02T15:03:31.417 回答