powershell - 具有一个可选参数,需要另一个参数

标签 powershell powershell-2.0

简而言之,如何初始化Powershell脚本的params部分,以便可以使用类似以下的命令行参数

Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]]

因此,只有在定义了-bar后,我才能使用foo2

如果-bar不依赖于-foo2,我可以做
[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]$foo1,

    [string]$foo2,

    [string]$bar
)

但是我不知道该怎么做才能使该从属参数。

最佳答案

我对原始问题的阅读与C.B.的阅读略有不同。从

Get-Foo [-foo1] <foo1Arg> [-foo2 <foo2Arg> [-bar <barArg>]]

第一个参数$ foo1始终是强制性的,而如果指定了$ bar,则也必须指定$ foo2。

所以我的编码方式是将$ foo1放在两个参数集中。
function Get-Foo
{
[CmdletBinding(DefaultParameterSetName="set1")]
param (
    [Parameter(ParameterSetName="set1", Mandatory=$true, Position=0)]
    [Parameter(ParameterSetName="set2", Mandatory=$true, Position=0) ]
    [string]$foo1,
    [Parameter(ParameterSetName="set2",  Mandatory=$true)]
    [string]$foo2,
    [Parameter(ParameterSetName="set2", Mandatory=$false)]
    [string]$bar
)
    switch ($PSCmdlet.ParameterSetName)
    {
        "set1"
        {
            $Output= "Foo is $foo1"
        }
        "set2"
        {
            if ($bar) { $Output= "Foo is $foo1, Foo2 is $foo2. Bar is $Bar" }
            else      { $Output= "Foo is $foo1, Foo2 is $foo2"}
        }
    }
    Write-Host $Output
}

Get-Foo -foo1 "Hello"
Get-Foo "Hello with no argument switch"
Get-Foo "Hello" -foo2 "There is no bar here"
Get-Foo "Hello" -foo2 "There" -bar "Three"
Write-Host "This Stops for input as foo2 is not specified"
Get-Foo -foo1 "Hello" -bar "No foo2" 

运行上面的命令后,您将获得以下输出。
Foo is Hello
Foo is Hello with no argument switch
Foo is Hello, Foo2 is There is no bar here
Foo is Hello, Foo2 is There. Bar is Three
This Stops for input as foo2 is not specified

cmdlet Get-Foo at command pipeline position 1
Supply values for the following parameters:
foo2: Typedfoo2
Foo is Hello, Foo2 is Typedfoo2. Bar is No foo2

关于powershell - 具有一个可选参数,需要另一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11131389/

相关文章:

powershell - 将文件复制到远程服务器,在Powershell中加入本地和远程服务器复制文件的路径时出现问题

Powershell "X509Certificate2Collection"异常调用 "Import"和 "3"参数 : "Cannot find the requested object

powershell - PowerShell进度栏不会消失

powershell - 如何在powershell中获取登录用户的电子邮件

windows - Powershell 确定远程计算机操作系统

python - virtualenv 挂断了安装 setuptools

powershell - 从 AzureAD/Office 365 清除已删除的外部用户失败并出现 UserNotFoundException

Powershell start-job -scriptblock 无法识别同一文件中定义的函数?

Powershell v2.0 模块 : Default Load Path (User/Windows system folder)?

arrays - 我可以创建具有数组属性的自定义 PowerShell 对象吗?