Top 51 PowerShell Examples You Should Learn

This PowerShell tutorial explains, What is Windows PowerShell? What are various tools we can use to write PowerShell script, What are the advantages of using Windows PowerShell? And also this tutorial contains 51 top useful PowerShell examples with scripts.

SharePoint Online tutorial contents:

What is Windows PowerShell?

PowerShell is a scripting language developed by Microsoft designed for system administration. PowerShell, also helpful for IT professionals to configure the system, control and automate the administration of Windows operating system. The PowerShell built the on.Net framework and PowerShell can be embedded in other applications.

Microsoft released the first version of PowerShell in 2006 for Windows XP, Window server 2003 and window Vista. Nowadays we are using the latest version PowerShell 5.0 it is delivered with Window 10 which is by default and one more benefits of the latest version of window PowerShell is, 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

Advantages Of PowerShell

PowerShell is more powerful than the command prompt, it allows function, variable, loop string etc.

  • The command line is a text-based scripting language and PowerShell is an object-oriented Scripting language.
  • The Command line also work with PowerShell editor.
  • We can execute complex Scripting language also in PowerShell.
  • It can automate a lengthy task within a few seconds. Suppose we want to add 500 users to a group. Doing this manually is time-consuming, hectic so we can automate the thing using the more user-friendly PowerShell scripting language.
  • We can reuse the PowerShell code again and again.
  • We can merge the PowerShell script with another script to perform a different task.
  • The PowerShell is handy for working with active directory also.

You may like following PowerShell tutorials:

Editors For PowerShell

These are the editor in which we can write the PowerShell script.

Here I am using PowerShell ISE. PowerShell ISE is a good environment for working with PowerShell commands(the PowerShell Commands are called “cmdlets”).

The output of cmdlets is an array of an object or objects.

The cmdlets are not case sensitive. When we will add more than one string then it should be separated by “;”.

Example:

How to check the latest version of PowerShell install in the server. For checking the version, we need to follow the command “$PSVersionTable”.

how to check PowerShell version in windows 10
how to check PowerShell version in windows 10

I have added the command in PowerShell ISE and Click on run. Now we can able to see all the version which install in the server.

Get-Help: The Get-Help command we can use for checking all PowerShell cmdlets. The Get-Help cmdlet is also helpful about how to give a command and its parameter in PowerShell. We can add this command with another command for Get-Help. For example, if we want to check how the Get-Process command will work, then follow the command: “Get-Help -Name Get-Process”

PowerShell add help to script
PowerShell add help to script

PowerShell Examples

Now we will see 51 very useful PowerShell examples below:

Example-1: Working with Folder Using PowerShell

In the PowerShell article now we are going to see how to work different operation like create a folder, copy folder, delete folder, remove folder using PowerShell.

PowerShell create a folder :

New-Item cmdlets are used to add a new folder in your System. Follow the command:

New-Item -Path 'G:\padmini\NewPowerShellFolder' -ItemType Directory

We need to pass the path in the New-item. “NewPowerShellFolder” is my folder name which we want to create in the mentioned path.

We add “ItemType Directory” because we want to create a directory so we mentioned item type is a directory.

PowerShell create a folder if not exist
PowerShell create a folder if not exist

Now you can find out your new folder(“NewPowerShellFolder”) in G drive.

PowerShell copy folder :

For copy a folder from one drive to another drive we need to use Copy-Item cmdlets.

Here we copy the SourceFolder to DestinationFolder

Copy-Item 'G:\padmini\SourceFolder' 'C:\DestinationFolder'

PowerShell delete folder:

We can remove a folder using Remove-Item cmdlet in PowerShell.

Remove-Item 'C:\DestinationFolder\SourceFolder'

PowerShell move folder:

To move a folder from a directory “Move-Item” cmdlets is used.

Move-Item C:\SourceFolder G:\padmini

PowerShell rename folder:

“Rename-Item” cmdlet is used to rename a folder.

Rename-Item 'G:\padmini\padmini images'

for check the folder exists or not in our drive “Test-Path” cmdlet is used.

Test-Path 'G:\padmini\SiteCollectionFolder'

PowerShell Check a folder exists :

To Check a folder exist or not in PowerShell we can use Test-Path cmdlets.

Test-Path 'G:\padmini\SiteCollectionFolder'

Example-2: Working with File Using PowerShell

Now we are going to discuss how to work with a different operation of the file using PowerShell.

Create New File Using PowerShell:

For creating a file using PowerShell we need to follow the same cmdlets “NewItem”. For the file, we need to mention “ItemType as File”. Pass the location or path where we want to create a file.

I have created the file in ‘G:\padmini\NewPowerShellFolder’ location. The path which we will pass in New-Item is ‘G:\padmini\NewPowerShellFolder\ImportantNoteRelatedToPowerShell.txt’ -ItemType File.

“ImportantNoteRelatedToPowerShell.txt” is my file name and I want to add the file as textbox type.

