简体   繁体   中英

How do I enforce command line argument checking in PowerShell

Here's my script (test.ps1):

[CmdLetBinding()]

Param
(
    [parameter(Mandatory=$true)][string]$environment,
    [switch][bool]$continue=$true
)

Write-Host $environment
Write-Host $continue

Question:
If I invoke this script by giving an argument which is a substring of the parameter I specified in the script like this: PS> .\\test.ps1 -envi:blah, PowerShell doesn't seem to check the argument name. I want PowerShell to enforce parameter spelling, ie, it should only accept -environment which matches the parameter name in the script. For anything else, it should raise an exception. Is that doable? How do I do that?
Thanks.

It's not pretty, but it will keep you from using anything except -environment as a parameter name.

Param
(
    [parameter(Mandatory=$true)][string]$environment,
    [parameter()]
     [ValidateScript({throw "Invalid parameter. 'environment' required."})]
     [string]$environmen,
    [switch][bool]$continue=$true
)


Write-Host $environment
Write-Host $continue
}

Edit: As Matt noted in his comment the automatic disambiguation will force you to specify enough of the parameter name to find a unique substring match. What I'm doing here is basically giving it a parameter that satisfies all but the last character to prevent using any substring up to the last character (because it's ambiguous), and throwing an error to prevent you from using that.

And, FWIW, that could well be the ugliest parameter validation I've ever done but I don't have any better ideas right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM