Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PowerShell

A Quick guideline for Microsoft Windows PowerShell Part-1.

4.88/5 (29 votes)
22 Aug 2010CPOL11 min read 114.6K  
The objective of this article (Part-1) is to introduce you with Microsoft Windows PowerShell.

Table of Contents

  • Introduction
  • Features of PowerShell
  • Common uses of PowerShell
  • Begin to learn Windows PowerShell
  • How to run your first PowerShell script
    • Variable declaration
    • Arrays
    • Associative Arrays
    • Loops
      • For statement
      • Foreach statement
      • While statement
  • Operators in Windows PowerShell
    • The logical operator table
    • The comparision operators table
    • If,else statement
      • Logical "and"
      • Logical "or"
      • Logical "not"
      • Logical "not equal"
  • Functions or methods
  • Commands
  • VB Script to PowerShell (Part-2)
  • Work with various objects (Part-3)
  • Work with .Net library (Part-4)  
  • Point of Interest
  • References
  • Conclusion
  • History

Introduction

The objective of this article (Part-1) is to introduce you with Microsoft Microsoft Windows PowerShell, We will learn some basic of windows PowerShell, For example: how to write your first PowerShell script, how to use Microsoft .Net library in your PowerShell script and some other stuff as well.

So, let’s start, at first we need to know what is Windows PowerShell? The answer is very simple,
PowerShell is a programming language like other programming language. The PowerShell language is similar to Perl. This is important that the PowerShell is an object-oriented language and interactive command line shell for Microsoft Windows Platforms.

Features of PowerShell

One of the great features of PowerShell is the integration with the Microsoft .Net environment & also can be implanted within other applications. Microsoft Windows PowerShell was specially design to automate system task and create system management tools for commonly implemented process.

The Microsoft windows PowerShell provides a number of ways to automate job, including:

  • Cmdlets, which are very small .NET classes that appear as system commands.
  • Scripts, which are combinations of cmdlets and associated logic.
  • Executables, which are standalone tools.
  • Instantiation of standard .NET classes.

For more information can be found from the links are listed below:

Common uses of PowerShell

As we know PowerShell is an object-oriented language & allow using Microsoft .Net library, So
we can use the PowerShell script in quite a lot of ways; some of the common uses are listed below:

  • Windows Active Directory.
  • Document management / File processing.
  • Network monitor.
  • Working with Xml.
  • Working with Microsoft Office system.
  • Working with Microsoft SQL server.
  • Working with Microsoft SharePoint.
  • Working with Microsoft Exchange Server.
  • Etc.

How to run your first PowerShell script

This is important that don't compare PowerShell script is like as VB script, we know the we can run vb script by double clicking the *.vbs file or from batch file. The PowerShell script can be run from the power shell command prompt or you can also run the script from windows batch file with the valid command. The figure below show how to write a script & run as well.

Figure- A (Windows PowerShell ISE- editor)

PowerShellWindow.png

Note: Windows 7 platform.

Begin to learn

Well, I hope that you dig up some basic information of windows PowerShell. So let’s start:
In this section we will learn the basic for writing PowerShell Script, such as variable declaration,
assign values and play with the variables, create & access object from Microsoft .Net library etc.

Variable declaration

All the variable in PowerShell script begin with the $ sign. For example, we want to add two integer value and assign to another variable, the script will like

Example:

VBScript
[int]$valA = 2;
[int]$valB = 3;
[int]$valC = 0;
$valC = $valA + $valB;
write-host ("The sum is: " + $valC);
write-host ("The sum is: $valC ");

Output: The sum is: 5*write-host -> command for write output.

Note: PowerShell allow reading value from a variable from double quotes string and also you can declare a variable without data type i.e., $valA = 0; as we do in vbScript isn’t cool.

Arrays

An array is a data structure for storing a collection of data elements of the same type. Windows PowerShell supports data elements, such as string, int (32-bit integer), long (64-bit integer), bool (boolean), byte, and other .NET object types. For example we want to create an integer array and assign values and finally we will display the sum of all the values in the array. The script will be like:

Example:

Create an array named $myArray that contains the ten numeric (int) values:1,2,3,4,5,6,7,8,9,10; 

$myArray = 1,2,3,4,5,6,7,8,9,10;
[int] $sum = 0; 
foreach ($val in $myArray)
{
    write-host ("Index with value:$val");
    $sum = $sum + $val;
}
write-host ("The sum is: $sum");

Output:

Index contain value:1
Index contain value:2
Index contain value:3
Index contain value:4
Index contain value:5
Index contain value:6
Index contain value:7
Index contain value:8
Index contain value:9
Index contain value:10
The sum is: 55