New-Item -Path 'G:\padmini\NewPowerShellFolder\ImportantNoteRelatedToPowerShell.txt'-ItemType File
PowerShell create a folder if not exist PowerShell create file if not exist
PowerShell create a file if not exist

Copy files from one folder to another using PowerShell script:

 “Copy-Item” cmdlets are used to copy a file from one folder to another folder in PowerShell.

Copy-Item 'G:\padmini\SourceFolder\NewText.txt' 'C:\DestinationFolder\NewText.txt'

In the above script, we need to give two locations and pass to Copy-Item. In the first location where the file is there which we want to copy and in the second location we need to give the location where we want to pass the file.

We need to copy the file from ‘G:\padmini\SourceFolder\NewText.txt’ to ‘C:\DestinationFolder\NewText.txt’ location.

PowerShell copy file from one folder to another
PowerShell copy file from one folder to another

We can able to see the text file is copied in “C:\DestinationFolder” location.

PowerShell Delete File from Folder:

The “Remove-Item” cmdlets are used to delete a file from the folder. To simply delete a file the command is

Remove-Item 'C:\NewFolderForPowerShell\ImportantNoteRelatedToPowerShell.txt'

But if we want to delete the file recursively then use the command

Remove-Item 'G:\padmini\NewPowerShellFolder\ImportantNoteRelatedToPowerShell.txt'-Recurse

PowerShell move file to another folder:

To move a file from one location(folder) to another folder the Move-Item cmdlets is used.

The PowerShell script is :

Move-Item 'G:\padmini\SourceFolder\PSNote.txt' C:\DestinationFolder

The file is copied from ‘G:\padmini\NewPowerShellFolder\Test File.txt’ to ‘c:\NewFolderForPowerShell\Test File.txt’.

Rename File using PowerShell:

For renaming a file the ‘Rename-Item’ cmdlets are used.

Rename-Item 'C:\NewFolderForPowerShell\PowerShell.txt'

We need to give the path where the file exists which we want to change the name. When we will pass the path In “Rename-Item”.It is asking for “Newname:”  in PowerShell console like below. Give the name. Now our file name automatically renamed.

PowerShell rename files in a folder
PowerShell rename files in a folder

Check file is exist or not using PowerShell:

To check a file is exist or not we need to use “Test-Path” cmdlets.

Test-Path 'C:\NewFolderForPowerShell\New File.txt'

In the OutPut, we can able to see “True”.

Retrieve content from a file using PowerShell:

For retrieving the content from a list “Get-Content” cmdlets is used.

Pass the path of a file in “Get-Content” cmdlets.

We will get all the value of the file.

PowerShell check if the file exists
PowerShell check if the file exists
PowerShell get-content
PowerShell get-content

Example-3: PowerShell Get-Date and time and Set-Date and time:

In the PowerShell example, we will discuss how will Get-Date and Set-Date using PowerShell.

Display Current Date in PowerShell:

To get the today’s system date we can use the cmdlets “Get-Date”. The output should be in the format of Day, Date, year time.

powershell get-date timezone
PowerShell get-date timezone
Get-Date

PowerShell Display Only Date:

Suppose we want to see the only date, not time, then use the cmdlets “Get-Date -DisplayHint Date”.

Get-Date -DisplayHint Date

The OutPut:

Tuesday, September 25, 2018

Like the above, if we want to display only time then use “Get-Date -DisplayHint Time”

PowerShell display date and time in the shortcut:

When we want to see the date and time in shortcut format go for the cmdlets:

Get-Date -Format g

OutPut:

9/25/2018 4:50 PM

In the “Get-Date -Format g” the .net Framework is used.

PowerShell Date Format yy/mm/dd/offset from UTC:

In PowerShell, we can also see the system time in year(full year)/month(two digits numeric month)/day(day in the week)/offset from UTC. The cmdlets we can use:

Get-Date -UFormat "%Y / %m / %d / %A / %Z"

OutPut is:

2018 / 09 / 25 / Tuesday / +05

PowerShell get Day of Year:

When we want to know one date number of position in 365 we need to follow the cmdlets:

(Get-Date - the Year 2018 -Month 9 -Day 25).DayOfYear

OutPut:

268

(Get-Date – the Year 2018 -Month 9 -Day 25).DayOfYear is used to count the day of the year for the current date.

25 September 2018 is the 268 number day in the year 2018. We all know the year contains 365 days from there today’s date is 268.

PowerShell Convert Date and Time To UTC Time:

To convert the current date and time to UTC the cmdlets used:

$a = Get-Date
$a.ToUniversalTime()

OutPut:

Tuesday, September 25, 2018, 12:14:23 PM

Here we declare a variable:

We can declare a variable using the $ symbol. By using the Get-Date cmdlets we can able to find out today’s date and the value is stored in the $a variable. To convert the current date t0 UTC.

$a.ToUniversalTime()

 PowerShell Set System Date:

We can set the system date and time using PowerShell.

set-date -date "06/08/2019 18:53"

OutPut:

Saturday, June 8, 2019, 6:53:00 PM

Adding Dates with PowerShell:

We can add the date to the system date. Here I want to add 4 days with system days.

