0% found this document useful (0 votes)
5 views77 pages

PowerShell and PowerShell Scripting

PowerShell is a cross-platform task automation solution that includes a command-line shell, scripting language, and configuration management framework, operating on Windows, Linux, and macOS. It allows users to automate system management tasks and provides a robust set of commands for file manipulation, system information retrieval, and network configuration. The document details various PowerShell commands and their functionalities, making it a comprehensive guide for users looking to leverage PowerShell for automation.

Uploaded by

thehsr484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views77 pages

PowerShell and PowerShell Scripting

PowerShell is a cross-platform task automation solution that includes a command-line shell, scripting language, and configuration management framework, operating on Windows, Linux, and macOS. It allows users to automate system management tasks and provides a robust set of commands for file manipulation, system information retrieval, and network configuration. The document details various PowerShell commands and their functionalities, making it a comprehensive guide for users looking to leverage PowerShell for automation.

Uploaded by

thehsr484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

1

PowerShell and PowerShell Scripting

What is PowerShell?

PowerShell is a cross-platform task automation solution


made up of a command-line shell, a scripting language,
and a configuration management framework.
PowerShell runs on Windows, Linux, and macOS.

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:

1)Robust command-line history


2)Tab completion and command prediction (See
about_PSReadLine)
3)Supports command and parameter aliases
4)Pipeline for chaining commands
5)In-console help system, similar to Unix man pages

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:

6)Extensible through functions, classes, scripts, and


modules
7)Extensible formatting system for easy output
8)Extensible type system for creating dynamic types
9)Built-in support for common data formats like CSV,
JSON, and XML

PowerShell basic commands:


Pwd – get path.
Get-location – show your current location.
cd.. _ go one step back.
Cd “folder_name” – change directory.
Cd\ - go to drive directly.
Note – we can go back more than one directory by
using “cd directory_name\directory_name\....”
ex.- cd windows\system32
– show all directory
get-ChildItem or dir or ls or gci
which are present at your current location.
-
Get-childItem –Name show all directory name (only)
which are present at your current location.
-
Get-childItem –Name -file show all file name which are
present at your current location.
3
PowerShell and PowerShell Scripting
Copy-Item/Xcopy/copy/cp file_name.ext “Location” – for copy a
file.
Move-Item/move/mv file_name “location” – Cut and
paste(move) a file.
Move-Item *.extension “location” – move all files of same
extension.
Remove-Item/del file_name – delete a file.
Del *.extension – delete all files of same extensions.

Without space: md/mkdir folder_name – make a folder.

With space: md/mkdir “folder_name” – make a folder.

New-Item folder_name1 folder_name2 folder_name3… -Directory –


create multiple
folders at once.
New-Item file_name – create a file without any
extension.
New-Item file_name.extension – create a blank new file.
Type nul > file_name.extension – create a blank new file.
Clear-Host/cls – for clearing the screen.
Get-Command – for help or show all existing
commands.
Get-Process/Tasklist – show all task which are running.
Taskkill /pid pid_id – for kill a task.
Get-Process software_name | Stop-Process – for close a
software.
4
PowerShell and PowerShell Scripting
Start-Process applications_name – for open a software.
Get- services/Net start – show all services
Get-Services | Where-Object {$_.Status -eq ‘running’} – show all
running
services.
Stop-Service/Net stop “service name” – stop a service.
Start-service/Net start “service name” – start a service.
Get-date/Date – show date and time.
Get-TimeZone – show time zone.
Get-TimeZone -ListAvailable - show list of all timezone.
Set-Date – change date or time.
Set-TimeZone -id “id_name” - change time zone.
Ex.- Set-TimeZone -id “India Standard Time”
$env:COMPUTERNAME/Hostname – show desktop
name.
Get-ComputerInfo/Systeminfo/msinfo32 – show all computer
information.
Get-WmiObject win32_networkadapterconfiguration | select description,
macaddress/getmac – show mac addresses of adapter.
Get-WmiObject win32_processor – show processor
information.
Repair-Volume -FileSystemLabel label_name/chkdsk – repair hard
disk if any
problem found.
Diskpart – go to in a loop
5
PowerShell and PowerShell Scripting
List disk – show list of all hard drives or SSD.
Select disk 0/1/2.. – disk will be select.
Detail disk – show all details of selected disk.
Get-Volume – Show all details of disk.
[System.Environment ]::OSVersion.version/winver - show
operating system
version.
Wmic
bios get smbiosbiosversio – show your bios version.
Get-WmiObject win32_bios – show bios information.
Wmic
Product get name, version – show list of installed
software’s with version.

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)

