Bootstrap FreeKB - PowerShell - Getting Started with command line options and flags
PowerShell - Getting Started with command line options and flags

Updated:   |  PowerShell articles

Let's say you have the following at the very top of your PowerShell script.

param (
    [string]$foo
)
Write-Host "The 'foo' variable contains a value of: '$foo'"

 

By default, parameters are optional. Let's say you run this script and you do not include the -foo option on the command line. In this scenario, the $foo variable will contain no value.

> C:\Users\JohnDoe\example.ps1
The 'foo' variable contains a value of: ''

 

Of course, if you include the -foo option, then the $foo variable will contain a value.

> C:\Users\JohnDoe\example.ps1 -foo bar
The 'foo' variable contains a value of: 'bar'

 

Better you, you can set parameters to be required

param (
    [Parameter(Mandatory=$True,HelpMessage="please enter a value for foo")] 
    [string]$foo
)
Write-Host "The 'foo' variable contains a value of: '$foo'"

 

switch can be used to create a flag. In this example, the $validate flag defaults to false.

param (
    [string]$foo,
    [switch]$validate = $false
)
Write-Host "The 'foo' variable contains a value of: '$foo'"
Write-Host "The 'validate' flag contains a value of: '$validate'"

 

If you run the PowerShell script without any command line options or flags, in this scenario, the $validate flag should return False.

> C:\Users\JohnDoe\example.ps1 -foo bar
The 'foo' variable contains a value of: ''
The 'validate' flag contains a value of: False

 

On the other hand, if you include the -validate flag, then $validate should return True.

> C:\Users\JohnDoe\example.ps1 -foo bar -validate
The 'foo' variable contains a value of: ''
The 'validate' flag contains a value of: True

 

You could then use an if statement to do something base on whether or not the -validate flag was used.

if ($validate -eq $true) {
    Write-Host "its true"
}
else {
    Write-Host "its not true"
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 512c5f in the box below so that we can be sure you are a human.