Powershell - Quick Guide

Windows PowerShell is a command-line shell and scripting language designed especially for system administration. It's analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment.
Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system.
In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more.
The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.
You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint.
There are a lot of PowerShell commands and it is very difficult to put in all these commands in this tutorial, we will focus on some of the most important as well as basic commands of PowerShell.
The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter.
PowerShell Icon can be found in the task bar and in the start menu. Just by clicking on the icon, it will open.
To open it, just click on the icon and then the following screen will open and it means that PowerShell is ready for you to work on.
The latest version of PowerShell is 5.0 and to check what is installed in our server we type the following command – :$PSVersionTable as shown in the following screenshot and from the screen we also know that we have PSVersion 4.0
To update with the latest version where it has more Cmdlets we have to download Windows Management Framework 5.0 from the following link − https://www.microsoft.com/en-us/download/details.aspx?id=50395 and install it.
The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.
You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint.
To open it you just go to Start - Search and then Type - PowerShell as shown in the following screenshot.
Then click on Windows PowerShell ISE. Or click on the downward Arrow as shown in the following screenshot.
It will list all the applications installed on the server and then click on Windows PowerShell ISE.
The following table will be open −
It has three sections, which include - The PowerShell Console with number 1, then Scripting File number 2 and the third is the Command Module where you can find the module.
While creating the script you can run directly and see the result like the following example −
There are a lot of PowerShell commands and it is very difficult to put in all these commands in this tutorial, we will focus on some of the most important as well as basic commands of PowerShell.
The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter.
To get the list of Updates −
Get-HotFix and to install a hot fix as follows
Get-HotFix -id kb2741530
A cmdlet or "Command let" is a lightweight command used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets at command prompt. You can create and invoke them programmatically through Windows PowerShell APIs.
Cmdlets are way different from commands in other command-shell environments in the following manners −
Cmdlets are .NET Framework class objects; and not just stand-alone executables.
Cmdlets are .NET Framework class objects; and not just stand-alone executables.
Cmdlets can be easily constructed from as few as a dozen lines of code.
Cmdlets can be easily constructed from as few as a dozen lines of code.
Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime.
Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime.
Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining. 
Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining. 
Cmdlets are record-based as they process a single object at a time.
Cmdlets are record-based as they process a single object at a time.
The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter.
Following are the examples of powershell scripts on Files and Folders.
Example Script to show how to create folder(s) using PowerShell scripts.
Example Script to show how to create file(s) using PowerShell scripts.
Example Script to show how to copy file(s) using PowerShell scripts.
Example Script to show how to create file(s) using PowerShell scripts.
Example Script to show how to delete folder(s) using PowerShell scripts.
Example Script to show how to delete file(s) using PowerShell scripts.
Example Script to show how to move folder(s) using PowerShell scripts.
Example Script to show how to move file(s) using PowerShell scripts.
Example Script to show how to rename folder(s) using PowerShell scripts.
Example Script to show how to rename file(s) using PowerShell scripts.
Example Script to show how to retrieve item(s) using PowerShell scripts.
Example Script to show how to check folder existence using PowerShell scripts.
Example Script to show how to check file existence using PowerShell scripts.
Following are the examples of powershell scripts on System Date and Time.
Example Script to show how to get system date using PowerShell scripts.
Example Script to show how to set system date using PowerShell scripts.
Example Script to show how to get system time using PowerShell scripts.
Example Script to show how to set system time using PowerShell scripts.
Following are the examples of powershell scripts of creating and reading different types of files.
Example Script to show how to create a text file using PowerShell scripts.
Example Script to show how to read a text file using PowerShell scripts.
Example Script to show how to create a XML file using PowerShell scripts.
Example Script to show how to read a XML file using PowerShell scripts.
Example Script to show how to create a CSV file using PowerShell scripts.
Example Script to show how to read a CSV file using PowerShell scripts.
Example Script to show how to create a HTML file using PowerShell scripts.
Example Script to show how to read a HTML file using PowerShell scripts.
Example Script to show how to erase file contents using PowerShell scripts.
Example Script to show how to append text to a file contents using PowerShell scripts.
A cmdlet or "Command let" is a lightweight command used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets at command prompt. You can create and invoke them programmatically through Windows PowerShell APIs. Following are advanced usage example of cmdlets.
Example program to showcase Get-Unique Cmdlet.
Group-Object Cmdlet
Example program to showcase Group-Object Cmdlet.
Example program to showcase Measure-Object Cmdlet.
Example program to showcase Compare-Object Cmdlet.
Example program to showcase Format-List Cmdlet.
Example program to showcase Format-Wide Cmdlet.
Example program to showcase Where-Object Cmdlet.
Example program to showcase Get-ChildItem Cmdlet.
Example program to showcase ForEach-Object Cmdlet.
Example program to showcase Start-Sleep Cmdlet.
Example program to showcase Read-Host Cmdlet.
Example program to showcase Select-Object Cmdlet.
Example program to showcase Sort-Object Cmdlet.
Example program to showcase Write-Warning Cmdlet.
Example program to showcase Write-Host Cmdlet.
Example program to showcase Invoke-Item Cmdlet.
Example program to showcase Invoke-Expression Cmdlet.
Example program to showcase Measure-Command Cmdlet.
Example program to showcase Invoke-History Cmdlet.
Example program to showcase Add-History Cmdlet.
Example program to showcase Get-History Cmdlet.
Example program to showcase Get-Culture Cmdlet.
Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment.
Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system.
In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more. Windows PowerShell Scripting is a fully developed scripting language and has a rich expression parser/
Cmdlets − Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI).
Cmdlets − Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI).
Task oriented − PowerShell scripting language is task based and provide supports for existing scripts and command-line tools.
Task oriented − PowerShell scripting language is task based and provide supports for existing scripts and command-line tools.
Consistent design − As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation.
Consistent design − As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation.
Simple to Use − Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation.
Simple to Use − Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation.
Object based − PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly.
Object based − PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly.
Extensible interface. − PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software.
Extensible interface. − PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software.
PowerShell variables are named objects. As PowerShell works with objects, these variables are used to work with objects.
Variable name should start with $ and can contain alphanumeric characters and underscore in their names. A variable can be created by typing a valid variable name.
Type the following command in PowerShell ISE Console. Assuming you are in D:\test folder.
$location = Get-Location
Here we've created a variable $location and assigned it the output of Get-Location cmdlet. It now contains the current location.
Type the following command in PowerShell ISE Console.
 $location