InterfaceAlias: Adapter_name (ex.- Wi-Fi)– set wi-fi or


other adapter’s ip address, prefix
length, default gateway etc.
Test-Connection or Ping IP/domain – for knowing that which
type of connection stablish between
two systems or two servers.
Set-NetFirewallProfile -profile (PRIVATE or PUBLIC) -Enable false –
disable public or private
firewall.
Set-NetFirewallProfile -profile (PRIVATE or PUBLIC) -Enable True –
Enable public or private
firewall.
Show-NetFirewallRule – show all firewall rules.
New-NetFirewallRule -DisplayName hariom_rule -profile @(‘public’,
‘private’) -Direction Inbound (or Outbound) -Action allow (or block) -
Make a firewall rule.
Netsh wlan delete profile name=”hotspot name” – delete a wi-fi
from your
computer.
(Get-Item filename.extension).Encrypt - Encrypt a file for
other system.
Cipher /e – encrypt all files of directory.
8
PowerShell and PowerShell Scripting
(Get-Item filename.extension).Decrypt - Decrypt a file for
other system.
Cipher /d – decrypt all files of directory.
(Get-Item filename.extension).Attributes =’hidden’ – Hide
a file.
Attrib +h +r +s – hide all files of directory.
Attrib -h -r -s - show all files of directory.
Net user – show user of your computer.
Net user user_name /add – create a user.
Net user user_name /del – delete a user.
New-LocalUser

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

DriveLetter[0]: drive_latter: - format drive.


Echo type_data > filename.txt - create a new text file with
written data.
Ex. - echo hello, my name is hariom mewada >
newfile.txt
9
PowerShell and PowerShell Scripting
Set-Content filename.txt ‘type your text here - create a new file
with written text.
Notepad filename.txt - open a text file in notepad.
Shutdown -s -t value_in_seconds – shutdown your
computer.
Ex.- shutdown -s -t 30 (After 30 seconds your computer
will shutdown).
Stop-Computer – shutdown your computer.
Restart-Computer – Restart your computer.

PowerShell commands:

Command Cmdlet name Description of command


alias

% ForEach-Object Performs an operation against


