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.
Filtering Data With Where-Object¶
?
which is an alias for Where-Object
, is used to filter all the data given to it.
Example
Example
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
This shows the full help on the PowerShell console
This opens a new window showing the full help content and offers other options such as Find
To Query Windows Services¶
This gets any Windows service that has the word "Xbox" in it.
This gets any Windows service that has the word "x" in it.
Putting *
around the word or letter finds anything that contains it.
Example syntax:
Get-Service [[-Name] <System.String[]>] [-ComputerName <System.String[]>] [-DependentServices] [-Exclude <System.String[]>] [-Include <System.String[]>] [-RequiredServices] [<CommonParameters>]
In this part
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:
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¶
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:
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
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
More info about Get-ChildItem cmdlet
Write Output to a File or String¶
Example:
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
You can also use the -milliseconds
parameter to specify how long the resource sleeps in milliseconds.
How to Stop/Kill a a Process or (.exe) Executable in Powershell¶
Using native PowerShell cmdlet
Using taskkill.exe
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.
Display All the Tcp and Udp Ports on Which the Computer Is Listening¶
Copy the Result of a Command to Clipboard Automatically¶
Add | clip
at the end the command
Example:
Example:
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
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:
Using the &
Call operator
- Method 2:
- Method 3
This example uses PowerShell Core
Enclosing Strings That Have a Lot of Single and Double Quotation Marks¶
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:
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.