Powershell
Powershell
Considering the features of any scripting language, you can use PowerShell to
automate the system management process and task. It lets you build, test, and deploy
solutions in CI/CD environments.
PowerShell is built on the .NET Common Language Runtime (CLR), which means all
the inputs and outputs are .NET objects. You do not have to parse text output to retrieve
information from it.
cmdlets
Cmdlets are PowerShell’s internal commands. These cmdlets will return one or more
objects to the pipeline where at the end of that pipeline, we mention some properties of
the objects in the following table to see their values displayed on the screen.
Command Description
In any registry, children are the subkeys of the current key. To get
Get-ChildItem the required details, you can use the following command.
Get-ChildItem Run this command to list all the children recursively of the
-recurse current PSdrive, folder, or registry key.
Get-ChildItem -rec Use this command To include the hidden folders (directories).
-force
(Get-ChildItem).na Run any of these commands to get the list file and directory
me or names in the current folder.
Get-ChildItem
-name
PSdrives
PSdrives are the collection of entities grouped together so they can be accessed as a
filesystem drive. The “PSprovider” does this grouping.
By default, a PS session can access several PSdrives including c:, env:, alias:, and
HKLM:, where c: refers to the usual Windows c-drive; env: is the space of Windows
environmental variables; alias: is the collection of cmdlet aliases; and HKLM is a hive in
the registry.
Any PS session will enter the user’s home folder. If you want to switch from a PS
session to another PSdrive and retrieve the information from that drive, consider the
following commands:
Commands Description
Set-Location env-
Env:\> This command will get you all the environment variables.
Get-Childitem
Env:\> Use this command to get the environment variables of
Get-Childitem “userprofile.”
userprofile
Alias:\> Run this command to get all the children of all aliases.
Get-Childitem
Alias:\> Use this command to get the “C:/>” prompt again, back to
Set-Location C:\ the default drive.
C:\Users\user_na Run this command to find what alias “ls” stands for.
me>$alias:ls
Pipelines
Cmdlets uses the pipelines to pass the objects but not the character streams like Unix.
The pipeline character is | (ASCII 124), followed by a command that handles the output
passed through the pipeline. The pipeline consists of the following three stages.
Command Description
"data.txt.rtf" | Changes the old file names and file extensions to the new
Rename-Item -NewName ones
"data_new.txt.rtf"
Get-ChildItem | Displays the list of the names of all the files that are present
Select-Object basename | in the current folder sorted in alphabetical order.
Sort-Object *
Get-ChildItem *.txt | Gives the error message that Move-Item lacks input
Move-Item ..\
Alias
Cmdlets come with several aliases. The following table highlights a few of aliases, along
with their descriptions:
Command Description
Format-Table Formats the table with selected properties for each object in
each column
Get-Command Provides you with commands from the current session only
Get-ItemPropertyValue Gives the current value for a specified property while using
-Path '.\data.txt' -Name the name parameter
LastWriteTime
New-Item -Path .\ -Name Creates a new file, directory, symbolic link, registry key, or
"testfile1.txt" -ItemType registry entry
"file" -Value "This is a text
string."
Rename-Item -Path Renames the old item name with the new name
“old_name” -NewName
“new_name”
Operators
● Arithmetic Operators
Operator Description Example
+ Adds integers; concatenates 6+2
strings, arrays, and hash tables. "file" + "name"
@(1, "one") + @(2.0, "two")
@{"one" = 1} + @{"two" = 2}
+ Makes a number out of an object 123
- Subtracts one value from another 6-2
- Calculates the opposite number - -6
(Get-Date).AddDays(-1)
Operator Precedence
● Assignment Operators
Operator Description
= Sets a variable’s value to the specified value
+= Increases a variable’s value by the specified value or appends the
specified value to the existing value
-= Decreases a variable’s value by a specified value
*= Multiplies a variable’s value by a specified value, or appends the
specified value to the existing value
/= Divides a variable’s value by a specified value
%= Divides the variable’s value by a specified value and then assigns the
remainder (modulus) to the variable.
#ERROR Increases a variable’s value, assignable property, or array element by 1.
!
-- Decreases the variable’s value, assignable property, or array element by
1.
● Comparison Operators
● Logical Operators
● Redirection Operator
● Type Operators
Operator Description
Regular Expressions
A regular expression is a pattern that is used to match text that includes literal
characters, operators, and other constructs. PowerShell regular expressions are
case-insensitive by default.
● Character Groups
These allow you to match any number of characters one time, while [^character group]
only matches characters NOT in the group.
● Character Range
A pattern can also be a range of characters. The characters can be alphabetic [A-Z],
numeric [0-9], or even ASCII-based [ -~] (all printable characters).
● Numbers
The \d character class will match any decimal digit. Conversely, \D will match any
non-decimal digit.
● Word Character
The \w character class will match any word character [a-zA-Z_0-9]. To match any
non-word character, use \W.
● Wildcard
The period (.) is a wildcard character in regular expressions. It will match any character
except a newline (\n).
● Whitespace
Whitespace is matched using the \s character class. Any non-whitespace character is
matched using \S. Literal space characters ' ' can also be used.
● Escaping Characters
The backslash (\) is used to escape characters so the regular expression engine doesn’t
parse them.
Flow Control
● ForEach-Object
ForEach-Object is a cmdlet that allows you to iterate through items in a pipeline, such
as with PowerShell one-liners. ForEach-Object will stream the objects through the
pipeline.
Although the Module parameter of Get-Command accepts multiple values that are
strings, it will only accept them via pipeline input using the property name, or parameter
input.
If you want to pipe two strings by value to Get-Command for use with the Module
parameter, use the ForEach-Objectcmdlet:
● For
A “for” loop iterates while a specified condition is true.
For example:
Example 1:
$number = Get-Random -Minimum 1 -Maximum 10
do {
$guess = Read-Host -Prompt "What's your guess?"
if ($guess -lt $number) {
Write-Output 'Too low!'
}
elseif ($guess -gt $number) {
Write-Output 'Too high!'
}
}
until ($guess -eq $number)
Example 2:
For example:
Variables
PowerShell allows you to store all types of values. For example, it can store command
results and command expression elements like names, paths, and settings. Here are
some of PowerShell’s different variables.
● User-created variables: These are created and maintained by the user. The
variables you create at the PowerShell command line will only exist until the
PowerShell window is open. When you close the PowerShell window, these
variables are deleted. If you want to save a variable, you need to add it to your
PowerShell profile. You can create variables and declare them with three
different scopes: global, script, or local.
● Automatic variables: These variables store the state of PowerShell and are
created by PowerShell. Only PowerShell can change their values as required to
maintain accuracy. Users can’t change these variables’ value. For example, the
$PSHOME variable will store the path to the PowerShell installation directory.
To create a new variable, you need to use an assignment statement and assign a value to the
variable. There is no need to declare the variable before using it. The default value of all
variables is $null.
For example-
$MyVariable = 1, 2, 3
$MyVariable
Function
For example:
function Get-Version {
$PSVersionTable.PSVersion
}
Copy the entire module folder into the Modules directory. You can use any method to
copy the folder, including Windows Explorer, Cmd.exe, and PowerShell.
Get-Module -ListAvailable
Import-Module <module-name>
Remove-Module <module-name>
$Env:PSModulePath
$Env:PSModulePath += ":<path>"
Hash Tables
A hash table is a complex data structure to store data in the form of key-value pairs. We
also refer to a hash table as a dictionary or associative array. To understand a hash
table, consider a series of IP addresses and the respective computer names. A hash
stores this data in the form of key-value pairs, where IP addresses refer to keys and
computer names to their corresponding values.
For example:
$hash = @{}
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}
[hashtable]$hash = [ordered]@{
Number = 1; Shape = "Square"; Color = "Blue"}
$hash
$hash["<key>"] = "<value>"
For example, you can add a "Time" key with a value of "Now" to the hash table with the
following statement format:
$hash["Time"] = "Now"
Or
$hash.Add("Time", "Now")
Or, you can remove the key with this statement format:
$hash.Remove("Time")
Get-Command -Noun Variable # the Variable Cmdlets $Host Reference to the application hosting the $OFS Output Field Separator. Specifies
Get-ChildItem variable: # listing all variables using the POWERSHELL language the character that separates the
variable drive $Input Enumerator of objects piped to a script elements of an array when the
$LastExitCode Exit code of last program or script array is converted to a string. The
# strongly-typed variable (can contain only integers) $Matches Exit code of last program or script default value is: Space.
[int]$number=8 $MyInvocation An object with information about the $OutputEncoding Determines the character
current command encoding method that Windows
# attributes can be used on variables $PSHome The installation location of Windows PowerShell uses when it sends
[ValidateRange(1,10)][int]$number = 1 PowerShell text to other applications
$number = 11 #returns an error $profile The standard profile (may not be $PSDefaultParameterValues Specifies default values for the
present) parameters of cmdlets and
# flip variables $Switch Enumerator in a switch statement advanced functions
$a=1;$b=2 $True Boolean value for TRUE $PSEmailServer Specifies the default e-mail server
$a,$b = $b,$a $False Boolean value for FALSE that is used to send e-mail
$PSCulture Current culture messages
# multi assignment $PSUICulture Current UI culture $PSModuleAutoLoadingPreference Enables and disables
$a,$b,$c = 0 $PsVersionTable Details about the version of Windows automatic importing of modules
$a,$b,$c = 'a','b','c' PowerShell in the session. "All" is the default.
$a,$b,$c = 'a b c'.split() $Pwd The full path of the current directory $PSSessionApplicationName Specifies the default application
name for a remote command that
# create read only variable (can be overwritten with - Windows PowerShell Preference Variables uses WS-Management technology
Force) $PSSessionConfigurationName Specifies the default session
Set-Variable -Name ReadOnlyVar -Value 3 -Option $ConfirmPreference Determines whether Windows configuration that is used for
ReadOnly PowerShell automatically PSSessions created in the current
prompts you for confirmation session
# create Constant variable (cannot be overwritten) before running a cmdlet or $PSSessionOption Establishes the default values for
Set-Variable -Name Pi -Value 3.14 -Option Constant function advanced user options in a
$DebugPreference Determines how Windows remote session
Windows PowerShell Automatic Variables PowerShell responds to
(not exhaustive) $VerbosePreference Determines how Windows
debugging PowerShell responds to verbose
$$ Last token of the previous $ErrorActionPreference Determines how Windows messages generated by a script,
command line PowerShell responds to a non- cmdlet or provider
$? Boolean status of last command terminating error $WarningPreference Determines how Windows
$^ First token of the previous $ErrorView Determines the display format PowerShell responds to warning
command line of error messages in Windows messages generated by a script,
$_, $PSItem Current pipeline object PowerShell cmdlet or provider
$Args Arguments to a script or function $FormatEnumerationLimitDetermines how many $WhatIfPreference Determines whether WhatIf is
$Error Array of errors from previous enumerated items are included automatically enabled for every
commands in a display command that supports it
$ForEach Reference to the enumerator in a $MaximumHistoryCount Determines how many
foreach loop commands are saved in the
$Home The user’s home directory command history for the
current session