PowerShell and PowerShell Scripting
PowerShell and PowerShell Scripting
What is PowerShell?
Shell
PowerShell is a modern command shell that includes
the best features of other popular shells. Unlike most
shells that only accept and return text, PowerShell
accepts and returns .NET objects. The shell includes the
following features:
Scripting language
As a scripting language, PowerShell is commonly used
for automating the management of systems. It is also
used to build, test, and deploy solutions, often in CI/CD
environments. PowerShell is built on the .NET Common
Language Runtime (CLR). All inputs and outputs
are .NET objects. No need to parse text output to
2
PowerShell and PowerShell Scripting
extract information from output. The PowerShell
scripting language includes the following features:
Wmic
Nic get name – show all adapter ‘s name.
Get-NetAdapter – show all physical adapter list.
Netsh wlan show interfaces - show all adapters which are
connected through internet.
netsh wlan show profile – show user profile (wi-fi
which has been connected to your computer
at least one time or save in your computer).
netsh wlan show all – show all information about user
profile and also show Wireless
System and Device Capabilities.
6
PowerShell and PowerShell Scripting
Get-wmicObject win32_product – show all installed
programs with other
information.
Invoke-History/ History/H – show history.
Get-NetIPAddress/Ipconfig – show windows IP
configuration.
Get-NetIPConfiguration – show connected wi-fi IP
information.
–
Test-NetConnection – TraceRoute domain/IP or Tracert domain/IP
show all IP address between your and
server router.
Disable-NetAdapter “Adapter_name” – disable wi-fi.
Enable-NetAdapter “Adapter_name” – Enable wi-fi.
Nslookup domain-name – show IP address of domain.
Nslookup IP – show domain name, server
information and IP address.
Resolve-Dnsname domain – show all server information
and ip addresses of particular
domain.
Resolve-Dnsname IP – show server information and
domain name of particular IP
address.
Remove-NetIPAddress – remove all save ip address from
your computer.
Remove-NetIPAddress -InterfaceAlias “adapter_name (i.e. wi-fi, Ethernet
etc.)”. - remove save ip address of particular
adapter from your computer.
7
PowerShell and PowerShell Scripting
Netsh interface ipv4 set address name=”adapter_name” static IP_address
subnet_mask default_geteway – set IP address.
New-NetIPAddress -IPAddress (ex.-20.20.20.20 or other) -PrefixLength (ex.- 8
or 16 or 24) -DefaultGateway (ex.- 20.20.20.2)
Name: user-name
Password: type_password (it is optional). = create
a user.
Remove-LocalUser user_name - remove a user.
New-LocalGroup group_name - create a group for multiple
users.
Remove-LocalGroup group_name - Remove a group.
Format-Volume
PowerShell commands:
PowerShell Scripting
Scripting is about automation. It's about storing steps
that you do often in a file. By running files that contain
your scripts, you can save time and reuse existing
solutions. You can then spend that time on something
more valuable.
PowerShell ISE
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.
PowerShell scripting is the process of writing a set of
statements in the PowerShell language and storing
those statements in a text file. Why would you do that?
After you use PowerShell for a while, you find yourself
repeating certain tasks, like producing log reports or
managing users. When you've repeated something
frequently, it's probably a good idea to automate it: to
store it in such a way that makes it easy to reuse.
The steps to automate your task usually include calls to
cmdlets, functions, variables, and more. To store these
steps, you'll create a file that ends in .ps1 and save it.
You'll then have a script that you can run.
19
PowerShell and PowerShell Scripting
Before you start learning to script, let's get an overview
of the features of the PowerShell scripting language:
Variables. You can use variables to store values.
Variables can be used as arguments to commands.
Functions. A function is a named list of
statements. Functions can produce an output that
can be displayed in the console or used as input
for other commands.
Note
Many of the tasks PowerShell is used for are about side
effects or modifications to system state (local or
otherwise). Often the output is a secondary concern
(reporting data, for example).
Flow control. Flow control is how you control
various execution paths by using constructs
like If, ElseIf, and Else.
Loops. Loops are constructs that allow you to
operate on arrays, inspect each item, and do some
kind of operation on each item. But loops are about
more than array iteration. You can also
conditionally continue to run a loop by using Do-
While loops. For more information, see About Do.
Error handling. It's important to write scripts that
are robust and can handle various types of errors.
You'll need to know the difference between
terminating and non-terminating errors. You'll use
20
PowerShell and PowerShell Scripting
constructs like Try and Catch. This topic will be
covered in the last conceptual unit of this module.
Expressions. You'll frequently use expressions in
PowerShell scripts. For example, to create custom
columns or custom sort expressions. Expressions
are representations of values in PowerShell syntax.
.NET and .NET Core integration. PowerShell
provides powerful integration with .NET and .NET
Core. This integration is beyond the scope of this
module.
Example:
cd\
cd A:
cd PowerShell_scripting
mkdir hariom123
cd hariom123
type nul > hsr.txt
Comments:
There are two types of comments in PowerShell:
Example:
# program for printing "Hello World"
cls
Write-Host("Hello World")
21
PowerShell and PowerShell Scripting
Output:
Hello World
Input by user:
cls
[int]$a = Read-Host -Prompt 'Enter first number'
[int]$b = Read-Host -Prompt 'Enter second number'
[int]$add = $a+$b
[int]$sub = $a-$b
[int]$multi = $a*$b
[double]$div = $a/$b
Output:
Enter first number: 4
Enter second number: 6
Addition = 10
Substraction = -2
Multiplication = 24
Division = 0.666666666666667
Data Types:
22
PowerShell and PowerShell Scripting
[Array] Array
[String] String
Note:
Windows PowerShell uses the Microsoft .NET Framework
data types.
We don’t have to rely on PowerShell’s ability to
automatically convert data types if we tell the interpreter
that we are expecting a number as input.
This ensures that our script works as intended.
23
PowerShell and PowerShell Scripting
The explicitly declaring variable types can prevent
unwanted results in your scripts and makes them more
reliable.
PowerShell Variables
Variables are the fundamental part of the Windows
PowerShell. We can store all the types of values in
the PowerShell variables. For example, we can
store the result of commands, and the elements
which are used in expressions and commands,
such as paths, names, settings, and values. In fact,
they store the objects specifically, Microsoft .NET
Framework objects.
A variable is a unit of memory in which the data is
stored. In Windows PowerShell, the name of a
variable starts with the dollar ($) sign, such
as $process, $a. The name of the variables are
not case-sensitive, and they include spaces and
special characters. By default, the value of all the
variables in a PowerShell is $null.
Note: In Windows PowerShell, special characters have
special meaning. If we use the special characters in the
variable names, we will need to enclose them in the
braces {}.
$myVariable, myVariable,
$MyVariable_1, $my-variable,
{my-variable} $my variable
Example:
24
PowerShell and PowerShell Scripting
$a=200
$b=40
cls
$sum=$a+$b
$sub=$a-$b
$product=$a*$b
$div=$a/$b
$sum
$sub
$product
$div
Output:
240
160
8000
5
Type of a variable
If you want to find the type of a variable, you can use
the GetType() method.
Example
$a=2
$b=25.78
[char]$c = 'H'
$d="Hariom Singh Rajput"
cls
$a.GetType().Name
$b.GetType().Name
$c.GetType().Name
$d.GetType().Name
$a
$b
$c
$d
Output:
Int32
Double
Char
String
2
25.78
H
Hariom Singh Rajput
25
PowerShell and PowerShell Scripting
Delete a variable
If you want to delete the value of the variable, use
the clear-variable cmdlet, or change the value of it
to $null.
Example:
$a=200
$b=40
cls
$sum=$a+$b
$sub=$a-$b
$product=$a*$b
$div=$a/$b
$sum
Clear-Variable sub #clear a variable
$div = $null # initialize variable with null value
$sub
$product
$div
Output:
240
8000
Variable Scope
PowerShell variables can have a "scope" which
determines where the variable is available. To denote a
variable, use the following syntax:
1. User-Created Variables.
2. Automatic Variables.
3. Preference Variables.
User-created Variables
Those variables which are created and maintained by the user
are called user-created variables. The variables that we create
at the PowerShell command line exist only while the Window of
PowerShell is open. When the Window of PowerShell is closed,
the variables are also deleted. We can create the variables in
the scripts with the local, global, or script scope.
Automatic Variables
Those variables which store the state of PowerShell are called
automatic variables. The PowerShell creates this type of
variable, and their values are changed by the PowerShell to
maintain their accuracy. The user cannot change the values of
these variables.
Preference Variables
27
PowerShell and PowerShell Scripting
Preference variables are those variables that store the user
preferences for the Windows PowerShell. The Windows
PowerShell creates this type of variable, and they are
populated with the default values. Any user can change the
value of preference variables.
PowerShell Operators
Like any other programming or scripting languages, Operators
are the building blocks of the Windows PowerShell. An operator
is a character that can be used in the commands or
expressions. It tells the compiler or interpreter to perform the
specific operations and produce the final result.
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Redirection Operators
Arithmetic Operators
The arithmetic operators are used in a PowerShell to
perform the calculation of the numeric values. Arithmetic
operators are used in mathematical expressions in the same
way that they are used in algebra. The following table lists the
arithmetic operators −
29
PowerShell and PowerShell Scripting
Assume integer variable A holds 10 and variable B holds 20,
then –
Example:
$a=200
$b=49
cls
Write-Host("Value of a is: $a")
Write-Host("Value of b is: $b")
# ----------------Arithmatic Operators---------------
$add = $a+$b
Write-Host("Adition = $add " )
$sub = $a - $b
Write-Host("Substraction = $sub")
$product = $a * $b
30
PowerShell and PowerShell Scripting
Write-Host("Multiplication = $product")
$div = $a / $b
Write-Host("Division = $div")
$mod = $a % $b
Write-Host("Remainder = $mod")
Output:
Value of a is: 200
Value of b is: 49
Adition = 249
Substraction = 151
Multiplication = 9800
Division = 4.08163265306122
Remainder = 4
Assignment Operators
The assignment operators are used in a PowerShell to
assign, change, or append the values in a variable. The most
commonly used assignment operator (=), which is used to
assign a given value to the variable. There are some other
assignment operators (+=, -=, *=, /=, %=), which modify the
value of a variable before assigning it.
Example 1:
# ----------------Assignment Operators---------------
$a=200
cls
Write-Host("Value of a is : $a")
$a+=100
Write-Host("After adding 100 Value of a is : $a")
$a-=100
Write-Host("After Substracting 100 Value of a is : $a")
$a*=50
Write-Host("After multiply by 50 Value of a is : $a")
$a/=25
Write-Host("After Divide by 25 Value of a is : $a")
Output:
Value of a is : 200
After adding 100 Value of a is : 300
After Substracting 100 Value of a is : 200
After multiply by 50 Value of a is : 10000
After Divide by 25 Value of a is : 400
Example 2:
# ----------------Assignment Operators---------------
$a=200, 300, 400
cls
Write-Host("Values present in a : $a")
$a+=500,600,700
Write-Host("After adding 500, 600 and 700 Values present in a : $a")
$name = "Hariom "
$name*=5
Write-Host("Your multiplied name is : $name")
$b = 10
Write-Host("value = $b")
$b++
Write-Host("After increament value = $b")
$b--
Write-Host("After decreament value = $b")
32
PowerShell and PowerShell Scripting
Output:
Values present in a : 200 300 400
After adding 500, 600 and 700 Values present in a : 200 300 400 500 600 700
Your multiplied name is : Hariom Hariom Hariom Hariom Hariom
value = 10
After increament value = 11
After decreament value = 10
Comparison Operators
The comparison operators are used in PowerShell to
compare the values. For example, we can compare the string of
two values to check that they are equal or not.
Example:
# ----------------Comparision Operators----------------
$a = 5
$b = 8
cls
($a -eq $b)
($a -ne $b)
($a -gt $b)
($a -ge $b)
($a -lt $b)
($a -le $b)
Output:
False
True
False
False
True
True
Logical Operators
The logical operators are used in PowerShell to connect
expressions or statements together to form a single
expression. Those expressions which contain the logical
operators usually result in the Boolean values True or False.
Example:
# ----------------Logical Operators----------------
$a = 5
$b = 8
cls
($a -lt $b) -and ($a -eq 5)
($a -gt $b) -and ($a -eq 5)
($a -lt $b) -or ($a -eq 10)
($a -ge $b) -or ($a -eq 8)
-not($a -eq 5)
-not(($a -ge $b) -or ($a -eq 8))
!(($a -eq 5) -and ($b -eq 8))
(1 -eq 1) -xor (2 -eq 2)
($a -eq 5) -xor ($b -ne 8)
Output:
35
PowerShell and PowerShell Scripting
True
False
True
False
False
True
False
False
True
Redirection Operators
The redirection operators are used in PowerShell to redirect
the output of one command as an input to another command.
This operator describes how to redirect the output from the
PowerShell to the text files.
>Operator
This operator is used to send the specified stream to the
specified text file. The following statement is the syntax to use
this operator:
Example:
>> Operator
This operator is used to append the specified stream to the
specified text file. The following statement is the syntax to use
this operator:
>&1 Operator
This operator is used to redirect the specified stream to the
success stream. The following statement is the syntax to use
this operator:
-Join Operator
The -Join operator is used in PowerShell to combine the set of
strings into a single string. The strings are combined in the
same order in which they appear in the command.
The following two statements are the syntax to use the Join operator:
1. -Join <String>
Example:
$name = "Hariom "
$lastname = "Mewada"
$string = "Wellcome ", "back ", "to ", "the ", "world ", "of ", "Programing"
cls
-join($name, $lastname)
-join "windows", "operating", "system"
-join ("Hariom ", "Singh ", "Rajput")
-join $string
Output:
Hariom Mewada
windows
operating
system
Hariom Singh Rajput
Wellcome back to the world of Programing
-Split Operator
The -Split operator is used in PowerShell to divide the one or
more strings into the substrings.
The following statements are the syntax to use the -split operator:
1. -Split <String>
2. -Split (<String[]>)
3. <String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]]
4. <String> -Split {<ScriptBlock>} [,<Max-substrings>]
38
PowerShell and PowerShell Scripting
In the above Syntax, the following parameters are
used:
Example:
$a = "Hariom Singh Rajput"
$b = "My=Name=Is=Hariom=Singh=Rajput"
$c = "a=b=c=d=e=f=g=h"
cls
-split $a
-split "a b c d e f"
$b -split "="
$b -split "=", 4
$c -split { $_ -eq "b" -or $_ -eq "f"}
Output:
Hariom
Singh
Rajput
a
b
c
d
e
f
My
39
PowerShell and PowerShell Scripting
Name
Is
Hariom
Singh
Rajput
My
Name
Is
Hariom=Singh=Rajput
a=
=c=d=e=
=g=h
40
PowerShell and PowerShell Scripting
If-Else Statement
When we need to execute the block of statements either when
the condition is true or when the condition is false, we must use
the if-else statement.
Example:
$age = 18
cls
if($age -gt 18){
Write-Host("You are capable for vote")
}
elseif($age -lt 18){
41
PowerShell and PowerShell Scripting
Write-Host("You can't vote now")
}
else{
Write-Host("You are just 18 and now you are ready for your first vote")
}
Output:
You are just 18 and now you are ready for your first vote
Loops:
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 −
For Loop
The For loop is also known as a 'For' statement in a
PowerShell. This loop executes the statements in a code of
block when a specific condition evaluates to True. This loop is
mostly used to retrieve the values of an array.
Example 1:
cls
for ($i=1; $i -le 10; $i++){
"10 x $i = " + (10*$i)
}
Output:
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
Example 2:
$color = "Red", "Orange", "Green", "White", "Blue", "Black", "Gray","Pink",
"Yellow"
cls
for($i=0; $i -lt $color.Length; $i++){
$color[$i]
}
44
PowerShell and PowerShell Scripting
Output:
Red
Orange
Green
White
Blue
Black
Gray
Pink
Yellow
ForEach loop
The Foreach loop is also known as a Foreach statement in
PowerShell. The Foreach is a keyword which is used for
looping over an array or a collection of objects, strings,
numbers, etc. Mainly, this loop is used in those situations
where we need to work with one object at a time.
Syntax
The following block shows the syntax of Foreach loop:
Foreach($<item> in $<collection>)
{
Statement-1
Statement-2
Statement-N
}
Example 1:
$array = 1,2,3,4,5,6,7,8,9,10
cls
foreach($nimber in $array){
$nimber+10
}
Output:
11
12
13
14
15
16
17
18
19
20
Example 2:
cls
foreach($file in Get-ChildItem){
$file
}
Output:
Directory: C:\WINDOWS\system32
46
PowerShell and PowerShell Scripting
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 6/5/2021 6:39 PM 0409
d----- 6/5/2021 5:40 PM AdvancedInstallers
d----- 12/7/2019 2:44 PM am-et
d----- 6/5/2021 5:40 PM AppLocker
d----- 11/23/2021 9:59 PM appraiser
d----- 11/23/2021 9:59 PM ar-SA
d----- 11/23/2021 9:59 PM bg-BG
d----- 12/19/2021 8:52 PM Boot
d----- 6/5/2021 5:40 PM Bthprops
d----- 11/23/2021 9:59 PM ca-ES
d----- 6/5/2021 5:40 PM CatRoot
d----- 1/16/2022 8:25 PM catroot2
d----- 10/30/2021 3:42 PM CodeIntegrity
d----- 6/5/2021 6:39 PM Com
d----- 1/2/2022 6:38 PM config
d---s- 6/5/2021 5:40 PM Configuration
d----- 12/7/2019 2:44 PM ContainerSettingsProviders
d----- 11/23/2021 9:59 PM cs-CZ
d----- 11/23/2021 9:59 PM da-DK
d----- 6/5/2021 5:40 PM DDFs
d----- 11/23/2021 9:59 PM de-DE
d---s- 11/12/2021 9:12 PM DiagSvcs
d----- 11/23/2021 9:59 PM Dism
d----- 6/5/2021 5:40 PM downlevel
d----- 1/13/2022 6:52 PM drivers
d----- 6/5/2021 5:40 PM DriverState
d----- 1/9/2022 3:20 PM DriverStore
d---s- 6/5/2021 6:39 PM dsc
d----- 11/23/2021 9:59 PM el-GR
d----- 6/5/2021 6:39 PM en
d----- 12/19/2021 8:52 PM en-GB
d---s- 12/19/2021 8:52 PM en-US
d----- 11/23/2021 9:59 PM es-ES
d----- 11/23/2021 9:59 PM es-MX
d----- 11/23/2021 9:59 PM et-EE
d----- 11/23/2021 9:59 PM eu-ES
d---s- 10/30/2021 3:42 PM F12
d----- 12/7/2019 2:44 PM ff-Adlm-SN
d----- 11/23/2021 9:59 PM fi-FI
d----- 11/23/2021 9:59 PM fr-CA
d----- 11/23/2021 9:59 PM fr-FR
d----- 6/5/2021 6:46 PM FxsTmp
d----- 11/23/2021 9:59 PM gl-ES
d----- 12/7/2019 2:44 PM GroupPolicy
d----- 12/7/2019 2:44 PM GroupPolicyUsers
d----- 11/23/2021 9:59 PM he-IL
d----- 11/23/2021 9:59 PM hi-IN
d----- 11/23/2021 9:59 PM hr-HR
d----- 11/23/2021 9:59 PM hu-HU
d----- 6/5/2021 6:47 PM Hydrogen
d----- 6/5/2021 5:40 PM ias
47
PowerShell and PowerShell Scripting
d----- 6/5/2021 5:40 PM icsxml
d----- 11/23/2021 9:59 PM id-ID
d----- 6/5/2021 5:40 PM IME
d----- 6/5/2021 5:40 PM inetsrv
d----- 6/5/2021 5:40 PM InputMethod
d----- 6/5/2021 5:40 PM Ipmi
d----- 11/23/2021 9:59 PM it-IT
d----- 11/23/2021 9:59 PM ja-jp
d----- 6/5/2021 5:40 PM Keywords
more…..
Example 3:
$fruit = "Apple", "Banana", "Orange", "Guava", "Pomegranate",
"Pineapple","Mango"
cls
foreach($item in $fruit){
$ITEM
}
Output:
Apple
Banana
Orange
Guava
Pomegranate
Pineapple
Mango
While loop
In a PowerShell, the While loop is also known as
a While statement. It is an entry-controlled loop. This loop
executes the statements in a code of block when a specific
condition evaluates to True.
while(test_expression)
{
Statement-1
Statement-2
Statement-N
}
Example:
cls
$i=1
while($i -le 10){
$i
$i++
}
Output:
1
2
3
4
5
6
7
8
9
10
Do-While Loop
When we need to run a loop at least once, then we use the Do-
while loop in a PowerShell.
49
PowerShell and PowerShell Scripting
The Do-While loop is a looping structure in which a condition is
evaluated after executing the statements. This loop is also
known as the exit-controlled loop.
The do-while loop is the same as while loop, but the condition
in a do-while loop is always checked after the execution of
statements in a block.
Syntax
The following block shows the syntax of Do-while loop:
Do
{
Statement-1
Statement-2
Statement-N
} while( test_expression)
Example:
cls
$i=1
do{
$i
$i++
}while($i -le 10)
Output:
1
2
3
4
5
6
7
8
9
10
Do-Until Loop
51
PowerShell and PowerShell Scripting
The Do keyword is also used with the 'Until' keyword to run the
statements in a script block. Like a Do-while loop, the Do-
until loop also executes at least once before the condition is
evaluated. The Do-Until loop executes its statements in a code
block until the condition is false. When the condition is true, the
loop will terminate.
Syntax
Do
{
Statement-1
Statement-2
Statement-N
} until( test_expression)
Example:
$array = 1,2,3,4,5,6,7,8,9,10
$i = 0
52
PowerShell and PowerShell Scripting
cls
do{
echo $array[$i]
$i+=1}until($i -eq $array.Length)
Output:
1
2
3
4
5
6
7
8
9
10
Example 1:
$a = 1
cls
while($a -le 10){
if($a -eq 5){
$a += 1
continue
}
$a
$a+=1
}
Output:
1
2
53
PowerShell and PowerShell Scripting
3
4
6
7
8
9
10
Example 2:
$a = 10
cls
do{
if(($a -eq 15) -or ($a -eq 18)){
$a++
continue
}
$a
$a++
}while($a -le 20)
Output:
10
11
12
13
14
16
17
19
20
Example 3:
cls
for($i=10; $i -gt 0; $i--){
if($i -eq 5){
continue
}
$i
}
Output:
10
9
8
7
6
4
3
2
1
Break Statement
54
PowerShell and PowerShell Scripting
The Break statement is used in PowerShell to exit the loop
immediately. It can also be used to stop the execution of a
script when it is used outside the switch or loop statement.
Example 1:
cls
for($a=1; $a -lt 10; $a++)
{
if ($a -eq 6)
{
break
}
$a
}
Output:
1
2
3
4
5
Example 2:
cls
$array="windows","Linux","MacOS","Android"
foreach ($os in $array) {
if ($os -eq "MacOS") {
break
}
$os
}
Output:
windows
Linux
Switch Statement
When you need to check the multiple conditions in PowerShell,
we must use the Switch statement.
Example 1:
55
PowerShell and PowerShell Scripting
# ***************___Switch-Case-Statement___***************
$cleancity = 6
cls
switch ($cleancity)
{
1{$result = "Indore"}
2{$result = "Jaipur"}
3{$result = "Surat"}
4{$result = "Mumbai"}
5{$result = "Ahamdabad"}
6{$result = "Raypur"}
7{$result = "Bhopal"}
8{$result = "Dholera"}
9{$result = "Chennai"}
10{$result = "Delhi"}
}
cls
$result
Output:
Raypur
Example 2:
$m=6
$a=13
cls
switch($m,$a)
{
1{echo "January"}
2{echo "February"}
3{echo "March"}
4{echo "April"}
5{echo "May"}
6{echo "June"}
7{echo "July"}
8{echo "August"}
9{echo "September"}
10{echo "October"}
11{echo "November"}
12{echo "December"}
Default { echo " You give a Wrong number"}
}
Output:
June
You give a Wrong number
PowerShell Functions
56
PowerShell and PowerShell Scripting
When we need to use the same code in more than one script,
then we use a PowerShell function.
Syntax
The following block describes a syntax for a function:
o A function keyword
o A name which is given by you
o A scope (It is optional)
o Any number of named parameter
o One or more commands of PowerShell which are enclosed
in braces {}.
Scope of a function
57
PowerShell and PowerShell Scripting
o In PowerShell, a function exists in a scope in which it was
created.
o If a function is in a script, it is only available to the
statements within that script.
o When a function is specified in the global scope, we can
use it in other functions, scripts, and the command line.
Simple function
The following block describes you how to create the simplest
function in a PowerShell:
function <function-name>
{
statement-1
statement-2
statement-N
}
Example 1:
function Sum{
$a=35
$b=55
$c=$a+$b
Write-Host("Your answer is : $c")
}
Output:
Note: you will have to call this function.
PS C:\WINDOWS\system32> sum
Your answer is : 90
Example 2:
function Office-Data{
$a = Read-Host -Prompt 'Enter Employee Name '
$b = Read-Host -Prompt 'Enter Employee Age '
$c = Read-Host -Prompt 'Enter Employee ID '
$d = Read-Host -Prompt 'Enter Employee Salary '
$e = Read-Host -Prompt 'Enter Employee Work experience (In Years) '
cls
Write-Host "Employee Database"
Write-Host "Please Enter following details : "
Office-Data
Output:
Employee Database
Please Enter following details :
Enter Employee Name : Hariom Singh Rajput
Enter Employee Age : 20
Enter Employee ID : 13400987
Enter Employee Salary : 25000
Enter Employee Work experience (In Years) : 2
Employee name is Hariom Singh Rajput
Employee Age is 20
Employee ID is 13400987
Employee Salary is 25000
Employee Work Experience is 2
Example 3:
function Send-Message
{
[CmdletBinding()]
Param (
[ Parameter (Mandatory = $true)]
[string] $Name
)
Process
{
Write-Host ("Hi " + $Name + "!")
}
}
Output:
PS C:\WINDOWS\system32> Send-Message
cmdlet Send-Message at command pipeline position 1
Supply values for the following parameters:
Name: hariom
Hi hariom!
Example 4:
cls
function Get-Square([int]$x)
{
$res = $x * $x
return $res
}
$x = Read-Host 'Enter a value'
$squre = Get-Square $x
59
PowerShell and PowerShell Scripting
Write-Output "$x * $x = $squre"
Output:
Enter a value: 25
25 * 25 = 625
PowerShell Array
Like other scripting languages, Windows PowerShell also
supports a data structure named as an array. An array in a
PowerShell is a data structure that is used to store the
collection of values in a single variable. The values in an array
can be the same type or the different types. A value can be a
string, an integer, a generic object, or another array.
Output:
6
Example 2:
60
PowerShell and PowerShell Scripting
# ____________________________Arrays__________________________
$color = @("Black", "Orange", "White", "Blue", "Red", "Pink", "Green", "Yellow")
$color = $color + "Purple" # Add a color
$color = $color | where {$_ -ne "Orange"} # Remove a color
cls
$color
Output:
Black
White
Blue
Red
Pink
Green
Yellow
Purple
Syntax
61
PowerShell and PowerShell Scripting
The following statement is the syntax to create the Hashtable:
1. $variablename = @{}
We can also add the keys and values to the hash table when
we create it.
Output:
Name Value
---- -----
Course BCA
name Abhay
Age 19
o To display all the keys or all the values of the hash table,
use the dot (.) notation. The following example displays all
the keys of the above example:
$student = @{ name = "Abhay" ; Course = "BCA" ; Age= 19 }
cls
$Student.Keys
Output:
Course
name
Age
Output:
BCA
Abhay
19
o Hash tables have a "count" property, which indicates the
total number of key/value pairs in the hash table. The
following command will display the total number of key-
value pairs in the example:
Example:
$student = @{ name = "Abhay" ; Course = "BCA" ; Age= 19 }
cls
63
PowerShell and PowerShell Scripting
$Student.count
Output:
3
PowerShell String
The PowerShell string is simply an object with
a System.String type. It is a datatype that denotes the
sequence of characters, either as a literal constant or some
kind of variable.
Examples:
Output:
It is a Single Quoted String
Output:
It is a double Quoted String
Concatenation
The concatenation of the string is performed using the plus
Sign.
64
PowerShell and PowerShell Scripting
Examples:
Output:
PowerShell
SubString()
The SubString is a method which accepts the two overload
arguments and returns a part of the longer string. Both the
arguments are numerical values and separated by the comma
(,). The left value is that value where you had like to start
the SubString. The right value represents the number of
characters you had like to move to the right of where you
started.
String Formatting
String formatting is a process to insert some characters or
string inside a string. We can format the string by using the -
f operator.
Example:
cls
$s1="Windows PowerShell"
$s2="POINT"
$formattedString = "{0} {1}...." -f $s1,$s2
$formattedString
Output:
Windows PowerShell POINT....
Replace()
The replace() method accepts the two arguments and is used
to replace the characters in a string.
Output:
Windows PowerShell
Hariom Singh Rajput
2. Export a file:
Example:
Error handling
When you need to handle the terminating errors within the
script blocks, use a Try, Catch, and finally blocks in a
PowerShell.
Try {........}
Try block is the part of a script where you want PowerShell to
monitor for errors. When an error occurs in this block, it is first
stored in the automatic variable $Error. After that, PowerShell
searches for the Catch block to handle it.
If the Try block does not have a matching Catch block, then
the PowerShell searches in the parent scopes for an
appropriate Trap or Catch block.
try
{
Statement-1
Statement-2
68
PowerShell and PowerShell Scripting
Statement-N
}
Catch {.....}
The Catch block is the part in the script which handles the
errors generated by the Try block. We can define which type of
error to be handled by the Catch block. A type of error is an
exception of a Microsoft .NET framework. A Try block can
have multiple catch blocks for different types of errors. Instead
of the Catch block, you can also use the Trap block for
handling the errors.
Finally {......}
The ‘finally’ block is a part of a script which is used to free a
resource that no longer needed by a script.
69
PowerShell and PowerShell Scripting
The following box shows the syntax of the Finally block:
finally
{
Statement-1
Statement-2
Statement-N
}
Examples
Output:
Directory: C:\WINDOWS\system32
Example 2:
cls
Try
{
71
PowerShell and PowerShell Scripting
Get-Child
}
catch
{
"Error in a Try block."
}
Output:
Error in a Try block.
Example 3:
cls
try
1/0
catch [DivideByZeroException]
catch [System.Net.WebException],[System.Exception]
finally
Write-Host “cleaning up …”
Output:
72
PowerShell and PowerShell Scripting
Divide by zero exception
cleaning up …
Example 4:
cls
$error.clear()
try{
Output:
Error Message: Cannot find any service with service name 'WhichService'.
AllSigned
o Only those scripts can run, which are signed by a trusted
publisher with a digital signature.
o Before running the scripts, this policy prompts you a
confirmation that you trust the publisher or not.
Bypass
o In this policy, nothing is blocked.
o There are no warnings, or no prompts are provided.
o Bypass policy is mainly designed for those configurations
in which a script of PowerShell is built into a larger
application.
RemoteSigned
o It is the default execution policy for the Windows Server
computers.
74
PowerShell and PowerShell Scripting
o This policy requires the digital signature from the trusted
publishers on the configuration files and the scripts. These
files and scripts are downloaded from the internet that
includes emails and instant messaging programs.
o This execution policy does not require the digital signature
on those scripts which are written on the local computers.
Restricted
o This execution policy is available by default for Windows
client computers.
o It does not allow to run the scripts but permits the
individual commands.
Undefined
o No execution policy is defined in the current scope.
Unrestricted
o It is a default execution policy for the non-windows
Computers.
o This policy executes those scripts which are unsigned.
MachinePolicy
75
PowerShell and PowerShell Scripting
o This scope sets by the group policy for all the computer
users.
UserPolicy
o This scope sets by the Group policy for the current user of
a computer.
Process
o This scope only affects the current session of PowerShell.
CurrentUser
o In this scope, the execution policy affects only the current
scope.
LocalMachine
In this scope, the execution policy affects all the users on the
current computer.
Get-ExecutionPolicy
Get-ExecutionPolicy -list