You can see following output in PowerShell console.
Path                                                                                    
----                                                                                    
D:\test                                                                                 

Get-Member cmdlet can tell the type of variable being used. See the example below.
 $location | Get-Member
You can see following output in PowerShell console.
   TypeName: System.Management.Automation.PathInfo

Name          MemberType   Definition                                               
----          ----------   ----------                                               
Equals        Method       bool Equals(System.Object obj)                           
GetHashCode   Method       int GetHashCode()                                        
GetType       Method       type GetType()                                           
ToString      Method       string ToString()                                        
Drive         Property     System.Management.Automation.PSDriveInfo Drive {get;}    
Path          Property     System.String Path {get;}                                
Provider      Property     System.Management.Automation.ProviderInfo Provider {get;}
ProviderPath  Property     System.String ProviderPath {get;}

PowerShell Special variables store information about PowerShell. These are also called automatic variables. Following is the list of automatic variables −
PowerShell provides a rich set of operators to manipulate variables. We can divide all the PowerShell operators into the following groups −
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Redirectional Operators
Spilt and Join Operators
Type Operators
Unary Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −
Show Examples
Following are the assignment operators supported by PowerShell language −
Assume integer variable A holds 10 and variable B holds 20, then −
Show Examples
Following are the assignment operators supported by PowerShell language −
Show Examples
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
Following are various important operators supported by PowerShell language −
Show Examples
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
PowerShell programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Enhanced for loop. This is mainly used to traverse collection of elements including arrays.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Like a while statement, except that it tests the condition at the end of the loop body.
Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
PowerShell scripting language provides following types of decision making statements. Click the following links to check their detail.
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
You can use one if or elseif statement inside another if or elseif statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
PowerShell provides a data structure, the array, which stores a fixed-size sequential collection of elements of the any type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables or objects.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you can specify the type of array the variable can reference. Here is the syntax for declaring an array variable −
$A = 1, 2, 3, 4
or
$A = 1..4  

Note − By default type of objects of array is System.Object. GetType() method returns the type of the array. Type can be passed.
The following code snippets are examples of this syntax −
[int32[]]$intA = 1500,2230,3350,4000

$A = 1, 2, 3, 4
$A.getType()
This will produce the following result −
IsPublic    IsSerial    Name                        BaseType                     
--------    --------    ----                        --------                     
True        True        Object[]                    System.Array 

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Here is a complete example showing how to create, initialize, and process arrays −
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123

write-host("Print all the array elements")
$myList

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

write-host("Get Second element of array")
$myList[1]

write-host("Get partial array")
$subList = $myList[1..3]

write-host("print subList")
$subList

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

write-host("using forEach Loop")
foreach ($element in $myList) {
   $element
}

write-host("using while Loop")
$i = 0
while($i -lt 4) {
   $myList[$i];
   $i++
}

write-host("Assign values")
$myList[1] = 10
$myList
This will produce the following result −
Print all the array elements
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
Get the length of array
10
Get Second element of array
4.5
Get partial array
print subList
4.5
3.3
13.2
using for loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using forEach Loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using while Loop
5.6
4.5
3.3
13.2
Assign values
5.6
10
3.3
13.2
4
34.33
34
45.45
99.993
11123

Here is a complete example showing operations on arrays using its methods
$myList = @(0..4)