each item in a collection of input
objects.
? Where-Object Selects objects from a collection
based on their property values.
ac Add-Content Appends content, such as words
or data, to a file.
asnp Add-PSSnapIn Adds one or more Windows
PowerShell snap-ins to the
current session.
cat Get-Content Gets the contents of a file.
cd Set-Location Sets the current working location
to a specified location.
chdir Set-Location Sets the current working location
to a specified location.
10
PowerShell and PowerShell Scripting
clc Clear-Content Deletes the contents of an item,
but does not delete the item.
clear Clear-Host Clears the display in the host
program.
clhy Clear-History Deletes entries from the
command history.
cli Clear-Item Deletes the contents of an item,
but does not delete the item.
clp Clear- Deletes the value of a property
ItemProperty but does not delete the property.
cls Clear-Host Clears the display in the host
program.
clv Clear-Variable Deletes the value of a variable.
cnsn Connect- Reconnects to disconnected
PSSession sessions
compa Compare-Object Compares two sets of objects.
re
copy Copy-Item Copies an item from one location
to another.
cp Copy-Item Copies an item from one location
to another.
cpi Copy-Item Copies an item from one location
to another.
cpp Copy-ItemProperty Copies a property and value from
a specified location to another
location.
curl Invoke- Gets content from a webpage on
WebRequest the Internet.
cvpa Convert-Path Converts a path from a Windows
PowerShell path to a Windows
PowerShell provider path.
dbp Disable- Disables the breakpoints in the
PSBreakpoint current console.
del Remove-Item Deletes files and folders.
diff Compare-Object Compares two sets of objects.
11
PowerShell and PowerShell Scripting
dir Get-ChildItem Gets the files and folders in a file
system drive.
dnsn Disconnect- Disconnects from a session.
PSSession
ebp Enable- Enables the breakpoints in the
PSBreakpoint current console.
echo Write-Output Sends the specified objects to
the next command in the
pipeline. If the command is the
last command in the pipeline, the
objects are displayed in the
console.
epal Export-Alias Exports information about
currently defined aliases to a file.
epcsv Export-Csv Converts objects into a series of
comma-separated (CSV) strings
and saves the strings in a CSV
file.
epsn Export-PSSession Imports commands from another
session and saves them in a
Windows PowerShell module.
erase Remove-Item Deletes files and folders.
etsn Enter-PSSession Starts an interactive session with
a remote computer.
exsn Exit-PSSession Ends an interactive session with
a remote computer.
fc Format-Custom Uses a customized view to
format the output.
fl Format-List Formats the output as a list of
properties in which each
property appears on a new line.
foreac ForEach-Object Performs an operation against
h each item in a collection of input
objects.
ft Format-Table Formats the output as a table.
fw Format-Wide Formats objects as a wide table
12
PowerShell and PowerShell Scripting
that displays only one property
of each object.
gal Get-Alias Gets the aliases for the current
session.
gbp Get-PSBreakpoint Gets the breakpoints that are set
in the current session.
gc Get-Content Gets the contents of a file.
gci Get-ChildItem Gets the files and folders in a file
system drive.
gcm Get-Command Gets all commands.
gcs Get-PSCallStack Displays the current call stack.
gdr Get-PSDrive Gets drives in the current
session.
ghy Get-History Gets a list of the commands
entered during the current
session.
gi Get-Item Gets files and folders.
gjb Get-Job Gets Windows PowerShell
background jobs that are running
in the current session.
gl Get-Location Gets information about the
current working location or a
location stack.
gm Get-Member Gets the properties and methods
of objects.
gmo Get-Module Gets the modules that have been
imported or that can be imported
into the current session.
gp Get-ItemProperty Gets the properties of a specified
item.
gps Get-Process Gets the processes that are
running on the local computer or
a remote computer.
group Group-Object Groups objects that contain the
same value for specified
properties.
13
PowerShell and PowerShell Scripting
gsn Get-PSSession Gets the Windows PowerShell
sessions on local and remote
computers.
gsnp Get-PSSnapIn Gets the Windows PowerShell
snap-ins on the computer.
gsv Get-Service Gets the services on a local or
remote computer.
gu Get-Unique Returns unique items from a
sorted list.
gv Get-Variable Gets the variables in the current
console.
gwmi Get-WmiObject Gets instances of Windows
Management Instrumentation
(WMI) classes or information
about the available classes.
h Get-History Gets a list of the commands
entered during the current
session.
history Get-History Gets a list of the commands
entered during the current
session.
icm Invoke-Command Runs commands on local and
remote computers.
iex Invoke-Expression Runs commands or expressions
on the local computer.
ihy Invoke-History Runs commands from the
session history.
ii Invoke-Item Performs the default action on
the specified item.
ipal Import-Alias Imports an alias list from a file.
ipcsv Import-Csv Creates table-like custom objects
from the items in a CSV file.
ipmo Import-Module Adds modules to the current
session.
ipsn Import-PSSes sion Imports commands from another
session into the current session.
14
PowerShell and PowerShell Scripting
irm Invoke- Sends an HTTP or HTTPS request
RestMethod to a RESTful web service.
ise powershell_ise.exe Explains how to use the
PowerShell_ISE.exe command-
line tool.
iwmi Invoke- Calls Windows Management
WMIMethod Instrumentation (WMI) methods.
iwr Invoke- Gets content from a web page on
WebRequest the Internet.
kill Stop-Process Stops one or more running
processes.
lp Out-Printer Sends output to a printer.
ls Get-ChildItem Gets the files and folders in a file
system drive.
man help Displays information about
Windows PowerShell commands
and concepts.
md mkdir Creates a new item.
measu Measure-Object Calculates the numeric
re properties of objects, and the
characters, words, and lines in
string objects, such as files of
text.
mi Move-Item Moves an item from one location
to another.
mount New-PSDrive Creates temporary and
persistent mapped network
drives.
move Move-Item Moves an item from one location
to another.
mp Move- Moves a property from one
ItemProperty location to another.
mv Move-Item Moves an item from one location
to another.
nal New-Alias Creates a new alias.
ndr New-PSDrive Creates temporary and
15
PowerShell and PowerShell Scripting
persistent mapped network
drives.
ni New-Item Creates a new item.
nmo New-Module Creates a new dynamic module
that exists only in memory.
npssc New- Creates a file that defines a
PSSessionConfigur session configuration.
ationFile
nsn New-PSSession Creates a persistent connection
to a local or remote computer.
nv New-Variable Creates a new variable.
ogv Out-GridView Sends output to an interactive
table in a separate window.
oh Out-Host Sends output to the command
line.
popd Pop-Location Changes the current location to
the location most recently
pushed to the stack. You can pop
the location from the default
stack or from a stack that you
create by using the Push-
Location cmdlet.
ps Get-Process Gets the processes that are
running on the local computer or
a remote computer.
pushd Push-Location Adds the current location to the
top of a location stack.
pwd Get-Location Gets information about the
current working location or a
location stack.
r Invoke-History Runs commands from the
session history.
rbp Remove- Deletes breakpoints from the
PSBreakpoint current console.
rcjb Receive-Job Gets the results of the Windows
PowerShell background jobs in
16
PowerShell and PowerShell Scripting
the current session.
rcsn Receive-PSSession Gets results of commands in
disconnected sessions.
rd Remove-Item Deletes files and folders.
rdr Remove-PSDrive Deletes temporary Windows
PowerShell drives and
disconnects mapped network
drives.
ren Rename-Item Renames an item in a Windows
PowerShell provider namespace.
ri Remove-Item Deletes files and folders.
rjb Remove-Job Deletes a Windows PowerShell
background job.
rm Remove-Item Deletes files and folders.
rmdir Remove-Item Deletes files and folders.
rmo Remove-Module Removes modules from the
current session.
rni Rename-Item Renames an item in a Windows
PowerShell provider namespace.
rnp Rename- Renames a property of an item.
ItemProperty
rp Remove- Deletes the property and its
ItemProperty value from an item.
rsn Remove- Closes one or more Windows
PSSession PowerShell sessions
(PSSessions).
rsnp Remove-PSSnapin Removes Windows PowerShell
snap-ins from the current
session.
rujb Resume-Job Restarts a suspended job
rv Remove-Variable Deletes a variable and its value.
rvpa Resolve-Path Resolves the wildcard characters
in a path, and displays the path
contents.
rwmi Remove- Deletes an instance of an
17
PowerShell and PowerShell Scripting
WMIObject existing Windows Management
Instrumentation (WMI) class.
sajb Start-Job Starts a Windows PowerShell
background job.
sal Set-Alias Creates or changes an alias
(alternate name) for a cmdlet or
other command element in the
current Windows PowerShell
session.
saps Start-Process Starts one or more processes on
the local computer.
sasv Start-Service Starts one or more stopped
services.
sbp Set-PSBreakpoint Sets a breakpoint on a line,
command, or variable.
sc Set-Content Replaces the contents of a file
with contents that you specify.
select Select-Object Selects objects or object
properties.
set Set-Variable Sets the value of a variable.
Creates the variable if one with
the requested name does not
exist.
shcm Show-Command Creates Windows PowerShell
commands in a graphical
command window.
si Set-Item Changes the value of an item to
the valu
18
PowerShell and PowerShell Scripting

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:

1. Single line comment:


 We use # for single line comment.
 Ex: #This is a single line comment.
2. Multi line comment:
 We use <# type comment #> for multi line
comment.
 Ex: <# This is a multi line comment #>

Print Output in PowerShell:


We use Write-Host cmdlet for printing output in PowerShell.

Example:
# program for printing "Hello World"
cls
Write-Host("Hello World")
21
PowerShell and PowerShell Scripting
Output:
Hello World

Note: cls is used for clear the screen.

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

Write-Host ("Addition = $add")


Write-Host ("Substraction = $sub")
Write-Host ("Multiplication = $multi")
Write-Host ("Division = $div")

Output:
Enter first number: 4
Enter second number: 6
Addition = 10
Substraction = -2
Multiplication = 24
Division = 0.666666666666667

Data types and variables:

Working with PowerShell’s Data Types


Windows PowerShell uses the Microsoft .NET Framework data
types. The poweshell can supports strings ,integers ,floating
point numbers, strings, and Boolean values.You don’t have to
explicitly declare the data type of a variable, the PowerShell
automatically chooses the data type for you when you initialize
the variable—that is,when you first assign a value.

Data Types:
22
PowerShell and PowerShell Scripting

Data Type Name Description

[Array] Array

[Bool] Value is TRUE or FALSE

[DateTime] Date and time

[Guid] Globally unique 32-byte identifier

Hash table, collection of key-value


[HashTable]
pairs

[Int32], [Int] 32-bit integers

[PsObject] PowerShell object

[Regex] Regular expression

[ScriptBlock] PowerShell script block

[Single], [Float] Floating point number

[String] String

[Switch] PowerShell switch parameter

[TimeSpan] Time interval

[XmlDocument] XML document

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 {}.

Valid variable Invalid variable


names: names:

$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:

Windows PowerShell supports the following scope


modifiers of a variable:

o Global: Global variables are those variables that


are valid everywhere, even outside the scripts and
functions. To denote global variables, use the
following format:

Ex: $Global: variable = <value>


26
PowerShell and PowerShell Scripting
o Local: Those variables which can be created in a
local scope. By default, the variable has a local
scope. To denote a local variable, use the following
format:

Ex: $variable = <value>


o Script: Those variables which are created during
the script. These variables are only available to
that script in which they are created. To denote a
script variable, use the following format:

Ex: $script: variable = <value>


Types of Variables
Following are the different types of variables in the Windows
PowerShell:

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.

PowerShell supports the following different types of


operators:
28
PowerShell and PowerShell Scripting

1. Arithmetic Operators

2. Assignment Operators

3. Comparison Operators

4. Logical Operators

5. Redirection Operators

6. Split and Join 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 –

Operator Description Exampl


e

Adds values on either side of the A+B


+ (Addition) operator. will give
30

- Subtracts right-hand operand


A - B will
(Subtraction from left-hand operand.
give -10
)

* Multiplies values on either side


A * B will
(Multiplicati of the operator.
give 200
on)

Divides left-hand operand by B / A will


/ (Division)
right-hand operand. give 2

Divides left-hand operand by B%A


% (Modulus) right-hand operand and returns will give
remainder. 0

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.

Operato Description Exampl


r e

Simple assignment operator. C=A+


Assigns values from right side B will
operands to left side operand. assign
=
value of
A+B
into C

+= Add AND assignment operator. It C += A


adds right operand to the left is
operand and assign the result to equivale
left operand. nt to C
31
PowerShell and PowerShell Scripting
=C+A

Subtract AND assignment operator. C -= A is


It subtracts right operand from the equivale
-=
left operand and assign the result nt to C
to left operand. =C-A

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.

Operator Description Exampl


e

Compares two values to be A -eq B


eq (equals) equal or not. will give
false

Compares two values to be A -ne B


ne (not equals) not equal. will give
true

Compares first value to be B -gt A


gt (greater
greater than second one. will give
than)
true

ge (greater Compares first value to be B -ge A


than or equals greater than or equals to will give
to) second one. true

lt (less than) Compares first value to be B -lt A


less than second one. will give
33
PowerShell and PowerShell Scripting
false

Compares first value to be B -le A


le (less than or
less than or equals to second will give
equals to)
one. false

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.

Operator Description Example

-and Called Logical AND (A -AND B) is


operator. If both the false
operands are non-zero,
34
PowerShell and PowerShell Scripting
then the condition becomes
true.

Called Logical OR Operator.


If any of the two operands
-or (A -OR B) is true
are non-zero, then the
condition becomes true.

Called Logical NOT


Operator. Use to reverses
the logical state of its -NOT(A -AND B)
-not
operand. If a condition is is true
true then Logical NOT
operator will make false.

Same as -not operator !(1 -eq 1)


!
Return false

Logical EXCLUSIVE OR. True (1 -eq 1) -xor (2


when only one statement is -eq 2)
-xor
true.
Return 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.

PowerShell supports the following redirection


operators:
1. >
2. >>
3. >&1

>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:

Command n> Filename

Example:

PS D:\> Get-childitem > k.txt

The above command sends the following output of the Get-


childItem cmdlet to the k.txt file.
36
PowerShell and PowerShell Scripting
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 30-09-2019 05:49 images
d----- 09-10-2019 11:14 files
d----- 09-10-2019 11:56 powershell
d----- 09-10-2019 10:58 users
d----- 09-10-2019 04:37 Windows
-a---- 05-11-2019 14:53 0 k.txt
-a---- 25-06-2018 09:46 2179 powershell.txt

>> 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:

Command n>> Filename


Example:

PS D:\> Get-help >> k.txt

The above command appends the output of the get-


help command to the k.txt file.

>&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:

Command n>&1 > Filename


Example:

PS D:\> &{Write-Error "hello"} 2>&1 > k.txt

The above command is used to redirect the following output


of Write-Error command to the k.txt file.

Split and Join Operators


The Split and Join operators are used in PowerShell to divide
and combine the substrings. The Join operator is used to
37
PowerShell and PowerShell Scripting
concatenate the multiple strings into a single string.
The split operator is used to split a string into substrings.

-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>

2. <String> -Join <Delimiter>

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:

1. <string> : This parameter is used to specify the


one or more string to be split. The same delimiter
rule splits the multiple strings.
2. <delimiter> : The default delimiter is " ". When
the strings are split, it is omitted from all the
substrings.
3. <max-substrings> : This parameter is used to
specify the maximum number of times that a
string splits.
4. <ScriptBlock> : This parameter is an expression
that specifies the rules for applying the delimiter.
We must enclose the script block in the
braces"{}".
5. <Options> : This parameter is valid only when
the <max-substring> parameter is used in the
statement.

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.

If the condition, which is a Boolean expression evaluates to


True, then the statements inside the 'if' body will be executed.
And if the condition evaluates to false, then the statements
inside the 'else' body will be executed.

Flowchart of 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 −

PowerShell programming language provides the following


types of loop to handle looping requirements.
42
PowerShell and PowerShell Scripting
 For loop
 forEach loop
 while loop
 do….while loop
 do – until loop

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.

Syntax of For loop

for (<Initialization>; <Condition or Test_expression>; <Repeat>)


{
Statement-1
Statement-2
Statement-N
}

In this Syntax, the Initialization placeholder is used to create


and initialize the variable with the initial value.

Flowchart of For loop


43
PowerShell and PowerShell Scripting

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
}

In this syntax, <item> is a single value of a variable or an


object which changes over each iteration. The <collection> is
an array or a collection of numbers and strings which you want
to access. When this loop executes, the PowerShell creates the
variable $<item> automatically. There is a block in syntax
which contains single or multiple statements which are
executed for each item in a collection.

Flowchart of ForEach loop


45
PowerShell and PowerShell Scripting

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.

Syntax of While loop

while(test_expression)
{
Statement-1
Statement-2
Statement-N
}

Flowchart of While loop


48
PowerShell and PowerShell Scripting

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)

Flowchart of Do-While loop


50
PowerShell and PowerShell Scripting

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)

Flowchart of Do-Until loop

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

Continue and Break Statement


Continue Statement
The Continue statement is used in PowerShell to return the
flow of the program to the top of an innermost loop. This
statement is controlled by the for, Foreach and while loop.

When this statement is executed in a loop, the execution of


code inside that loop following the continue statement will be
skipped, and the next iteration of a loop will begin. It is
generally used for a condition so that a user can skip some
code for a specific condition.

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.

This statement in PowerShell is equivalent to the series of 'If'


statements, but it is simple to use. This statement lists each
condition and the code of block associated with each condition.
If a condition is 'True', then the block of code is executed with
that particular condition.

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.

A function is a list of PowerShell statements whose name is


assigned by the user. When we execute a function, we type the
name of a function.

Like the cmdlets, functions can also have parameters. The


function parameters can be read from the pipeline or from the
command line.

In PowerShell, functions return the values that can be


assigned to the variables or passed to the cmdlets or other
functions. By using the return keyword, we can specify the
return value.

Syntax
The following block describes a syntax for a function:

function [<scope:>]<name> [([type]$parameter1[,[type]


$parameter2])]
{
param([type]$parameter1 [,[type]$parameter2])
dynamicparam {<statement list>}
begin {<statement list>}
process {<statement list>}
end {<statement list>}
}

The above syntax includes the following terms:

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) '

Write-Host "Employee name is $a "


Write-Host "Employee Age is $b "
Write-Host "Employee ID is $c "
58
PowerShell and PowerShell Scripting
Write-Host "Employee Salary is $d "
Write-Host "Employee Work Experience is $e "
}

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.

Each element or a value in an array has an index. Indexes are


the integers which represent the place of a value in an array.
We can retrieve the elements of an array using the index. The
index of an array always starts with 0, which indicates the first
item of an array.

Creating and Initializing an array


o To declare the array in a PowerShell, assign the multiple
values to the variable using the assignment operator. The
comma separates the values which are stored in the
array.
The following statement is a syntax to declare the array
variable:

$variable_name = value1, value2, value3, ..... ,ValueN


Example 1:
# ____________________________Arrays__________________________
$a = 1,2,3,4,5,6,7,8,9,10
$a[5]

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

PowerShell Hast table


The PowerShell Hashtable is a data structure that stores one
or more key/value pairs. It is also known as the dictionary or
an associative array.

In the PowerShell, there exists a Hashtable


(System.Collections.Hashtable) object for each hash table.

We can use the properties and methods of the Hashtable object


in the PowerShell. The key and the values in the Hash table are
also the objects of .NET type.

After the PowerShell version 3.0 introduced, we can use the


[ordered] attribute to create an ordered dictionary
(System.Collections.Specialized.OrderedDictionary) in
PowerShell.
23.2M
485
HTML Tutorial

The main difference between the ordered dictionaries and the


Hashtable is that the keys in dictionaries always appear in the
order in which we list them. But the order of the keys in the
Hashtable is not determined.

Syntax
61
PowerShell and PowerShell Scripting
The following statement is the syntax to create the Hashtable:

1. $variable_name = @{ <key1> = <value1> ; < key2> = <value2>


; ..... ; < keyN> = <valueN>;}

The following statement is the syntax to create an ordered


dictionary:

