我正在编写脚本,我想指定参数来执行以下操作:
参数1为动作(检查或杀死) 参数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
)
答案 0 :(得分:1)
为什么要迫使用户猜测期望输入什么? 只是提前告诉他们期望什么。
例如:
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
答案 1 :(得分:0)
快速,肮脏和简单的处理方法是使用参数集。在这种情况下,如果情况不正确,它将默认显示“使用情况”信息。
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
}
}
}