Set-Date -Date (Get-Date).AddDays(5)

Output:

In the output, we can able to see what is the date after 5 days

Sunday, September 30, 2018 6:10:46 PM

PowerShell set System Clock  back 15 minutes:

Set the System Clock back 15minutes:

By using the “Set-Date -Adjust -0:15:0 -DisplayHint Time” we can set the system time 15 minutes back.

Set-Date -Adjust -0:15:0 -DisplayHint Time

OutPut:5:54:23 PM

PowerShell add minutes to System clock:

When we add the below cmdlets automatically 150 minutes add to the System clock.

$a = New-TimeSpan -Minutes 150
Set-Date -Adjust $a

OutPut:

Tuesday, September 25, 2018, 10:04:41 PM

Example-4: PowerShell Create and read XML file

In the PowerShell Tutorial now we will see how to create and read an XML file.

PowerShell Create a New XML file:

For creating an XML file following the same cmdlets which we were using creating a text file but when we need to give the file name as “.xml” in the path. Remember in the text file we have mentioned the file name with .txt like that for XML file .xml.

Script or cmdlets for creating a New XML file:

New-Item G:\padmini\SourceFolder\NewFile.xml -ItemType File
PowerShell write an XML file
PowerShell write an XML file

PowerShell Add Content to XML file:

To add some content to XML file using PowerShell use the cmdlets:”Set-Content“.

Set-Content G:\padmini\SourceFolder\NewFile.xml '<title>Welcome to Top 51 PowerShell Example</title>'

We need to pass the file location in “Set-Content “, then add the content which we want to add in the file.

Here I have added the content  “Welcome to Top 51 PowerShell Example”  in the title tag.

PowerShell Retrieve Content from the XML file:

Get-Content cmdlets are used to get the content from the XML file. Pass the location of the file in Get-Content.

Get-Content G:\padmini\SourceFolder\NewFile.xml

We can able to see the OutPut in PowerShell console.

Example-5: PowerShell Create HTML and read HTML file

Now we will see how to Create and read an HTML file using PowerShell.

PowerShell Create a New HTML file:

To create file use PowerShell cmdlets “New-Item”. Pass the location to “New-Item”. Add the file type and Item Type File.

Here I want to add the HTML file soI have added “NewHtmlFile.html”.

New-Item G:\padmini\SourceFolder\NewHtmlFile.html -ItemType File

PowerShell Add Content To HTML file:

To add content to a list the Set-Content cmdlets is using. In the Set-Content cmdlets pass the location of HTML file.

In HTML tag add the content which we want to add an HTML file.

Here I have added “Welcome To Top 51 PowerShell Example”.

Set-Content G:\padmini\SourceFolder\NewHtmlFile.html '<html><h1>Welcome To Top 51 PowerShell Example</h1></html>'

Set-Content G:\padmini\SourceFolder\NewHtmlFile.html '<html><h1>Welcome To Top 51 PowerShell Example</h1></html>'Set-Content G:\padmini\SourceFolder\NewHtmlFile.html '<html><h1>Welcome To Top 51 PowerShell Example</h1></html>'

PowerShell Retrive content from HTML file:

To retrive the content from HTML file the Get-Content cmdlets is used. We need to pass the HTML file location in the Get-Content cmdlets.

Get-Content G:\padmini\SourceFolder\NewHtmlFile.html

In the PowerShell console we can able to see the HTML file content.

Example-6: PowerShell create and reads CSV file

In the below example we will discuss how to create and read a CSV file.

PowerShell Create CSV file:

To creating a CSV file the New-Item cmdlets is used as like every file but we need to mention the file type.

Here I am creating a CSV file so I have mentioned “NewCSVfile.csv”.

ew-Item G:\padmini\SourceFolder\NewCSVFile.csv -ItemType File

Just mentioned the file type as the filename. filetype like NewCSVfile.csv.

PowerShell Add Content To CSV file:

To add Content to a CSV file, the “Set-Content” is used. Pass the file location in the Set-Content cmdlets. Directly add the value which you want to add to the CSV file. Here I have added ‘Monday, Sunday, Tuesday’ in the CSV file.

Set-Content G:\padmini\SourceFolder\NewCSVFile.csv 'Monday,Sunday,Tuesday'

PowerShell Retrieve Content From CSV file:

To retrieve the content from CSV file Get-Content cmdlets is used. We need to pass the CSV file location to retrieve the content.

Get-Content G:\padmini\SourceFolder\NewCSVFile.csv

In the Power Console, we can able to see all the content which stored in a CSV file.

Example-7: PowerShell Erase File Content and Append text to a file

In the below example we will see how to erase and append content to a file using PowerShell.

Erasing a Content from a file:

To clear the content from the file the “Clear-Content” cmdlets are used. In the “Clear-Content” cmdlets pass the file location.

Clear-Content G:\padmini\SourceFolder\NewHtmlFile.html

Append Text To A File:

We can set the value in a file using “Set-Content” cmdlets. But when we want to add more text than we can use “Add-Content” cmdlets. Pass the location of a file.