2. $variable_name = [ordered] @{ < key1> = <value1> ; < key2> =


<value2> ; ..... ; < keyN> = <valueN>;}

Create a Hash Table

The following are the steps to create the hash table in


the PowerShell:

1. Create a hast table with the @ symbol at the beginning.


2. Enclose the hash table in the braces.
3. Enter one or more key/value pairs as the content of the hash table.
4. To separate each value form it's key, we must use an equal sign
(=).
5. To separate the key/value pairs, we must use a semi colon (;) or the
line break.
6. Those keys which contain the spaces enclosed them in a quotation
marks. And the values must be valid expression of PowerShell.
7. To manage the Hast table, assign it to the variables.
8. When you assign the ordered hast table to the variable, you can
place the ordered attribute before @ sign.

If you want to create an empty hash table, type the following


command in the PowerShell:

1. $variablename = @{}

We can also add the keys and values to the hash table when
we create it.

The following example describe how to create the hash table


with three keys and their values.
62
PowerShell and PowerShell Scripting
$student = @{ name = "Abhay" ; Course = "BCA" ; Age= 19 }
cls
$Student

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

The following example displays all the values of the


above example:
$student = @{ name = "Abhay" ; Course = "BCA" ; Age= 19 }
cls
$Student.Values

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.

A String can be defined in PowerShell by using the single or


double-quotes. Both the strings are created of the
same System.String object type.

Examples:

Example1: This example describes how to use the single


quotes in a String:
cls
$String1='It is a Single Quoted String'
$String1

Output:
It is a Single Quoted String

Example2: This example describes how to use the double


quotes in a String:
cls
$String2="It is a double Quoted String"
$String2

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:

Example1: The following example describes how to


concatenate the two string variables:
cls
$s1="Hariom"
$s2="Mewada"
$s1+$s2
Output:
HariomMewada

Example2: We can also use the method concat() to


concatenate the strings. The following example describes how
to use this method:
cls
$s1="Power"
$s2="Shell"
[System.String]::Concat($s1,$s2)

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.

Example: The following example skips the first three


characters and returns the next seven-character from the given
string.
cls
$s1="Windows PowerShell"
$s1.SubString(3,7)
Output:
65
PowerShell and PowerShell Scripting
dows Po

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.

Example: In the following example, we can replace the


character x to S in the given string s1 and Mewada to Rajput in
the given string s2.
cls
$s1="Windows Powerxhell"
$s1.replace("x","S")
$s2 = "Hariom Singh Mewada"
$s2.Replace("Mewada", "Rajput")

Output:
Windows PowerShell
Hariom Singh Rajput

Import-Export CSV Files in terminal:


1. Import a file:
Example:

Import-Csv Hsr1.csv | Select-Object name,city,code


66
PowerShell and PowerShell Scripting
Output:

Name City Code


---- ---- ----
Aman Indore 101
Ankit Bhopal 102
Hariom Ashta 103
Pooja Ashta 104
Rajesh Mumbai 105

2. Export a file:
Example:

# export data of Get-Process Command in test.csv file


Get-Process | Select-Object id , processname | ConvertTo-Csv | Export-Csv .\
test.csv

Simple Calculator Code:


#______________________Calculator______________________
cls
[int]$a=Read-Host -Prompt 'Enter 1st Number'
[char]$b=Read-Host -Prompt 'Enter Operation (+, -, *, /, %)'
[int]$c=Read-Host -Prompt 'Enter 2nd Number'
[int]$add=$a+$c
[int]$sub=$a-$c
[int]$multi=$a*$c
[double]$div=$a/$c
[int]$mod=$a%$c
cls
switch($b)
{
+{$result = 'You Choose Addition'
Write-Host ("Your Answer is : $add")
break;
}

-{$result = 'You Choose Substraction'


Write-Host ("Your Answer is : $sub")
break;
}

*{$result = 'You Choose Multiplication'


Write-Host ("Your Answer is : $multi")
break;
}

/{$result = 'You Choose Division'


Write-Host ("Your Answer is : $div")
break;
}
67
PowerShell and PowerShell Scripting
%{$result = 'You Choose Remainder'
Write-Host ("Your Answer is : $mod")
break;
}
}
$result

Error handling
When you need to handle the terminating errors within the
script blocks, use a Try, Catch, and finally blocks in a
PowerShell.

The terminating errors are those errors which stop the


statement from running. When PowerShell does not handle the
terminating errors in some way, then it also stops running a
script or function using the current pipeline. In other languages,
such as C, these errors are referred to as exceptions.

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.

Syntax of Try Block


The following box shows the syntax of the try block:

