【问题标题】:Powershell arguments list passing like -a <args list> -d <args list>Powershell 参数列表传递,如 -a <args list> -d <args list>
【发布时间】:2011-11-04 04:42:41
【问题描述】:

我想编写一个 powershell ps1 脚本,它需要 2 个参数集(-a -d),每个参数集最多可以有 n 个属性。如何实现?

example : DoTheTask -a <task name 1> <task name 2> ...  -d <machine name 1> <machine name 2>...

【问题讨论】:

    标签: powershell arguments command-line-arguments variadic-functions


    【解决方案1】:

    如果您将这些参数传递给脚本本身,则可以利用 $args 内部变量,尽管键/值映射会有点棘手,因为 PowerShell 会将每个语句解释为参数。我建议(像其他人一样)您使用另一个分隔符,以便您可以更轻松地进行映射。

    不过,如果你想继续这样做,你可以使用如下函数:

     Function Parse-Arguments {
        $_args = $script:args                                # set this to something other than $script:args if you want to use this inside of the script.
        $_ret  = @{}         
        foreach ($_arg in $_args) {
            if ($_arg.substring(0,1) -eq '-') {
                $_key = $_arg; [void]$foreach.moveNext()     # set the key (i.e. -a, -b) and moves to the next element in $args, or the tasks to do for that switch
                while ($_arg.substring(0,1) -ne '-') {       # goes through each task until it hits another switch
                    $_val = $_arg
                    switch($_key)    {
                         '-a'     {
                              write-host "doing stuff for $_key"
                              $ret.add($_key,$_val)          # puts the arg entered and tasks to do for that arg.
                         }
    
                         # put more conditionals here
                    }
                }
            }
        }
     }
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      param(
          [string[]]$a,   
          [string[]]$d
      )
      
      write-host $a
      write-host ----
      write-host $d
      

      那你可以拨打DoTheTask -a task1,task2 -d machine1,machine2

      【讨论】:

      • manojlds : DoTheTask -a task1,task2 -d machine1,machine2 这工作正常。有没有一种方法可以在没有 , (逗号)分隔的情况下给出格式。示例:DoTheTask -a task1 task2 -d machine1 machine2 machine3
      • 我冒昧地尝试一个答案:这是可行的,但相当棘手。查看$MyInvocation 变量。使用其属性LineBoundParameters 和/或UnboundArguments 应该可以让您完全按照自己喜欢的方式解析参数。
      • 我强烈建议您不要尝试修改 PowerShell 的语法。
      【解决方案3】:

      你能不能把你的任务名称和机器名称组织成一个带分隔符的字符串。

      换句话说,你的 -a 参数可以是一个逗号分隔的任务名称的字符串,而你的 -d 参数是一个逗号分隔的机器名称字符串吗?如果是这样,那么您需要做的就是在脚本开始时将字符串解析为其组件。

      【讨论】:

      • 而不是作为字符串传递,然后拆分等,只是作为数组传递。看我的回答。
      猜你喜欢
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      相关资源
      最近更新 更多