Here I want to add some more text in my HTML file. So I have added the “Add-Content” cmdlets and pass the location of my HTML file and an HTML tag, I have added the content.

Add-Content G:\padmini\SourceFolder\NewHtmlFile.html "<html><h2>PowerShell is a more powerful scripting language</h2></html>"

Example-8: PowerShell get unique values

Below example is describing:

  • Assign a value to a variable in PowerShell
  • PowerShell sort and get a unique value

Assign a value to a variable in PowerShell:

Some rule to declare a variable and assign a value to a variable in PowerShell we should know.

  1. PowerShell variable start with a “$” symbol
  2. PowerShell variable contains a letter, number and underscores only.
  3. We should not use the predefined function as a PowerShell variable name.
  4. We can use the other character which PowerShell is not allowing we can place inside a curly bracket.

Example:

$variableValue

$variableValue_1

$VariableValue

the”-” is not allowed in PowerShell so we can add the variable like below:

${variable-Value}

Assign a value to a variable:

we can assign a value to a PowerShell variable using (=) operator.

$variableValue= 10

We can write $variableValue=$integerValue=$a=1

We can assign a single value to multiple variable.

We can also do assign the value to a variable in a single line like below.

$p,$q,$r=10,34,23

Suppose we take one variable name as listValue and assign some value.

$listValue=123,12345,1234567,123,12345678,124

When we will put $listValue in Power console we can able to see all the value which the variable contains.

PowerShell sort and get unique values:

To get the shorted and unique value to follow the below script.

$listValue| sort | get-unique

First, it shorted all the value then find the unique value and display in PowerShell console.

Example-9: PowerShell measure-object count

We can able to count the number of Lines, Words, Characters Property of a file by using the “Get-Content|measure-object -character -line -word”.

By using the Get-Content cmdlets we can retrieve all the content of the file.

“measure-object -character -line -word” is used to count the character, line, and words of a file. It will work on over “Get-Content”. So we are using “|” here for run two cmdlets at a time.

\PSNote.txt| measure-object -character -line -word

Example-10: PowerShell Get-ChildItem cmdlets

Retrieve all the content of Folder:

To retrieve the content we can use the Get-ChildItem cmdlets it will display all the file and subfolder.

Here I have added the path of the folder in which we want to retrieve the content “Get-ChildItem”, we can able to see in PowerShell console all the file and folder which the “SourceFolder” is contained.

Get-ChildItem G:\padmini\SourceFolder
powershell get-childitem filename
PowerShell get-childitem filename

Retrieve all text file of Folder:

To retrieve all the text file which the folder contains We can able to see in PowerShell console using “Get-ChildItem G:\padmini\SourceFolder *.txt -Recurse -Force”.

These above cmdlets are displayed all the text file which is present in the current folder and subfolder. The recurse parameter is used to get the content recursively and the force parameter displays all the hidden files forcefully.

Get-ChildItem G:\padmini\SourceFolder *.txt -Recurse -Force
PowerShell get-child item txt files only
PowerShell get-child item txt files only

Example-11: PowerShell Compare Two Text File

Two compare two files use the below cmdlets.

Compare-Object -ReferenceObject $(Get-Content G:\padmini\SourceFolder\NewPSNote.txt) -DifferenceObject $(Get-Content G:\padmini\SourceFolder\PSNote.txt)

G:\padmini\SourceFolder\NewPSNote.txt contains:

“PowerShell is a scripting language.
PowerShell supports programming.
PowerShell more potent than command editor.
Welcome to the Top Beautiful PowerShell Example”

G:\padmini\SourceFolder\PSNote.txt:

“PowerShell is a scripting language.
PowerShell supports programming.
PowerShell more potent than command editor.”

The different text line is “Welcome to the Top Beautiful PowerShell Example”

So in the output, we can able to see the difference text line.

PowerShell compare two text files
PowerShell compare two text files

Example-12: PowerShell start-sleep minutes

To stop the PowerShell for some time we can use “StartSleep” cmdlets.

Here I am trying to stop the processing for some second and minutes.

Start-Sleep -m 200//for minutes
Start-Sleep -s 20//for second

Example-13: PowerShell for Loop Example

Basically for Loop is used to execute the block of statement repeatedly when the condition is true.

Syntax for ForLoop:

for (<init>; <condition>; <repeat>)
{code to be execute till the condition is true}
$arrayItem = @("Laptop", "Mobile", "Tablet")
for($i = 0; $i -lt $arrayItem.length; $i++)
{
$arrayItem[$i]
}

In the above script I have taken one array variable(arrayItem) and store some value to the arrayvariable.

@ symbol is specify that we are creating an array.

And I have declared one more variable “i”, check the condition is I less than (-lt) array item length. Up to the condition is true the block of code will execute. The code will stop executing when the condition is false.

In the PowerShell console, we can able to see all the array value.

Example-14: PowerShell forEach Loop Example

In the below script I have added one for each loop example. I have declared a variable ArrayList and assign some value to the variable.

