Windows PowerShell – Basic Constructs

Blog Programming


Windows PowerShell is a powerful scripting language and an indispensable platform developed by Microsoft, and meant to be designed mainly for system administration. PowerShell is also helpful for IT professionals to configure, maintain and automate the system through a single interface. PowerShell is built on Windows .NET framework and can be embedded in other applications as well.

First version of PowerShell was released in 2006 for Windows XP, Window server 2003 and window Vista. Currently, the latest version of PowerShell is 5.0 which is delivered with Window 10. It also works with Windows Server 2008 R2, Windows Server 2012 and Windows Server 2012 R2, Windows 7 Service Pack 1 and Windows 8.1.

In this article we’ll majorly focus on the basic but integral constructs of PowerShell script, which is preferably used in a PowerShell script file (.ps1). You may need to use PowerShell Editor, that is PowerShell ISE, albeit you can also use a simple text editor like Microsoft NotePad for this purpose. The scripting constructs like ‘if’ and ‘switch’ statements and loops etc. which are fundamental to almost all programming platforms, are also available in Windows PowerShell so that you can carry out all sorts of administrative tasks with quite ease.

One thing to be noted before we’re going to start learning basic constructs, is that if you encounter an error like “Script not digitally signed…” while you attempt to run a script referred by .ps1 file, the error message could be something like:

The file Filepath.ps1 is not digitally signed. You cannot run this script on the current system…

This is because the execution policy for running the script on Local Machine is set to AllSigned. You can check this by using this cmdlet:

Get-ExecutionPolicy -list

You can bypass this issue for the current PowerShell session by executing the following cmdlet:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy  ByPass

Then you can execute your script file without fear. However, this Execution Policy bypass is set for the current session only – which is safe for you in fact.

Let’s move on and get our feet somewhat wet with what we’re supposed to learn in this article.
 

Simple if Statement:

write-host("`n")
write-host("simple if statement")
write-host("------------")

$x = 60
$y=70
if($x -lt $y){
	write-host("x is smaller than y")
}

Here’s a little elaboration of the above code-snippet. write-host() function is used to print anything on the display screen. “`n” is equivalent to ‘\n‘ character which represents a new-line. PowerShell script provides some other escape-characters as well. Then there’s simple variable initialization. The if statement resembles the ones you may have used in languages of c-family, java or php. However, note that -lt is the operator which means ‘less than’. This operator is equivalent to ‘<‘ operator from other languages. Some commonly used comparison operators are ‘lt‘ which stands for less-than, ‘le‘ which stands for less-than-or-equal-to, ‘gt‘ that stands for greater-than and ‘ge‘ which stands for ‘greater-than-or-equal-to.

$x = 80
$y=70
if($x -lt $y){
	write-host("x is smaller than y")
}else{
	write-host("x is greater than y")
}

 

Compound-if Statement

Compound-if statement constitutes two or more if conditions and executes code blocks based on respective conditions. Hence it enables you to address a situation where you have to perform separate course of actions based on particular conditions. Here’s the code example for you.

write-host("`n")
write-host("compound if statement")
write-host("------------")

$x = 60
$y=30

write-host("x="+$x)
write-host("y="+$y)

if($x -gt $y){
	write-host("x is greater than y")
} elseif($x-lt $y){
	write-host("x is less than y")
}
else
{
	write-host("x is equal to y")
}

Remember, you can add as many ‘elseif‘ conditions as desired, but the conditions are mutually exclusive, means the code block under only one condition, which is true at that time, will execute.
 

switch Statement

switch statement is a clean alternate to the compound-if statement.

write-host("")
write-host("switch statement, a better equivalent of compound-if statement.")
write-host("------------")

$season = 3
switch ( $season )
{
1 { $result = '1st Quarter' }
2 { $result = '2nd Quarter' }
3 { $result = '3rd Quarter' }
4 { $result = '4th Quarter' }
}
write-host($season)
write-host($result)

 

for-loop

The renown for loop executes a code block based on an integer’s lower and upper limits. The loop is normally run on an array of values or objects.

write-host("for loop")
write-host("--------")

$arrDevices = @("Desktop", "Laptop", "Mobile", "Tablet")
for($i = 0; $i -lt $arrDevices.length; $i++)
{
    $arrDevices[$i]
}

Here we build a simple array, $arrDevices and then run ‘for loop’ on it to display its elements one by one.

 

foreach loop

foreach loop does the same thing as the for-loop except it doesn’t require a counter. It rather enumerates all items from the array and performs the designated action.

write-host("`n")
write-host("foreach loop")
write-host("------------")

foreach ($item in $arrDevices)
{
	$item
}

 

while loop

while loop is again the same construct which is used by all known programming languages. It’s execution style resembles ‘for-loop’, however it looks like more cumbersome than for-loop. Anyways, let’s have a look at a simple code example to elaborate while loop.

write-host("`n")
write-host("while loop")
write-host("------------")

$counter = 0;
while($counter -lt $arrDevices.length){
	$arrDevices[$counter]
	$counter += 1
}

 

do…while loop

do…while loop is almost the same as while loop except that the code block must execute unconditionally for the first time and for the subsequent passes it checks for the while condition.

write-host("`n")
write-host("do...while loop")
write-host("------------")

$counter = 0;
do {
	$arrDevices[$counter] 
	$counter += 1
}
while($counter -lt $arrDevices.length)

 

Some Array examples

Arrays are an integral part of almost all programming languages on this planet. They make the life of a programmer far easier especially when used with a loop construct (as explained above). Here are simple usages of how arrays are used and manipulated by using PowerShell script.

It is assumed that you have a basic knowledge of arrays and have some practical knowledge of making use of them in at least one programming language. With that assumption the following examples should prove to be pretty darn simple for you.

write-host("")
write-host("array examples")
write-host("------------")

$NumberList = 10,20,30,40,50,60,70,80,90
write-host("Display all the Array element:")
$NumberList


write-host("")
write-host("Get the length of array:")
$NumberList.Length

write-host("")
write-host("Get fourth element of array")
$NumberList[3]

write-host("")
write-host("Get partial array")
$subList = $NumberList[2..4]
write-host("print subList")
$subList

write-host("")
write-host("using for loop")
for ($i = 0; $i -le ($NumberList.length - 1); $i += 1) {
$NumberList[$i]
}


write-host("")
write-host("Changing some array element values")
$NumberList[3] = 100
$NumberList

Topics Related To PowerShell Techniques:

Windows PowerShell Technique: Get Hard Drive Information
Windows PowerShell Technique: Obtain Network Data
Windows PowerShell Technique: Get CPU Information

Leave a Reply

Your email address will not be published. Required fields are marked *