George Mihailescu
George Mihailescu

Reputation: 163

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

I want to force users to supply mandatory command-line parameters when running a specific script and to make sure that they mandatory supply all three parameters and if they do not supply all of them, or if any of the parameters is wrong, then to prompt them to do it or to exit the script. I am using the script bellow, but I am still struggling. Can you help?

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" 

Upvotes: 1

Views: 3137

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

I recommend you to omit the Write-Host outputs within your function and to validate the parameters using attributes, for example:

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

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

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

PowerShellalready provides a well-known mechanism for that which experienced user will benefit of. Take a look at about_functions_advanced_parameters to find more attributes.

Upvotes: 3

Related Questions