I have declare one more variable $item.

$arrayList = @("Laptop", "Mobile", "Tablet")
foreach ($item in $array)
{
$item
}

Example-15: PowerShell while Loop

In the while loop first we are declaring an array with the varible “arrayItem”.

I have declared on more counter variable and assign 0 value.

while(condition)

The condition is counter is less than the length of $arratItem.

If the condition is true then go for the code to be executed then increment the counter value to one.

$arrayItem = @("Laptop", "Mobile", "Tablet")
$counter = 0;
while($counter -lt $arrayItem.length){
$arrayItem[$counter]
$counter += 1
}

Output:

  • Laptop
  • Mobile
  • Tablet

Example-16: PowerShell do…while Loop

In the below PowerShell do…while Loop I have declare arrayItem variable and store some value Laptop, Mobile and Tablet.

I have declared one more variable named as a counter and assign the value to counter is 0.

In the do part the code is there to execute and increment counter value by 1.

In the while part Condition is there is the counter is less then length of array item.

$arrayItem = @(“laptop”, “Mobile”, “Tablet”)
$counter = 0;

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

Example-17: PowerShell if statement

We all know the if statement is nothing but a collection of boolen expression. We know the boolen statement has only two value either true or false. In the if statemnet if the condition is true then block of code which is inside the curly bracket will execute. The code will not execute if the condition is false.

Here I have declared x and y and assign some value to it.

In the if condition I am just checking that is the x value is less than or equal to y.

If the condition is true go for a block of code which is inside the curly bracket.

If the condition is false then the code will not execute.

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

Example-18: PowerShell if…else statement

In the if else statement when the condition is true then go for the block of code of if part otherwise goes to else part and execute the block of code or else part.

In the below example we checked x is less than equal to y. The statement is false so we need to go for else part.

$x = 60
$y=50
if($x -le $y){
write-host("x is smaller than y")
}
else
{
write-host("x is greater than y")
}

Output:

x is greater than y

Example-19: PowerShell if…elseif…else Statement

In the below example I have discussed the if else if statement in PowerShell.

I have declared two variable x and y assign 30 value to both of it.

First I have checked if x is not equal to y. Then the block of code will execute and write “x not equal to y”.

Else if I have checked that if x value is higher than equal to y. Then display “x greater than y”.

Else if I have checked x is less than equal to y. Then display “x is less than y”.

Else display x is equal to y.

$x = 30
$y=30
if($x -ne $y){
write-host("x not equal to y")
} elseif($x -ge $y){
write-host("x is greater than y")
} elseif($x-le$y){
write-host("x is less than y")
}
else
{
write-host("x is equal to y")
}

Example-20: PowerShell nested if statement

In the nested if ststement we can place a if statement or if else ststement inside a other if statement and if else statement.

Here I have to use the if statement inside another if statement.

I have declared the variable x,y, and z and assign the value to x,y and z variable.

I have checked if x greater than y then go for inside if statement and check if x greater than z. If both the “if statement” are true then display “x is greater than y and z”.

$x = 30
$y = 10
$z =5
if($x -gt $y){
if($x -gt $z) {
write-host(“X is larger than y and z”)
}
}

Example-21: PowerShell switch statement

Switch statement is nothing but a series of if statement. This statement is used for checking multiple condition. We can understand better by the below example.

First  I have declared and assigned a value to a variable(season).

switch($season) means switch(1)

The one value is Winter. The output value will store in the Result variable. Then I have written one statement write-host($result). It will print the result value.

$season = 1
switch ( $season )
{
0 { $result = 'Summer' }
1 { $result = 'Winter' }
2 { $result = 'rain' }
}
write-host($result)

Output: Winter

The collect of value is called case. Here 0,1,2 are case value.

When we want to break the statement we can directly write break statement.

Example-22: PowerShell Array

PowerShell Array is designed to store a collection of the same type of item or a different type of item.

$N=1,2,3,4,5,6

Here I am declaring an Array variable and assign some value. A comma separates the values.

$N=1..6

In PowerShell Array, we can declare and assign the value like 1…6 also.

In the PowerShell array no datatype is mentioned then the PowerShell creates each array as an object array.

Using the GetType method we can able to know the type of array value.

$NumberList = 1,2,3,4,5,6,7,8
write-host("Display all the Array element:")
$NumberList
write-host("Get the length of array:")
$NumberList.Length
write-host("Get fourth element of array")
$NumberList[3]
write-host("Get partial array")
$subList = $NumberList[1..3]
write-host("print subList")
$subList
write-host("using for loop")
for ($i = 0; $i -le ($NumberList.length - 1); $i += 1) {
$NumberList[$i]
}
write-host("Assign values")
$NumberList[1] = 10
$NumberList

OutPut:

Display all the Array element:
1
2
3
4
5
6
7
8
Get the length of array:
8
Get fourth element of array
4
Get partial array
print subList
2
3
4
using for loop
1
2
3
4
5
6
7
8
Assign values
1
10
3
4
5
6
7
8

Example-23: PowerShell Alias

