Powershell 动态条件参数

Powershell Dynamic conditional parameters

我正在编写一个脚本,我想指定参数来执行以下操作:

参数 1 是动作(check 或 kill) 参数 2 是计算机名。

如果未指定任何参数,我希望显示我的使用信息 如果指定了参数 1,则仅应提示参数 2。

Param(
    [Parameter(Mandatory=$True,
    HelpMessage="Please Enter an Action. (C)heck, (K)ill, or (?) for usage")]
    [String]$Action,

    [Parameter(Mandatory = $false,
    Helpmessage="Please Enter One or More Hostnames. seperate multiple hostnames with an , EXAMPLE: Hostname1,Hostname2")]
    [ValidateNotNullorEmpty()]
    [String]$Computers 
    )

做事情的快速、肮脏和简单的方法是使用参数集。在这种情况下,如果事情不正确,它将默认显示使用信息。

Function Test {
    [CmdletBinding()]
Param(
    [Parameter(Mandatory=$true, ParameterSetName = "Action",
    HelpMessage="Please Enter an Action. (C)heck, (K)ill, or (?) for usage")]
    [ValidateSet("C","K","?")]
    [Parameter(Mandatory=$false, ParameterSetName = "Usage")]
    [String]$Action,

    [Parameter(Mandatory = $true, ParameterSetName = "Action",
    Helpmessage="Please Enter One or More Hostnames. seperate multiple hostnames with an , EXAMPLE: Hostname1,Hostname2")]
    [ValidateNotNullorEmpty()]
    [String]$Computers 
    )
Process
{
    if($PSCmdlet.ParameterSetName -eq "Usage" -or $Action -eq "?")
    {
        Write-Host "Usage"
    }
    else
    {
        Write-Host "Action"
        Write-Host $Action
        Write-Host $Computers
    }
}
}

为什么要强制用户猜测预期的输入是什么? 只需提前告诉他们期望的内容即可。

例如:

Function Test-DescriptiveUserPrompt
{
    [CmdletBinding()]

    Param
    (
        [ValidateSet('C','K')]
        [string]$Action = $(
        Write-Host '
        Please Enter an Action. (C)heck, (K)ill:   ' -ForegroundColor Yellow -NoNewLine
        Read-Host 
            ),

        [ValidateNotNullorEmpty()]
        [string[]]$Computers = $(
        Write-Host '
        Please Enter One or More Hostnames. separate multiple hostnames with a comma. 
        EXAMPLE: Hostname1,Hostname2:   ' -ForegroundColor Yellow -NoNewLine
        Read-Host 
        )
    )

    Process
    {
            "You choose $Action"
            "You enter the list $Computers"
    }
}


# Results

Test-DescriptiveUserPrompt

        Please Enter an Action. (C)heck, (K)ill:   c

        Please Enter One or More Hostnames. seperate multiple hostnames with a comma. 
        EXAMPLE: Hostname1,Hostname2:   localhost,remotehost
c
localhost,remotehost


Test-DescriptiveUserPrompt -Action C -Computers localhost,remotehost

C
localhost
remotehost