write-host("Print array")
$myList

$myList = @(0..4)

write-host("Assign values")
$myList[1]  = 10
$myList
This will produce the following result −
Clear array
Print array
0
1
2
3
4
Assign values
0
10
2
3
4

Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys.
This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods.
To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable −
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{} 

Note − Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not.
The following code snippets are examples of this syntax −
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}
Print the hashtable.
$hash
Name                           Value    
----                           -----                                                    
ID                             1                                                        
Color                          Blue                                                     
Shape                          Square 

The hashtable values are accessed through the keys.
> $hash["ID"]
 1
Dot notation can be used to access hashtables keys or values.
> $hash.keys
ID
Color
Shape

> $hash.values
1
Blue
Square
Here is a complete example showing how to create, initialize, and process hashtable −
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}

write-host("Print all hashtable keys")
$hash.keys

write-host("Print all hashtable values")
$hash.values

write-host("Get ID")
$hash["ID"]

write-host("Get Shape")
$hash.Number

write-host("print Size")
$hash.Count

write-host("Add key-value")
$hash["Updated"] = "Now"

write-host("Add key-value")
$hash.Add("Created","Now")

write-host("print Size")
$hash.Count

write-host("Remove key-value")
$hash.Remove("Updated")

write-host("print Size")
$hash.Count

write-host("sort by key")
$hash.GetEnumerator() | Sort-Object -Property key
This will produce the following result −
Print all hashtable keys
ID
Color
Shape
Print all hashtable values
1
Blue
Square
Get ID
1
Get Shape
print Size
3
Add key-value
Add key-value
print Size
5
Remove key-value
print Size
4
sort by key

Name                           Value                                                                                                   
----                           -----                                                                                                   
Color                          Blue                                                                                                    
Created                        Now                                                                                                     
ID                             1                                                                                                       
Shape                          
Square    

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.
Here is the table listing down all the regular expression metacharacter syntax available in PowerShell −
Here is a complete examples showing how to use regex in PowerShell;
Example of supported regular expression characters.
Example of supported character classes.
Example of supported quantifiers.
Backtick (`) operator is also called word-wrap operator. It allows a command to be written in multiple lines. It can be used for new line (`n) or tab (`t) in sentences as well. See the examples below −
Get-Service * | Sort-Object ServiceType `
| Format-Table Name, ServiceType, Status -AutoSize
It will become 
Get-Service * | Sort-Object ServiceType | Format-Table Name, ServiceType, Status -AutoSize
Verify the output as
Name                                                   ServiceType  Status
----                                                   -----------  ------
MSSQLServerADHelper100                             Win32OwnProcess Stopped
ntrtscan                                           Win32OwnProcess Running
...

Use of new line and tab.
> Write-host "Title Subtitle"
Title Subtitle

> Write-host "Title `nSubtitle"
Title 
Subtitle

> Write-host "Title `tSubtitle"
Title   Subtitle
Powershell supports three types of brackets.
Parenthesis brackets. − () 

Parenthesis brackets. − () 
Braces brackets. − {} 

Braces brackets. − {} 
Square brackets. − [] 

Square brackets. − [] 
This type of brackets is used to
pass arguments
pass arguments
enclose multiple set of instructions
enclose multiple set of instructions
resolve ambiguity
resolve ambiguity
create array
create array
> $array = @("item1", "item2", "item3")
 
> foreach ($element in $array) { $element }
item1
item2
item3
This type of brackets is used to
enclose statements
enclose statements
block commands
block commands
$x = 10

if($x -le 20){
   write-host("This is if statement")
}
This will produce the following result −
This is if statement.

This type of brackets is used to
access to array
access to array
access to hashtables
access to hashtables
filter using regular expression
filter using regular expression
> $array = @("item1", "item2", "item3")
 
> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
item1
item2
item3
 
>Get-Process [r-s]*
 Handles    NPM(K)     PM(K)    WS(K)   VM(M)   CPU(s)     Id    ProcessName
-------    ------     -----     -----   -----   ------     --    -----------  
    320        72     27300     33764    227     3.95    4028    SCNotification 
   2298        77     57792     48712    308             2884    SearchIndexer
   ...
PowerShell alias is another name for the cmdlet or for any command element.
Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help for Get-Help cmdlet.
 New-Alias -Name help -Value Get-Help  
Now invoke the alias.
 help Get-WmiObject -Detailed  
You will see the following output.
NAME
   Get-WmiObject
    
SYNOPSIS
   Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.    
    
SYNTAX
   Get-WmiObject [
...

Use get-alias cmdlet to get all the alias present in current session of powershell.
 Get-Alias
You will see the following output.
CommandType     Name                     Definition
-----------     ----                     ----------  
Alias           %                        ForEach-Object
Alias           ?                        Where-Object
Alias           ac                       Add-Content
Alias           asnp                     Add-PSSnapIn 
...


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page