Scripting
Scripting
$i = 1
$string = "Hello World!"
$this_is_a_variable = "test"
💡 Variables are for storing simple values, strings, and also the output of commands.
$date = Get-Date
Write-Host "Today is" $date
Data Types
PowerShell automatically assigns a data type to a variable based on the type that best suits its
content.
$x = 4
$string = "Hello World!"
$date = Get-Date
$x.GetType().Name
$string.GetType().Name
$date.GetType().Name
Casting Variables
Convert the data type of variable by casting it to another type.
$number = "4"
$number.GetType().Name # String data type
Automatic Variables
Built-in variables that are created and maintained by PowerShell.
$?: Execution status of the last command. True if command succeeded, otherwise False.
$_: Called pipeline variable, represents the current item being processed in a pipeline or loop.
$Error: Contains the most recent errors, collected in an array. Indexed using $Error[0]
$LastExitCode: Contains the last exit code of the program that was run.
$null: Contains null or an empty value, used to check whether a variable contains a value or set
to undefined.
$true: Contains True. use $true to represent True in commands and scripts.
Environment Variables
Store information about the operating system and paths that are frequently used by the system.
To show all the environment variables within a session, using dir env:
#Find help pages that write about the word we're looking for
Get-Help filter -Category:HelpFile
Variable Scope
Variable scope determines where a variable is accessible within a script, function, or session.
💡 In general, variables are only available in the context in which they are set.
Scope Modifier
global: Sets the scope to global, effective when PowerShell starts or a new session is created.
💡 Variables with global scope defined in a module are available in the session once the
module is loaded.
script: Scope is only effective within the script that sets this scope.
function Set-Variables {
$local_variable = "Hello, I'm a local variable."
$script:script_variable = "Hello, I'm a script variable."
$global:global_variable = "Hello, I'm a global variable."
Write-Host "##########################################################"
Write-Host "This is how our variables look in the function,
where we defined the variables - in a LOCAL SCOPE:"
Write-Host " Local: " $local_variable
Write-Host " Script: " $script_variable
Write-Host " Global: " $global_variable
}
Set-Variables
Write-Host "##########################################################"
Write-Host "This is how our variables look in the same script - in a
SCRIPT SCOPE:"
Write-Host " Local: " $local_variable
Write-Host " Script: " $script_variable
Write-Host " Global: " $global_variable
Set-Variable function is declared first, once function is called, it sets variables of three scopes.
💡 Working with script and global scope variables, it is a good practice to always use the
variable with the modifier: $script:script_variable/$global:global_variable
#Substraction
$a = 3; $b = 5; $result = $b - $a
#Multiplication
$a = 3; $b = 5; $result = $a * $b
#Division
$a = 3; $b = 5; $result = $a / $b
#Modulus
$a = 12; $b = 4; $result = $a % $b
Comparison Operators
Equal (-eq): Returns True if both values are equal.
$a = 1; $b = 1; $a -eq $b
Not equal (-ne): Returns True if both values are not equal.
$a = 1; $b = 2; $a -ne $b
Less equal(-le): Return True if the first value is less than or equal to the second value.
$a = 1; $b = 2; $a -le $b
Greater equal(-ge): Return True if the first value is greater than or equal to the second value.
$a = 1; $b = 2; $a -ge $b
Less than(-lt): Returns True if the first value is less than the second value.
$a = 1; $b = 2; $a -lt $b
Greater than(-gt): Returns True if the first value is greater than the second value.
-like : Check whether a value matches a wildcard expression when used with a scalar.
Used in an array context, the -like operator returns only the elements that match the
specified wildcard expression.
-notlike :Check whether a value does not match a wildcard expression when used with a scalar.
Used in an array context, the -notlike operator returns only te elements that do not match
the specified wildcard expression.
Assignment Operators
= : Assigns a value
+= : Increases value by the amount defined after the operator and stores the result in initial
variable.
$a += 1; $a += 2; $a
-= : Decreases value by the amount defined after the operator and stores the result in initial
variable.
$a -= 1; $a
*= : Multiplies value by the amount defined after the operator and stores the result in initial
variable.
$a *= 5; $a
/= : Divides the value by the amount defined after the operator and stores the result in the initial
variable.
$a /= 2; $a
%= : Performs a modulo operation on the variable using the amount after the operator and
stores the result in the initial variable.
$a %= 2; $a
$a = 1; $a++; $a
$a = 10; $a--; $a
Logical Operators
-and : Combine conditions, action is triggered only if both conditions are met.
$a = 1; $b = 2
if (($a -eq 1) -and ($b -eq 2)) {Write-Host "Conditon is true!"}
-xor : Logical exclusive -or . Is True if only one statement is True ( but returns False if both are
True)
Control Structures
A control structure is a logic that assesses conditions and variables and decides which defined
action to take if certain condition is met.
Conditions
if / elseif / else :
Syntax:
if (<condition>)
{
<action>
}
elseif (<condition>)
{
<action 2>
}
...
else
{
<action 3>
}
Code:
Switch :
Check a variable against a long list of values.
Syntax:
Code:
ForEach-Object :
Accepts a list or an array of items and allows to perform an action against each of them.
To perform specific actions before processing each item use the -Begin and -End
parameters.
Use -Process parameter to specify the script block that is run for each item in the pipeline.
Foreach :
Works similar to Foreach-Object , but it doesn’t accept pipeline objects.
Foreach statement loads all items into a collection before they are processed, making it quicker but
consuming more memory than ForEach-Object .
Code:
Foreach statement:
Foreach method:
$items.foreach ({
Write-Host "Current item: $_"
})
💡 The $_ variable is used to reference the current item being iterated over.
while :
Does something (<actions>) as long as defined condition is True.
Syntax:
Code:
for:
Defines the initializing statement, a condition, and loops through until the defined condition is not
fulfilled.
Syntax:
do-until / do-while:
Starts running the defined commands, and then checks whether the condition is still met or not.
Syntax:
do{
<action>
}
<while/until> <condition>
💡 do-while runs as long as the condition is True, do-until runs as long as the condition is not
met.
break:
Used to exit the loop.
Code:
continue:
Used to skip the current iteration of a loop and move to the next one.
Code:
PowerShell profiles
PowerShell profiles are configuration files that allow to personalize the PowerShell environment.
💡 Profiles are scripts that are executed when a PowerShell session is started, allow setting
variables, define functions, create aliases, and more.
All Users, Current Host ( $profile.AllUsersCurrentHost ): This profile applies to all users for the
current PowerShell host.
Current User, All Hosts ( $profile.CurrentUserAllHosts ): This profile applies to the current user for
all PowerShell hosts.
Current User, Current Host ( $profile.CurrentUserCurrentHost ): This profile applies only to the
current user and the current PowerShell host.
💡 This profile is loaded when using the PowerShell ISE and can be viewed by running
the $profile | f1 * -force command within ISE.
# Syntax:
# $profile.<profile name>
if ( !(Test-Path $profile.CurrentUserCurrentHost)) {
New-Item -ItemType File -path $profile.CurrentUserCurrentHost
}
Understanding PSDrives
PowerShell drives in PowerShell are similar to filesystem drives in Windows, but instead of
accessing files or folders, use PSDrives to access a variety of data stores.
Data stores include directories, registry keys, and other data sources.
💡 PSDrives are powered by PSProviders, which are underlying components that provide
access to data stores.
💡 To access a PSDrive, use a special prefix in the path, like we do C: to access filesystem
drive.
Get-ChildItem Env:\*path*
C: and D : (and other drive letters): Used to access the filesystem, just like in Windows Explorer
Cmdlets
PowerShell command that performs a specific task and can be written in C# or in another .NET
language.
Functions
Functions are a collection of PowerShell commands that should be run following a certain logic.
function Verb-Noun {
<#
<Optional help text>
#>
param(
[data type] $Parameter
)
<...Code: Function Logic...>
}
Calling a Function:
Parameters:
Allow to pass values to functions, enhancing their flexibility and reusability.
Defining parameters:
function Invoke-Greeting {
param (
[string] $Name
)
Write-Output "Hello $Name!"
}
function Invoke-Greeting {
[cmdletbinding()]
param (
[Parameter(Mandatory)]
[string] $Name
)
Write-Output "Hello $Name!"
}
SupportsShouldProcess:
Adding [CmdletBinding(SupportsShouldProcess)] , enables the -WhatIf and -Confirm parameters in
function.
To use SupportsShouldProcess effectively, will need to call ShouldProcess() for each item being
processed.
Example Code:
function Invoke-Greeting {
[CmdletBinding (SupportsShouldProcess) ]
param (
$Name
)
Accept the input by passing values directly to the parameters of the function when calling it, and
PowerShell automatically matches the positional parameters.
Specify the parameter names when calling the function, This allows to pass arguments in any order.
Example Code :
function Invoke-Greeting {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[string] $Name
)
process {
Write-Output "Hello $Name!"
}
}
2. By property name:
Comment-based help:
Comments simplify the adjustment or reuse of function code.
<#
.SYNOPSIS
<Describe the function shortly.>
.DESCRIPTION
<More detailed description of the function.>
.PARAMETER Name
<Add a section to describe each parameter, if function has one or
more parameters.>
.EXAMPLE
<Example how to call the function>
Error Handling:
try{
New-PSSession -ComputerName $Computer -ErrorAction Stop
}
catch {
Write-Warning -Message "Couldn't connect to Computer: $Computer"
}
As terminating errors are caught, the action defined in the catch block is triggered.
.DESCRIPTION
This is just for learning purpose
.PARAMETER Identity
If the parameter is specified, an individual greetin is added.
.EXAMPLE
Write-HelloWord -Ideentity "prash"
[cmdletbinding()]
param(
[string]$Identity
)
if (![string]::IsNullOrEmpty($Identity)) {
$appendStr = " Hello $Identity!"
}
💡 Get-Alias can also be used to check if specific alias exists using the -Name parameter.
New-Alias:
Use New-Alias to create a new alias within the current PowerShell session.
💡 These aliases are not set permanently, so once session exit, alias will not work anymore.
Export-Alias:
Export one or more aliases with Export-Alias .
Import-Alias:
Used to import aliases from a file into current PowerShell session.
Modules
Modules are a collection of PowerShell commands and functions that can be easily shipped and
installed on other systems.
💡 The PowerShell Gallery, is the central repository for PowerShell content, which
contains thousands of helpful modules, scripts and Desired State Configuration(DSC)
resources.
To see which modules are available to import, including that come pre-installed with Windows,
using the Get-Module -ListAvailable :
To find which commands are available in a module using Get-Command -Module <modulename> :
Most necessary files commonly seen in modules — .psm1 file and .psd1 file.
.psm1 file contains the scripting logic that module should provide, and can also use it to import
other functions within a module.
.psd1 file is the manifest of module, which include information about the module.
1. Define the path where module should be save in the $path variable.
3. The -RootModule parameter specifies the name of the PowerShell module file.
4. Using Set-Content cmdlet, create the Module.psm1 file which contains the code logic.
💡 To use the module in PowerShell session, either import it directly into session or copy it
into one of the PSModule paths.
PSModule path are directories that are searched for modules when using Import-Module
cmdlet.
Import-Module MyModule
OR
Import-Module $env:TEMP\MyModule\MyModule.psd1
💡 Module Manifest Options allow to specify the author,the description, or modules that are
required to install the module, using the RequiredModules hashtable.
Further Readings
1. System Namespace: https://learn.microsoft.com/en-us/dotnet/api/system
3. about_Automatic_Variables: https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_automatic_variables
5. about_Scopes: https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_scopes
6. about_Comparison_Operators: https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_comparison_operators
7. about_Assignment_Operators: https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_assignment_operators
8. about_Operators: https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_operators
9. ForEach-Object: https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/foreach-object
16. PowerShell Basics for Security Professionals Part 6 – Pipeline by Carlos Perez:
https://youtube.com/watch?v=P3ST3lat9bs