Associative Arrays

PowerShell allow you to work with associative array / array list as like as we do in C#.Net or other available language in Microsoft Visual Studio .Net. An associative array is a compact data structure for storing a collection of keys and values where each key is paired with a value. PowerShell uses the hash table data type for storing the contents of an associative array because this data structure provides a fast lookup mechanism.

For example, we want to create an associative array of countries and assign some value and finally lookup values. The script will be like:

Example:

##Declaration syntax:
$<array name> = @{<keyName = Value>;...}
$countries = @{'88' = 'Bangladesh'; '44' = 'United Kingdom'; '11' = 'United States'; '1' = 'Canada'};
$countries ;

Output:

Name Value
------- -------------------
44 United Kingdom
11 United States
1 Canada
88 Bangladesh

So it is very similar to create and initialize a standard array. However, for an associative array, you must also do the following:

  • Assign a label to each value in the associative array.
  • Append an @ sign to the outside of the array contents.
  • Surround any keys or values that contain spaces with single or double quotes.

Loops

In a loop structure, a computer program that performs a series of instructions repeatedly until some specified condition is satisfied.

For statementThe for statement (also known as a for loop) is a language construct for creating a loop that runs commands in a command block while a specified condition evaluates to true.

A typical use of the for loop is to iterate an array of values and operate on a subset of these values. In most cases, if you want to iterate all values in an array, consider using a foreach statement.

The following shows the for statement syntax:

for (<init>; <condition>; <repeat>) 
{<command_block>}

For example, the following for statement will continually display the value of the $i variable until you manually break out of the command by pressing Ctrl+C.

for ($i=0; $i<10;$i++)
{Write-Host $i} 
$i = 1
for (;;){Write-Host $i}
Foreach statement

The foreach statement (also known as a foreach loop) is a language construct for stepping through (iterating) a series of values in a collection of items.

The simplest and most typical type of collection to traverse is an array. Within a foreach loop it's common to run one or more commands against each item in an array.

The following shows the foreach syntax:

foreach ($<item> in $<collection>){<command_block>}

For example, the foreach loop in the following example displays the values in an array named $letterArray:

$letterArray = "a","b","c","d"
foreach ($letter in $letterArray)
{
Write-Host $letter
}

In this example, the $letterArray is created and initialized with the string values "a", "b", "c" and "d". Then, the first time the foreach statement runs, it sets the $letter variable equal to the first item in $letterArray ("a"), and then uses the Write-Host Cmdlet to display the letter a. The next time through the loop, $letter is set to "b", and so on.

***Note that the entire foreach statement must appear on a single line to run it as a command at the PowerShell command prompt. This is not the case if you place the command in a .ps1 script file instead.

While statement

The while statement (also known as a while loop) is a language construct for creating a loop that runs commands in a command block as long as a conditional test evaluates to true. The while statement is easier to construct than a for statement because its syntax is less complicated. In addition, it's more flexible than the foreach statement because you specify a conditional test in the while statement to control how many times the loop runs.

The following shows the while statement syntax:

while (<condition>){<command_block>}

When you run a while statement, the Windows PowerShell evaluates the <condition> section of the statement before entering the <command_block> section. The condition portion of the statement resolves to either true or false. As long as the condition remains true, PowerShell reruns the <command_block> section.

The <command_block>} section of the statement contains one or more commands that are run each time the loop is entered or repeated.

For example, the following while statement displays the numbers 1 through 3 if the $val variable has not been created or has been created and initialized to 0.

while($val -ne 3)
{
$val++
Write-Host $val
}

In this example, the condition ($val is not equal to 3) is true while $val = 0, 1, 2. Each time through the loop, $val is incremented by 1 using the ++ unary increment operator ($val++). The last time through the loop, $val = 3. When $val equals 3 the condition statement evaluates to false and the loop exits.

Operators in Windows PowerShell

You can use the if statement to run a code blocks if a specified conditional test evaluates to true. You can also specify one or more additional conditional tests to run if all prior tests evaluate to false. Finally, you can specify an additional code block that is run if no other prior conditional test evaluates to true.

The following shows the if statement syntax:

if (<test1>) 
{<code_block1>}
[elseif (<test2)
{<code_block2>}]
[else
<code_block3>}]

The logical operator table

Microsoft Windows PowesShell logical operator table with description given below.

PowerShell supports the following logical operators:

Operator

Description

Example

Results

-and

logical and

(A -eq A) -and (A -eq B)

false

-or

logical or

(A -eq B) -or (A -eq A)

true

-not

logical not

(1 -eq 1) -and -not (2 -gt 2)

true

!

logical not

