Skip to content

Basic PowerShell Tricks and Notes

The following PowerShell series is designed for newcomers to PowerShell who want to quickly learn the essential basics, the most frequently used syntaxes, elements and tricks. It can also be used by advanced users as a quick reference or those who want to sharpen their skills.

The main source for learning PowerShell is Microsoft Learn websites. There are extensive and complete guides about each command/cmdlet with examples.

PowerShell core at Microsoft Learn

You can also use the Windows Copilot for asking any PowerShell related questions, code examples etc.

This is part 1 of this series, find other parts here:


Pipeline Variable

$_ is the variable for the current value in the pipeline.

Examples


Filtering Data With Where-Object

? which is an alias for Where-Object, is used to filter all the data given to it.

Where-Object

Example

Get-PSDrive | ?{$_.free -gt 1}

Example

Get-PSDrive | Where-Object {$_.free -gt 1}


Show the Properties of an Object Selectively

Select or Select-Object show the properties that we want to see from an object

If we use * then all of the properties will be shown and from there we can choose which properties to add.

Example:

Get-PSDrive | Where-Object {$_.free -gt 1} | Select-Object -Property *

Get-PSDrive | Where-Object {$_.free -gt 1} | Select-Object -Property root, used, free


Looping Using Foreach-Object

The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified using the InputObject parameter.

In other words: for every item in the pipe, run this line.

Examples:

Get-PSDrive | Where-Object { $_.free -gt 1 } | Select-Object -Property root, used, free | ForEach-Object { 'zebra' }
Get-PSDrive | Where-Object { $_.free -gt 1 } | Select-Object -Property root, used, free | ForEach-Object { Write-Host 'Free Space for ' $_.Root 'is' ($_.free / 1gb ) }

The parenthesis, ($_.free/1gb ) must be there if we want to modify one of the output strings.


To Get Online Help About Any Cmdlet

These commands open the webpage for the specified cmdlet or command

Get-help <cmdlet> online
Get-Help dir online
Get-Help ForEach-Object online


This shows the full help on the PowerShell console

Get-help Get-Service -full


This opens a new window showing the full help content and offers other options such as Find

Get-help Get-Service -ShowWindow


To Query Windows Services

This gets any Windows service that has the word "Xbox" in it.

Get-Service "*xbox*"

This gets any Windows service that has the word "x" in it.

Get-Service "*x*"

Putting * around the word or letter finds anything that contains it.

Get-Service "*x*" | Sort-Object status

Example syntax:

Get-Service [[-Name] <System.String[]>] [-ComputerName <System.String[]>] [-DependentServices] [-Exclude <System.String[]>] [-Include <System.String[]>] [-RequiredServices] [<CommonParameters>]

In this part

Get-Service [[-Name] <System.String[]>]

The -Name Parameter accepts <System.String[]>, which is a StringList, and when [] is included, that means there can be multiple inputs/strings, separated by comma ,.

So [[-Name] <System.String[]>] can be used like this:

Get-Service -Name WinRM,BITS,*Xbox*

Also in another similar example syntax:

Get-Service [-ComputerName <System.String[]>] [-DependentServices] -DisplayName <System.String[]> [-Exclude <System.String[]>] [-Include <System.String[]>] [-RequiredServices] [<CommonParameters>]

Everything is inside a bracket except for -DisplayName, that means it is mandatory. If a parameter is inside a bracket, that means it is optional.


How to Suppress Errors in Powershell

-ErrorAction SilentlyContinue

Everything you wanted to know about exceptions

Try/Catch will only 'trigger' on a terminating exception. Most cmdlets in PowerShell, by default, won't throw terminating exceptions. You can set the error action with the -ErrorAction or -ea parameters:

Do-Thing 'Stuff' -ErrorAction Stop

Be careful when using -ErrorAction Stop. If using it in loops like with ForEach-Object, it will stop the entire loop after the first encounter of error.

Handling Errors the PowerShell Way

Tip: If you set

$ErrorActionPreference = 'Stop'

In your PowerShell code, either locally or globally for the entire script, Write-Error will cause the script to stop because it will be like throwing an error.


Get File Signature of All of the Files in a Folder

This will check all of the files' signatures in the current directory

Get-ChildItem -File | ForEach-Object -Process {Get-AuthenticodeSignature -FilePath $_}

More info about Get-ChildItem cmdlet


Write Output to a File or String

> output.txt

Example:

ipconfig /all > mynetworksettings.txt

about_Redirection


How to Add Delay/Pause to the Execution of Powershell Script

To sleep a PowerShell script for 5 seconds, you can run the following command

Start-Sleep -Seconds 5

You can also use the -milliseconds parameter to specify how long the resource sleeps in milliseconds.

Start-Sleep -Milliseconds 25

Start-Sleep


How to Stop/Kill a a Process or (.exe) Executable in Powershell

Using native PowerShell cmdlet

Stop-Process -Name "Photoshop"

Stop-Process

Using taskkill.exe

taskkill /IM "photoshop app.exe" /F

taskkill


Automatically Answer “Yes” to a Prompt in Powershell

Use –force at the end of the command


Displays All Information in the Current Access Token

The command below displays all information in the current access token, including the current user name, security identifiers (SID), privileges, and groups that the current user belongs to.

whoami /all

whoami


Display All the Tcp and Udp Ports on Which the Computer Is Listening

netstat -a

netstat


Copy the Result of a Command to Clipboard Automatically

Add | clip at the end the command

Example:

Get-TimeZone | clip

Example:

rg -i -F URL: | clip


How to Scan 2 Text Files for Differences and Pipe the Difference to a Third File

$File1 = "C:\Scripts\Txt1.txt"
$File2 = "C:\Scripts\Txt2.txt"
$Location = "C:\Scripts\Txt3.txt"

Compare-Object -ReferenceObject (Get-Content -Path $File1) -DifferenceObject (Get-Content -Path $File2) | Format-List | Out-File -FilePath $Location

Compare-Object


Difference Between Strings and StringLists

This is Stringlist in PowerShell:

[String[]]

And this is a string

[String]

When we define Stringlist in a parameter, then the argument will keep asking for multiple values instead of 1, if we want to stop adding arguments for the parameter, we have to enter twice.


How to Run a Powershell (.PS1) Script ?

  • Method 1:
&"Path\To\PS\Script.ps1"

Using the & Call operator

  • Method 2:
Set-Location 'Path\To\Folder\OfThe\Script'
.\Script.ps1
  • Method 3
pwsh.exe -File 'Path\To\Folder\OfThe\Script.ps1'

This example uses PowerShell Core


Enclosing Strings That Have a Lot of Single and Double Quotation Marks

$string =@"

Some string text

"@

$string

the markers @" and "@ indicating the beginning and end of the string must be on separate lines.


How to Find the Type of the Output of a Command in Powershell

Using GetType()

Examples:

(Get-BitlockerVolume -MountPoint "C:").KeyProtector.keyprotectortype.GetType()
(Get-NetTCPConnection).GetType()


Make Sure to Use Pascal Case for Variable Names

Pascal Case requires variables made from compound words and have the first letter of each appended word written with an uppercase letter.

Example: $Get-CurrentTime

This will make your code readable and more understandable.