【问题标题】:How do I pass an array parameter to powershell -file?如何将数组参数传递给 powershell -file?
【发布时间】:2011-10-06 21:29:36
【问题描述】:

我有以下 powershell 脚本:

param(
    [Int32[]] $SomeInts = $null, 
    [String]$User = "SomeUser", 
    [String]$Password = "SomePassword"
)

New-Object PSObject -Property @{
    Integers = $SomeInts;
    Login = $User;
    Password = $Password;
} | Format-List

如果我执行.\ParameterTest.ps1 (1..10),我会得到以下信息:

Password : SomePassword
Login    : SomeUser
Integers : {1, 2, 3, 4...}

但是,如果我在像 powershell -file .\ParameterTest.ps1 (1..10) 这样的单独的 powershell 实例中运行它,我不会得到预期的结果。在这种情况下,我得到以下信息:

Password : 3
Login    : 2
Integers : {1}

我的问题是如何从命令行传递数组或其他复杂数据类型?

【问题讨论】:

    标签: powershell command-line


    【解决方案1】:

    数组的各个元素 (1..10) 正在作为参数传递给脚本。

    另一种方法是:

    powershell -command {.\test.ps1 (1..10)}
    

    对于同时适用于 powershell 控制台和 cmd 的版本:

    powershell -command "&.\test.ps1 (1..10)"
    

    【讨论】:

    • 这比 -EncodeCommand 更简单,并且也可以在 cmd.exe 中工作。
    【解决方案2】:

    答案是使用powershell.exe -EncodedCommand 并对参数进行base64 编码。对此的描述在PowerShell.exe Console Help technet 页面上。我已经将他们的仪式版本压缩成一条线:

    powershell.exe -EncodedCommand "$([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('.\ParameterTest.ps1 (1..10)')))"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2023-03-26
      • 1970-01-01
      • 2011-08-01
      相关资源
      最近更新 更多