Overview
PowerShell functions are helpful in saving time when you have repetitive task(s) to be executed. In this guide we will demonstrate, as to how to construct a “
IF” & “
ELSE” conditional statements.
Applies To
Tested on Windows 10, Windows 2008 R2 and Windows 2012.
Pre-Requisites
Launch PowerShell Command Console or PowerShell ISE.
To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or “Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”.
Each Policy type and its purpose is shown in the below table.
Policy Type |
Purpose |
Restricted |
No scripts can be run. Windows PowerShell can be used only in interactive mode. |
AllSigned |
Only scripts signed by a trusted publisher can be run. |
RemoteSigned |
Downloaded scripts must be signed by a trusted publisher before they can be run. |
Unrestricted |
No restrictions; all Windows PowerShell scripts can be run. |
PowerShell Script – Function
This PowerShell script call function without any function arguments / parameters.
Code Snippet
#
# Simple Function with one Mandatory Argument Value
#
function MandatoryParameter
{
param(
[Parameter(Mandatory=$True, Position=1)]
[ValidateNotNullOrEmpty()]
[string]$Parameter_Position_One
)
Clear-Host
Write-Host "`nParameter Value that was passed : $Parameter_Position_One`n"
[console]::beep(500,300)
}
PowerShell Script – Function
This PowerShell script call function with function’s mandatory argument / parameter value, when the argument value is passed; Passed value will be displayed else an exception will be thrown.
Code Snippet – IF Statement
The code snippet is for demonstrating
“IF” Statement / condition only.
#
# Simple Conditional Statements - IF
#
Clear-Host
$Input=Read-Host "Key-In Input"
if ($Input -ne "") {
Write-Host "`nValid Input, Keyed Input String:" $Input -ForegroundColor Green
[console]::Beep(500,600)
}
PowerShell Output – IF Condition
When Input text is provided upon execution of the script;
PowerShell Output – IF Condition – No Input
When
“NO” Input text is provided upon execution of the script; script will simply execute and exit.
Code Snippet – IF & ELSE Statement
The code snippet below is for demonstrating
“IF” and
“ELSE” statement.
#
# Simple Conditional Statements - IF & Else
#
Clear-Host
$Input=Read-Host "Key-In Input"
if ($Input -ne "") {
Write-Host "`nValid Input, Keyed Input String:" $Input -ForegroundColor Green
[console]::Beep(500,600)
} else {
Write-Host "Invalid Input" -ForegroundColor Red
[console]::Beep(900,600)
}
PowerShell Output – IF & ELSE Condition
When Input text is provided upon execution of the script;
PowerShell Output – IF & ELSE Condition – No Input
When
“NO” Input text is provided upon execution of the script; script will simply execute and message will be displayed as shown below.
SlideShare Information
A step by step guide is uploaded to slideshare.
No comments:
Post a Comment