如何强制用户在 Powershell 中提供命令行参数并提示他们这样做

How to force users to supply command line parameters in Powershell and to prompt them to do it

我想强制用户在 运行 特定脚本时提供强制命令行参数,并确保他们强制提供所有三个参数,如果他们没有提供所有参数,或者如果有的话的参数是错误的,然后提示他们这样做或退出脚本。我正在使用下面的脚本,但我仍在挣扎。你能帮忙吗?

Param(
[Parameter(Mandatory=$True)]
[string]$dbusername="",
[Parameter(Mandatory=$True)]
[string]$password="",
[Parameter(Mandatory=$True)]
[string]$Machine=""
)

if ($dbusername -eq NULL) Write-Host "You must supply a value for -dbusername" -or 
if ($password -eq NULL) Write-Host "You must supply a value for -password" -or 
if ($Machine -eq NULL) Write-Host "You must supply a value for -Machine" 

我建议您省略函数中的 Write-Host 输出并使用属性验证参数,例如:

Param(
    [Parameter(Mandatory=$True)]
    [ValidateNotNullOrEmpty()]
    [string]$dbusername,

    [Parameter(Mandatory=$True)]
    [ValidateNotNullOrEmpty()]
    [string]$password,

    [Parameter(Mandatory=$True)]
    [ValidatePattern("[a-z]*")]
    [ValidateLength(1,15)]
    [string]$Machine
)

PowerShell已经提供了一种众所周知的机制,有经验的用户将从中受益。查看 about_functions_advanced_parameters 以找到更多属性。