NTRODUCTION TO THE WINDOWS POWERSHELL IF -AND STATEMENT
One of the best statements for filtering data is the ‘If’ clause. For scripts that require precise flow control you could incorporate PowerShell’s -And, the benefit is that your test could now include multiple conditions.
TOPICS FOR POWERSHELL’S IF -AND STATEMENT
- PowerShell ‘If’ Statement
- Example 1: Basic ‘If’ Test
- Example 2: PowerShell If -And Script
- Example 3: PowerShell -And Statement
- Example 4: PowerShell If -Or Example
- PowerShell If -Not
- Summary of PowerShell’s If And Construction
INTRODUCTION TO THE POWERSHELL ‘IF’ -AND STATEMENT
The key point is that you only need one ‘If’.
If (condition1 -And condition2) {Do stuff}
# An alternative explanation would be
If (test1 -And test2) {
execute block command when true
}
Summary: The PowerShell ‘If’ conditionally executes a statements, depending on the truth of the test expression.
EXAMPLE 1: BASIC ‘IF’ TEST
If you are new to PowerShell’s implementation of If statement then it’s worth starting with a plain ‘If’ flow control before adding -And.
$Calendar = Get-Date
If ($Calendar.Month -eq '5') {"This month is May"}
Else {"Not May"}
LEARNING POINTS
Note 1: Trace the construction, and separate into two components: if (test) and {what to do}.
Note 2: Avoid over-think; there is no ‘Then’ in a PowerShell ‘If’ statement. My advice is that instead of worrying about ‘Then’, pay close attention to the two types of bracket. Furthermore, there is no endif in PowerShell as there is in VBScript.
Note 3: To double check your understanding, try amending, $Calendar.Month -eq ‘5’ to a different number, such as: ’12’. Once you have done that, change: Else {something different}.
EXAMPLE 2: POWERSHELL IF -AND SCRIPT
The purpose of this script is merely to test different dates and compare them with today’s date, which is held by the variable $Calendar.
# PowerShell If AND Statement Simple Example
Clear-Host
$Calendar = Get-Date
If ($Calendar.Day -eq '25' -And $Calendar.Month -eq '12') {
"Christmas Day"
}
Else {
"It's not Christmas yet! " + $Calendar.Month +"/" +$Calendar.Day
}
MULTIPLE -AND CONDITIONS
Once your flow control works with one -And, it’s straightforward (if a little clumsy) to append more -And conditions. Avoid ‘overthink’, you only need one set of (parenthesis brackets).
Here is an additional example with a few more statements containing -And
Clear-Host
$Calendar = Get-Date
If ($Calendar.day -eq '25' -And $Calendar.Month -eq '12') {"Christmas Day"}
ElseIf ($Calendar.day -eq '4' -And $Calendar.Month -eq '7') {"4th of July"}
ElseIf ($Calendar.day -eq '1' -And $Calendar.Month -eq '5') {"May Day"}
Else {"It's not Christmas today!"}
Note 4: Pay close attention to the (first parenthesis). In particular find the two tests: “.day -eq ’25’ “, also “.Month -eq ’12’ “. My first point is they are separated by -And. My second point is there is only one set of (condition brackets).
Note 5: I included a few ElseIfs and a final Else statement to give the script a little more context, and to give ideas for modifying your scripts.
GUY RECOMMENDS: FREE WMI MONITOR FOR POWERSHELL (FREE TOOL)
Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems. Fortunately, SolarWinds have created a Free WMI Monitor for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts.
Take the guesswork out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.
EXAMPLE 3: POWERSHELL -AND STATEMENT
Here is an example using logic to check whether you have a standard installation of your Microsoft Windows operating system.
Clear-Host
If ($env:SystemDrive -eq "C:" -And $env:SystemRoot -eq "C:\Windows")
{
"This looks like a standard Windows installation"}
Else { "Non standard Windows installation" }
Note 5: There are no commas in this construction, in particular, there is no special syntax before the -And.
EXAMPLE 4: POWERSHELL -OR EXAMPLE
The reason for including this example is that -Or follows the same pattern as PowerShell’s -And.
While this script is designed to test the tiny ‘-Or’ syntax, it has lots of extraneous code which changes the startupType to manual. The sole purpose of this convoluted layout is so that you can check the logic and thus understand how -Or works in PowerShell.
Clear-Host
$NameSrv = 'Spooler'
Set-Service $NameSrv -startupType manual
$Service = Get-WmiObject win32_service -filter "NAME = '$NameSrv'"
$Service | Ft Name, Startmode
if ($Service.Startmode -eq "Manual" -Or $Service.Startmode -eq "Disabled") {
Set-Service $NameSrv -startuptype Automatic }
$Service = Get-WmiObject win32_service -filter "NAME = '$NameSrv' "
$Service | Ft Name, Startmode
Production script:In real life you may want to strip the code down, and append a command to actually start the spooler service.
$Service = Get-WmiObject win32_service -filter "NAME = 'Spooler'"
if ($Service.Startmode -eq "Manual" -Or $Service.Startmode -eq "Disabled") {
Set-Service 'Spooler' -startuptype Automatic }
Start-Service 'Spooler'
Note 6: It’s always difficult to get the balance between example scripts that illustrate a point and those that do useful work.
GUY RECOMMENDS: NETWORK PERFORMANCE MONITOR (FREE TRIAL)
SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.
What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.
RESEARCHING POWERSHELL’S IF -AND
For more information refer to the built-in About_If file
Get-Help About_If
SUMMARY OF POWERSHELL’S IF -AND CONSTRUCTION
When it comes to filtering output, one of the oldest and best statements is the ‘If’ clause. As usual, the secret of understanding the syntax is to pay close attention to the style bracket. If (parenthesis for the test) and {braces for the action}. Once you have mastered the basic ‘If’ statement, then extend your capabilities by introducing ‘-And’.
If you like this page then please share it with your friends
No comments:
Post a Comment
Note: only a member of this blog may post a comment.