【问题标题】:powershell: script with variable argspowershell:带有可变参数的脚本
【发布时间】:2010-08-02 13:07:09
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: powershell args


    【解决方案1】:

    您需要使用喷溅操作符。查看powershell team blogstackoverflow.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
    

    【讨论】:

    • 我很高兴能帮上忙。如果您对答案感到满意,您可以通过接受答案来关闭问题;)
    • 喷溅操作符在哪里?这里没有操作符,这恰好是 PowerShell 处理命令的方式......即它是一个功能,而不是一个操作符。
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢,最后的结果是一样的,但这是真正的好和短的变体!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多