Alias is nothing but an alternative name for cmdlets. In the below example I have created a new name for Get-Help cmdlets. I have created an alias named as “PowerShell command”.

New-Alias -Name PowerShellCommand -Value Get-Help
PowerShell command

In PowerShell, some default shortcut name or alias is there. We can able to know all the shortcut cmdlets by using Get-alias cmdlets.

Get-alias

Example-24: PowerShell Hashtable

Hashtables is nothing but an array but we can store paired key and value. Basically, the object that is used as a key, and the value that you want to be linked to that key.

Empty Hashtable:

$NumberList=@{}

Example:

$hash = @{ ID = 13; Name = "Purnima"; Color = "fair"}
$HashValue= @{ ID = 13; Name = "Purnima"; Color = "fair"}
write-host("Print all hashtable keys")
$HashValue.keys
write-host("Print all hashtable values")
$HashValue.values
write-host("Get ID")
$HashValue["ID"]
write-host("print Size")
$HashValue.Count
write-host("Add key-value")
$HashValue["Updated"] = "Now"
write-host("sort by key")
$HashValue.GetEnumerator() | Sort-Object -Property key

Output:

Print all hashtable keys
ID
Name
Color
Print all hashtable values
13
Purnima
fair
Get ID
13
print Size
3
Add key-value
sort by key

Name  Value
—-       —–
Color     fair
ID          13
Name      Purnima
Updated   Now

Example-25: PowerShell Bracket

The PowerShell allow the brackets are

  • Parenthesis brackets− ()
  • Braces brackets− {}
  • Square brackets− []
  • <angle> bracket

Parenthesis brackets:

Basically, the curve bracket is used to

  • close the multiple statements.
  • used in loop
  • Pass the parameter
  • assign array value

Braces brackets:

The curly bracket is used to

execute a block of statement

enclose the code

Square brackets:

Represent each array item.

Suppose $A=@(1,2,3,4)

$A[1] is 2.

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

Some time we are using the angle bracket

In the below example we can abe to see when we add item to HTML file.

Set-Content G:\padmini\SourceFolder\NewHtmlFile.html '<html>Welcome To Top 51 PowerShell Example</html>'

Example-26: PowerShell Backtick

PowerShell support set of Backtick character

  • `n-Newline
  • `t- horizontal tabline
  • `v-vertical tabline
  • `o-null
  • `b-backspace
  • `e-Escape
  • `%-stop parsing

Ex:

Writehost “Collection of `n  important PowerShell `t Example” 

OutPut:

Collection of important PowerShell Example

Example-27: Function in PowerShell

A function in PowerShell is a block of code has a name assign by the user. We can use the function multiple times in code. We need not write the code again and again. We can call the function in a program whenever required.

Syntax:

function functionName
{
code
}

Example of simple function without using Parameter:

function displayDate
{
Get-Date
}

When pass some parameter to function we need to use param keyword

function devidedValue
{
Param ([int]$x,[int]$y)
$z = $x / $b
Write-Output $z
}

Whenever it is required we need to call by the function name.

Factorial of an integer value:

function Factorial-Of-A-Number([int]$number)
{
if($number -lt 0)
{
$factValue = 0
}
elseif($number -le 1)
{
$factValue = 1
}
else
{
$factValue = $number * (Get-Factorial($number - 1))
}
return $factValue
}
$number = Read-Host 'Enter a value'
$factValue = Factorial-Of-A-Number $number
Write-Output "$number! = $factValue"

Example-28: PowerShell Split and Join String

Split the text using PowerShell:

The split operator is used to split the string value. The below example is split of a string value.

$stringValue="Top  51 Window  PowerShell Example"
$arrValue = $stringValue -split ' '
$arrValue

OutPut:

  • Top
  • 51
  • Window
  • PowerShell
  • Example

Join String Value:

In the below example we will discuss how to join the string value. To join multiple value join opearator is used.

$stringValue=("Top "," 51"," Window"," PowerShell"," Example")
$arrValue = -join$stringValue
$arrValue

OutPut:

Top 51 Window PowerShell Example

Example-29: How to show a message box from PowerShell

Below is the PowerShell script which will show a message box.

$msgBoxInput = [System.Windows.MessageBox]:: Show('Would you like to exit the page','Leave the page or not','YesNoCancel','Error')
switch ($msgBoxInput) {
'Yes' {
Write-Host "You pressed yes"
}
'No' {
Write-Host "You pressed No"
}
'Cancel' {
Write-Host "You pressed cancel"
}
}

OutPut:

You pressed yes

PowerShell display message on the screen
PowerShell display message on the screen

Example-30: Write Warning Message and change the color of the text

To write a warning message “Write-Warning” is used.

Write-Warning "Give a Proper UserName"
powershell Write-warning
powershell Write-warning

To change the text color below script is used.

Write-Host "Top 51 Window PowerShell Example" -BackgroundColor Red
Write-Host "Top 51 Window PowerShell Example" -ForegroundColor Yellow
Write-Host "Top 51 Window PowerShell Example" -BackgroundColor green
Write-Host "Top 51 Window PowerShell Example" -ForegroundColor Red
powershell change text color
powershell change text color

Example-31: Retrieving User Information From Active Directory

The below cmdlets is used to retrieve all the username whose password is never expired.

Search-ADAccount -PasswordNeverExpires | FT Name,  ObjectClass, UserPrincipalName
get all active users active directory powershell
get all active users active directory powershell

Example-32: PowerShell registry value

We will get all the PowerShell Drives using Get-“PSDrive” cmdlets.

Get-"PSDrive
PowerShell get registry value data
PowerShell get registry value data

We can able to see two registry key:HKCU and HKLM.

Example-33: PowerShell get IP to address remote computer

By using the below cmdlets we can able to find out Current system IP address.

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Format-Table -Property IPAddress
powershell get ip address remote computer
powershell get ip address remote computer

Example-34: PowerShell restart-computer

To restart the current system “Restart-Computer” cmdlets is used.

Restart-Computer

Example-35: PowerShell find five processes using memory

ps | sort –p ws | select –last 5
powershell get process memory usage remote computer
powershell get process memory usage remote computer

Example-36: PowerShell working with Binary PowerShell

Convert an integer value to hexadecimal value:

$hexValue=0x1234
$hexValue

By simply putting “0x” before a number, we can convert an integer value into a hexadecimal value.

Convert integer to Binary value:

[Convert]::ToString(1234,2)

To convert an integer value to binary in the ToString function pass two parameter one number which we want to convert and 2.

Example-37: PowerShell Create form

For creating a Winform I have created a  variable “NewForm” and create a new form. I have set the size and Start position of form.

I have created an button and click event by calling add_click() method and pass it a PowerShell script block. I have let the button size defult and then add the button to form controls collection and finally call to ShowDialog() method and store in Dialouge variable.

Add-Type -AssemblyName System.Windows.Forms
$NewForm = New-Object Windows.Forms.Form
$NewForm.Size = New-Object Drawing.Size @(250,150)
$NewForm.StartPosition = "CenterScreen"
$Button = New-Object System.Windows.Forms.Button
$Button.add_click({Get-Date|Out-Host})
$Button.Text = "Click here"
$NewForm.Controls.Add($Button)
$Dialouge = $NewForm.ShowDialog()

Output:When we click on button it will show date and time.

powershell gui interface
powershell gui interface

Example-38: PowerShell Clear All History

To clear all the history information using “Clear-History”.

Clear-History

Example-39: PowerShell Get-EventLog

The “Get-EventLog” is used to collect the machine event log.

In the below script I am trying to collect all information of System log file.

Get-EventLog -Log "System"

Example-40: PowerShell Get disk Information

Previously when we want any information about the disks we need to open the CMD window and use disk part. But nowadays the beautiful PowerShell provides the cmdlets “Get-Disk”.

The “Get-Disk” will give all information about the disk attached to our current Operating System.

 By using “Get-PhysicalDisk” cmdlets we can able to get all the physical disc information.

To see all the information of virtual disk created for storage pools we will use “Get-VirtualDisk” cmdlets.

PowerShell get-disk
PowerShell get-disk

To display the volume object we can use Get-volume cmdlets.

Get-volume

Example-41: Take Screenshot Through PowerShell

In the below script I have explained how to take a screenshot in our system using PowerShell cmdlets.

For taking a screenshot we need to do the following steps:

Step-1: First Get the screen information means property of screens like height, width, and co-ordinates. We need to configure the area up to which area we want to copy the screen.

Virtual Screen property is used to get all the property of screen which we want to take the screenshot.

$ScreenInformation = [System.Windows.Forms.SystemInformation]::VirtualScreen
$ScreenWidth = $ScreenInformation.Width
$ScreenHeight = $ScreenInformation.Height
$Left = $ScreenInformation.Left
$Top = $ScreenInformation.Top

Step-2: Create a  BitmapObject to store  image

In step-2 we need to create a new object named as BitmapObject. For the BitmapObject specify screen height and  screen width.

$BitmapObject = New-Object System.Drawing.Bitmap $ScreenWidth, $ScreenHeight

$ScreenWidth and $ScreenHeight  is a variable in which I have store the width and height of screen.

Step-3: create a graphic object

Now I have created a graphic object of the same height and width and pass the “BitmapObject”. The Graphics class is used to draw the BitmapObject.  This Graphics object is used to capture the screen.

$GraphicObject = [System.Drawing.Graphics]::FromImage($BitmapObject)

Using the GraphicObject  and the method CopyFromScreen we will capture the area of screen . We need to set the co-ordination.

$GraphicObject.CopyFromScreen($Left, $Top, 0, 0, $BitmapObject.Size)

For saving the screenshot to local system

For saving the screenshot to local system save $BitmapObject to file. We have dclare a file variable and store the file location where we want to store the capture screen. I want to save the file innewscreenshot So I have to give the address of the file.

$File = "D:\Padmini files\newscreenshot.png"
$BitmapObject.Save($File)
$File = "D:\Padmini files\newscreenshot.png"
Add-Type -AssemblyName System.Windows.Forms
Add-type -AssemblyName System.Drawing
$ScreenInformation = [System.Windows.Forms.SystemInformation]::VirtualScreen
$ScreenWidth = $ScreenInformation.Width
$ScreenHeight = $ScreenInformation.Height
$Left = $ScreenInformation.Left
$Top = $ScreenInformation.Top
$BitmapObject = New-Object System.Drawing.Bitmap $ScreenWidth, $ScreenHeight
$GraphicObject = [System.Drawing.Graphics]::FromImage($BitmapObject)
$GraphicObject.CopyFromScreen($Left, $Top, 0, 0, $BitmapObject.Size)
$BitmapObject.Save($File)
Write-Output "Screenshot saved to your file:"
Write-Output $File

Example-42: PowerShell casting Value

When we are doing any kind of operation with different datatype value then the casting concept arises. It will convert the data type.

For example

$StringValue = "PowerShell" $DoubleValue = 2.0
$SumValue = $StringValue + $DoubleValuewrite-output $SumValue

Here I have taken two variable $StringValue and $DoubleValue. One variable is string type and other variable is double type. So when we will get for sum value we will get error.

So for overcoming the error, we need to follow:

Trace-Command -Name TypeConversion -pshost {[string]$DoubleValue + $StringValue}

The above one is preferred method for casting value

Example-43: PowerShell Change The Look

To Change the PowerShell color we need to use the below command.

$Host.UI.RawUI.BackgroundColor="DarkRed"
$Host.UI.RawUI.ForegroundColor="white"

In the Output, we can able to see background color with Dark red and the text is a white color.

Example-44: PowerShell gets and stop the process:

get-process

By the cmdlets get-process, we will get all the process which is running in the current system.

PowerShell get-process command line
PowerShell get-process command line
get-process  -id 196

We will get the particular process name which is running in the current system.

To stop a particular process

stop-process-id 196

Example-45: Add-Printer Powershell

Get Printers in System using PowerShell:

The “Get-Printer” cmdlets used to get all the printer name associated with the system.

Get-Printer
powershell add printer
PowerShell add printer

Remove Printer to System using PowerShell:

To remove the printer from your System “Remove-Printer” cmdlets is used.

Remove-Printer -Name "Microsoft XPS Document Writer"

The above cmdlets used to Remove the printer name “Microsoft XPS Document Writer”.

Add Printer to System using PowerShell:

When we want to create a new printer to the system we need to mention the value of the parameter. The parameters are

  • Name
  • DriverName
  • PortName
Add-Printer -Name "Microsoft Print to PDF " -DriverName "Microsoft Print To PDF " -PortName " PORTPROMPT:"

Example-46: Convert to HTML

ConvertTo-Html -InputObject (Get-Process)

The ConvertTo-Html parameter is used to converts .NET Framework objects to HTML and we can see the output in a Webpage.

In the above example, I have converted the output of Get-Process to HTML. We can able to see the output in WebPage also.

Example-47: PowerShell Set strict mode

Here we will discuss how to Set strict mode, and how to off the strict mode.

Set-StrictMode -Version 1.0

This Set-“StrictMode” command turns strict mode on and sets it to version 1.0.

Set-StrictMode -Off

The “Set-StrictMode -Off” cmdlets used to turn off the strict mode.

Example-48: PowerShell Get all IP Addresses

Get all the IP address configuration in our system the ‘Get-NetIPAddress’ cmdlets is used. The IP address such as IPv4, IPV6 and the IP interfaces with which addresses are associated.

Get-NetIPAddress
get-net IP address PowerShell
get-net IP address PowerShell

Example-49: PowerShell Get PnpDevice

The “Get-PnpDevice” cmdlet is used to returns information about Plug and Play (PnP) devices in Your System.

Get-PnpDevice
Get-PnpDevice -FriendlyName 'Generic USB Hub'
get-pnplistitem example
get-pnplistitem example

Get-PnpDevice -FriendlyName “Motherboard resources” command gets all the devices named “Motherboard resources”.

Get-PnpDevice -FriendlyName "Motherboard resources"

Like that, we can able to see all the device details by Status, class, FriendlyName, and InstanceId.

Example-50: PowerShell get application pool

“Get-IISAppPool” cmdlets are used to gets all the information about application pool. We can able to see all the application pool name, Status, CLR ver, Pipeline Mode and Start Mode.

Get-IISAppPool
PowerShell get application pool identity
PowerShell get application pool identity

Example-51: PowerShell send email Gmail

By using the below script we can able to send an email to PowerShell.

$From = "xyz@gmail.com"
$To = "abc@gmail.com"
$Cc = "pqr@gmail.com"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential (Get-Credential)

You may like following PowerShell tutorials:

Conclusion:

This PowerShell tutorial we discuss what is Windows PowerShell? Advantages of Windows PowerShell, Different editors we can use to write PowerShell Scripts. Also, we have seen 51 very useful PowerShell examples.

  • >