param ( $Name = $(Read-Host-Prompt'Enter your name'), $Id = $(Read-Host-Prompt'Enter your ID') )
"You are $Name and your ID is $Id"
当您运行以上脚本时,它像 Read-Host 一模一样地显示提示信息。您也可以通过参数执行该脚本:
1
PS> C:\myscript.ps1 –Name test –Id 12
If you do not need custom prompting, you can go even simpler, and declare parameters as mandatory by adding [Parameter(Mandatory)] above each parameter variable. 如果您不需要自定义提示信息,您还可以更加简单,只需要在每个参数变量上加上 [Parameter(Mandatory)] 使它们变为必需参数。
[ValidateScript({ If ($_ -gt10) { throw'You have submitted a value greater than 10. That will not work, dummy!' } Elseif ($_ -lt1) { throw'You have submitted a value lower than 1. That will not work, dummy!' }
PS C:\> $test2 = 11 You have submitted a value greater than 10. That will not work, dummy! At line:5 char:3 + { throw'You have submitted a value greater than 10. That will not work, dummy ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (You have submitted a...not work, dummy!:String ) [], RuntimeException + FullyQualifiedErrorId : You have submitted a value greater than 10. That will not work, dummy! PS C:\> $test2 = -2 You have submitted a value lower than 1. That will not work, dummy! At line:7 char:3 + { throw 'You have submitted a value lower than 1. That will not work, dummy ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (You have submitted a...not work, dummy!:String ) [], RuntimeException + FullyQualifiedErrorId : You have submitted a value lower than 1. That will not work, dummy!