Saturday, July 29, 2023

PowerShell notes from my scratch pad

The Basics


Commands = cmdlets

Cmdlet = function or task-based script

Cmdlets can be used individually or in combo with more complex tasks.

Cmdlet format = verb-noun (i.e., Get-Service, Restart-Computer, Add-User, etc.)

The biggest advantage of Powershell is that it is an object-based shell.

Every object in Powershell is a .NET object from the .NET framework class.

Pipelines = used to connect a group of cmdlets together to build a complex task.

Pipeline Syntax

PS> cmdlet1 | cmdlet2 -parameter1 arguement1 | cmdlet3 -paramenter1 arguement1 arguement2

Example:

PS > Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 4 -Property ProcessName CPU, VirtualMemorySize | Format-Table

ProcessName      CPU         VirtualMemorySize
-----------      ---         -----------------
vpnui           865.078125      207405056
RuntimeBroker   243.046875      398295040
accuweather     189.171875      357261312
explorer        134.109375      610177024

Aliases

Aliases = used as pointers for cmdlets to make it easy to remember long commands or make them more recognizable.

Get-ChildItem cmdlet = “dir” for DOS and “ls” for UNIX to list contents of a folder

These aliases can be used in Powershell.

No Aliases Example

PS > Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 5 -Property ProcessName, CPU, VirtualMemorySize | Format-Table

Alias Example

PS > gps | Sort -Property CPU -Des | Select -First 5 -Property ProcessName, CPU, VirtualMemorySize | FT

To get list of alises, use the following command (let)

PS:> Get-Alias

Note: You can create your own aliases but must persist them to be used at another time. It is highly preferred to use Powershell Profiles instead.

Variables and Data Types

Variables = defined with “$” as the prefix, i.e., $var, $arr4, etc.

In this example, we define different data types, but Powershell still can perform a math operation since it infers all variables should be treated as numbers if adding all together:

PS > $a = 1; $a.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType


PS:> $b = "2"; $b.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object


PS:> $c = 3.5; $c.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Double System.ValueType


PS:> $a + $b + $c

6.5

Comparison Operators

 

Not equal = -ne

Equal = -eq

Less than = -lt

Greater than = -gt

Contain = -contains

Not contain = -notcontains

Less than or equal to = -le

 

Wildcards


Like = -like

Not like = -notlike

Match = -match

Not a match = -notmatch

Replace = -replace

 

Working with Arrays and hash tables

Arrays

· Array in Powershell is zero based list of objects.

· No need to define the data type like in C#.

· Array can be defined simply by @() or create a variable and assign the list to it

Examples and output:

PS:> $arr = @()

PS:> $arr = 1,2,3,4,5

PS:> $arr.GetType()


IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array


PS:> $arr[0]
1
PS:> $arr[3]
4
PS:> $arr[4]
5
PS:> $arr
1
2
3
4
5

Hash Tables

Syntax - @{}

$ht = @{}


Working with Script Files

All Powershell files have a .ps1 extension.

Powershell files can be created in any text editor but cannot be executed by simply double-clicking the file (for security reasons)

.ps1 = .exe file

Powershell scripts have $args built-in functionality, just like EXE files.

For example:

$firstname = $args[0]

$lastname = $args[1]

Write-Host “Hello, $firstname $lastname”


Powershell Script Execution (Policies)

Execution policy: This is a security policy that defines how Powershell scripts should be executed on your system. There are four options:

1. Restricted: (Default for Windows 2012 R2) No script allowed to execute.

2. RemoteSigned: Script execution only allowed for scripts you wrote on your local, but not external scripts (i.e., Internet)

3. AllSigned: All scripts must be signed by a trusted publisher, even on your local

4. Unrestricted: All scripts can be executed.

To view your currently set execution policy, type the following:

PS:> Get-ExecutionPolicy

Unrestricted


Running Powershell Scripts

You can either navigate to the folder that contains the Powershell script and type the following:

PS C:\My_Powershell_Scripts\Greetings.ps1 Harry Douglass

Hello, Harry Douglass

Or by typing ./<scriptfilename>.ps1


Note: PowerShell ISE is considered a legacy GUI and supports PS 5, it is recommended to now use Visual Studio Code IDE and install the Powershell extension to get robust IntelliSense support, and incorporates PowerShell Core.

Getting Help

The Powershell console has robust help features.

Use the “Get-Help” cmdlet with any cmdlet you wish to know more about, for example:

PS:> Get-Help Get-Process

Getting more detailed information

PS:> Get-Help Get-Process -Detailed

Getting examples of actual usage of a cmdlet

PS :> Get-Help Get-Process -Examples

Lastly, reading long pieces of information in the console window can be difficult. Powershell has a “-ShowWindow” parameter to help with this: