【问题标题】:How to pass array of arguments to Powershell commandline如何将参数数组传递给 Powershell 命令行
【发布时间】:2012-11-07 06:36:29
【问题描述】:

我正在尝试将参数数组传递给 powershell 脚本文件。

我试图在命令行中像这样传递命令行。

Powershell -file "InvokeBuildscript.ps1" "z:\" "组件1","组件2"

但它并没有采用看起来的参数。我错过了什么?如何传递参数数组?

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    简短回答:更多双引号可能会有所帮助...

    假设脚本是“test.ps1”

    param(
    
        [Parameter(Mandatory=$False)]
        [string[]] $input_values=@()
    
    )
    $PSBoundParameters
    

    假设想传递数组@(123,"abc","x,y,z")

    在Powershell控制台下,将多个值作为数组传递

    .\test.ps1 -input_values 123,abc,"x,y,z"
    

    在 Windows 命令提示符控制台或 Windows 任务计划程序下;一个双引号替换为三个双引号

    powershell.exe -Command .\test.ps1 -input_values 123,abc,"""x,y,z"""
    

    希望对大家有所帮助

    【讨论】:

    • 这里的诀窍是使用明确的-command 而不是-file
    • 我可以使用-input_values 123,abc,'x,y,z'
    • 重申,迈克指出的,因为我在这个答案中也错过了它。对我有用的是使用-command而不是-file从批处理文件中调用Powershell.exe
    【解决方案2】:

    也可以将数组变量作为命令行参数传递。示例:

    考虑以下 Powershell 模块

    文件:PrintElements.ps1

    Param(
        [String[]] $Elements
    )
    
    foreach($element in $Elements)
    {
       Write-Host "element: $element"
    }
    

    要使用上面的 powershell 模块:

    #Declare Array Variable
    [String[]] $TestArray = "Element1", "Element2", "Element3"
    
    #Call the powershell module
    .\PrintElements.ps1 $TestArray
    

    如果您想连接并传递 TestArray 作为单个空格分隔元素的字符串,那么您可以通过将参数括在引号中来调用 PS 模块,如下所示:

    #Declare Array Variable
    [String[]] $TestArray = "Element1", "Element2", "Element3"
    
    #Call the powershell module
    .\PrintElements.ps1 "$TestArray"
    

    【讨论】:

      【解决方案3】:

      试试

      Powershell -command "c:\pathtoscript\InvokeBuildscript.ps1" "z:\" "Component1,component2"
      

      如果test.ps1 是:

      $args[0].GetType()
      $args[1].gettype()
      

      从 dos shell 中调用它,例如:

      C:\>powershell -noprofile -command  "c:\script\test.ps1" "z:" "a,b"
      

      返回:

      IsPublic IsSerial Name                                     BaseType
      -------- -------- ----                                     --------
      True     True     String                                   System.Object
      True     True     Object[]                                 System.Array
      

      【讨论】:

        猜你喜欢
        • 2010-11-20
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 2013-10-11
        • 2013-06-15
        • 2016-06-25
        • 2012-09-01
        相关资源
        最近更新 更多