try
{
Statement-1
Statement-2
68
PowerShell and PowerShell Scripting
Statement-N
}

A Try statement must have at least one catch or one finally


block. In the above syntax, the Try keyword is followed by
single or multiple statements in the braces.

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.

Syntax of Catch block


The following box shows the syntax of the catch block:

catch [ [<error type>] [',' <error type>] *]


{
Statement-1
Statement-2
Statement-N
}
The types of errors appear in the brackets. The outermost
bracket shows that the element is optional. In the above
syntax, the catch keyword is followed by an optional list of
error type specifications and a list of statements. When anyone
catch block is found, then the statements in the catch block are
executed.

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
}

The ‘finally’ block is followed by single or multiple statements


which are enclosed in the braces that execute every time when
the script is executed.

Examples

Example1: The following example uses only one Catch block


with the Try block:
cls
Try
{
Get-ChildItem
}
catch
{
"Error in a Try block."
}

Output:
Directory: C:\WINDOWS\system32

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
70
PowerShell and PowerShell Scripting
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
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 2:
cls
Try
{
71
PowerShell and PowerShell Scripting
Get-Child
}
catch
{
"Error in a Try block."
}

In this example, the command is wrong in the Try block, so


there exists an error in a Try block. Hence, we get the output
from the catch block:

Output:
Error in a Try block.

Example 3:
cls
try

1/0

catch [DivideByZeroException]

Write-Host “Divide by zero exception”

catch [System.Net.WebException],[System.Exception]

Write-Host “Other exception”

finally

Write-Host “cleaning up …”

Output:
72
PowerShell and PowerShell Scripting
Divide by zero exception
cleaning up …

Example 4:
cls
$error.clear()
try{

Get-Service WhichService -ErrorAction Stop


}
catch{
Write-Host "`nError Message: " $_.Exception.Message
Write-Host "`nError in Line: " $_.InvocationInfo.Line
Write-Host "`nError in Line Number: "$_.InvocationInfo.ScriptLineNumber
Write-Host "`nError Item Name: "$_.Exception.ItemName
}
finally{
"This is going to run anyway"
$error.clear()
}

Output:
Error Message: Cannot find any service with service name 'WhichService'.

Error in Line: Get-Service WhichService -ErrorAction Stop

Error in Line Number: 5

Error Item Name:


This is going to run anyway

PowerShell Execution Policy


An execution policy is the feature of PowerShell that specifies
the conditions under which PowerShell loads the configuration
files and run the scripts.

On a Windows operating system, we can set the execution


policy for the current user, local computer, or for a specific
session. Execution policies for the Current user and the local
computer are stored in the registry, and for a specific session,
execution policy is stored only in the memory, which is lost
when the session is closed.
73
PowerShell and PowerShell Scripting
On a non-Windows operating system, the default execution
policy is unrestricted. And this policy cannot be unchanged.

PowerShell Execution Policies


The following are the PowerShell execution
policies:
o AllSigned
o Bypass
o RemoteSigned
o Restricted
o Undefined
o Unrestricted

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.

Execution Policy Scope


The following are the valid values for the
execution policy scope:
o MachinePolicy
o UserPolicy
o Process
o CurrentUser
o LocalMachine

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.

Manage the Execution policy

o We can use the following Cmdlet to get the effective


execution policy for the current PowerShell session:

Get-ExecutionPolicy

o We can use the following command to get all the


execution policies which affect the current session. And,
using this command, we display them in the precedence
order.

Get-ExecutionPolicy -list

The output of the above command looks like this:


76
PowerShell and PowerShell Scripting

o We can use the -Scope parameter to get the execution


policy for a particular scope. For example, the following
command gets the execution policy for
the LocalMachine Scope:

Get-ExecutionPolicy -Scope LocalMachine

Change the Execution Policy


o We can use the Set-ExecutionPolicy cmdlet to change
the execution policy of PowerShell on Windows computers.
The changes done by you are affected immediately. You
don’t require to restart the PowerShell Window.
o If you made some changes in the execution policy for the
scope CurrentUser and LocalMachine, the changes are
saved in the registry, and they remain effective until you
change them again.
o If you make changes in the execution policy for
the Process scope, then they are not saved in the
registry.
o The following block describes you a syntax which is used
to change the execution policy:

Set-ExecutionPolicy -ExecutionPolicy <PolicyName>

Remove the ExecutionPolicy


77
PowerShell and PowerShell Scripting
We can remove the execution policy for a particular scope by
setting the execution policy to Undefined.

Example: This example removes the execution policy for all


the users of the local computer.

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope LocalM


achine

You might also like