【问题标题】:How to get the remaining parameters in PowerShell? [duplicate]如何在 PowerShell 中获取剩余参数? [复制]
【发布时间】:2016-03-31 06:53:45
【问题描述】:

假设您有一个带有可变数量参数的 PowerShell 脚本。您想将任何不是选项的内容视为文件名。在 Bash 中,这很容易:

files=() # Empty array of files

while [ $# -gt 0 ]
do
    case "$1" in
        -option1) do_option1=true ;;
        -option2) option2_flag="$2" shift ;;
        *) # Doesn't match anything else
            files+=("$1") ;;
    esac
    shift
done

使用 PowerShell 的 Param() 的等效代码是什么?它对于消除大部分样板解析代码很有用,但我将如何使用它来解析文件?例如,这有效:

Param(
    [switch]$Option1,
    [string]$Option2,
    [string[]]$Files
);

但您必须调用像script.ps1 the,file,names 这样的脚本才能正确解析它。如果您拨打script.ps1 the file names,它将不会被识别。

我也试过$PSBoundParameters,但也没有用。

为什么会发生这种情况,我该如何解决?谢谢!

【问题讨论】:

  • [Parameter(ValueFromRemainingArguments)]

标签: windows bash powershell scripting windows-10


【解决方案1】:

使用Mandatory=$True 作为文件名参数,使用Mandatory=$False 作为选项。

Param(
    [Parameter(Mandatory=$false)]
    [switch]$Option1,
    [Parameter(Mandatory=$false)]
    [string]$Option2,
    [Parameter(Mandatory=$True)]
    [string[]]$Files
);

所以当你调用你的函数时,你可以这样做

yourFunc "filename" # only pass value for $files
yourFUnc -option1 "value" -option2 "value" -files "value" # pass value to all of your paras

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多