(1 -eq 1) -and !(2 -gt 2)

true

The comparison operators table

Microsoft Windows PowesShell comparison operator table with description:

The comparison operators for the shell, by default, the comparison operators are not case sensitive when comparing strings. Case sensitive variants exist for comparison operators as well as explicit case insensitive operators.

-eq

Equal (case insensitive)

-ne

Not equal (case insensitive)

-ge

Greater than or equal (case insensitive)

-gt

Greater than (case insensitive)

-lt

Less than (case insensitive)

-le

Less than or equal (case insensitive)

-like

Wildcard comparison (case insensitive)

-notlike

Wildcard comparison (case insensitive)

-match

Regular expression comparison (case insensitive)

-notmatch

Regular expression comparison (case insensitive)

-replace

Replace operator (case insensitive)

-contains

Containment operator (case insensitive)

-notcontains

Containment operator (case insensitive)

-ieq

Case insensitive equal

-ine

Case insensitive not equal

-ige

Case insensitive greater than or equal

-igt

Case insensitive greater than

-ile

Case insensitive less than or equal

-ilt

Case insensitive less than

-ilike

Case insensitive equal

-inotlike

Case insensitive equal

-imatch

Case insensitive regular expression comparison

-inotmatch

Case insensitive regular expression comparison

-ireplace

Case insensitive replace operator

-icontains

Case insensitive containment operator

-inotcontains

Case insensitive containment operator

-ceq

Equal (case sensitive)

-cne

Not equal (case sensitive)

-cge

Greater than or equal (case sensitive)

-cgt

Greater than (case sensitive)

-clt

Less than (case sensitive)

-cle

Less than or equal (case sensitive)

-clike

Wildcard comparison (case sensitive)

-cnotlike

Wildcard comparison (case sensitive)

-cmatch

Regular expression comparison (case sensitive)

-cnotmatch

Regular expression comparison (case sensitive)

-creplace

Replace operator (case sensitive)

-ccontains

Containment operator (case sensitive)

-cnotcontains

Containment operator (case sensitive)

-is

Is of a type

-isnot

Is not of a type

-as

Is a type, no error if conversion fails

IF, Else Statement

So, We get an idea on how to write if statement, well there is a little question raise up on the conditional operator. The conditional operator in PowerShell is quite different from any other programming language, the table above show the conditional operator detail.

Logical "AND"

In Powershell we cannot write a conditional statement with logical "and" like && in Microsoft Visual C# or AND in Microsoft Visual Basic as well, Windows PowerShell allow to do this like:

Example:

if (($val1 -eq $val2) -and ($val1 -eq "Some value")){ 
Write-Host("Equal");}else{
Write-Host("Not equal");
}
Logical "OR"

We can implenent logical "or" in a conditional statement in Windows PowerShell like:

Example:

if (($val1 -eq $val2) -or ($val1 -eq "Some value")){ 
Write-Host("One condition satisfied.");}else{
Write-Host("Condition not satisfied.");
} 
Logical "NOT"

We can implenent logical "NOT" in a conditional statement in Windows PowerShell like:

Example:

if (($val1 -eq $val2) -not ($val1 = "Some value")){ 
Write-Host("One condition satisfied.");}else{
Write-Host("Condition not satisfied.");
} 
Logical "NOT" Equal

We can implenent logical "NOT" equal in a conditional statement in Windows PowerShell like:

Example:

if (($val1 -eq $val2) -and ! ($val1 = "Some value")){ 
Write-Host("One condition satisfied.");
}else{
Write-Host("Condition not satisfied.");
} 

Function

A function is a named block of code that you can reference within your Windows PowerShell commands. By definition Windows PowerShell function is similar to the other programming language function. The code with in a function will run when you call the function.

So, this is very common that a function can can accept imported values that you specify as arguments when you call the function or accept values that are passed to the function through the current pipeline. The function returns values that can then be assigned to variables or passed to other functions or cmdlets.


To create a regular function or a filter, you must specify several required elements. You can also specify optional elements. The following syntax shows the various components that make up a function definition:

function | filter
[<scope_type>:]<name>
{ param(<param_list>) <script_block> }

A basic function definition consists only of the initial keyword (function or filter), the name of the function or filter, and the script block (enclosed in braces. The following definition defines a regular function that includes only the required elements:

Example:

function HelloWorld 
{
    Write-Host ("Hello World");
}

Points of Interest

Windows PowerShell script for systems tools.

References

  • Microsoft Development Network

Conclusion

I hope this might be helpful to you. Enjoy!

History

  • 16th August 2010: Initial post.
  • 17th August 2010: Update Operators in PowerShell & fix formation issues.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)