-
Notifications
You must be signed in to change notification settings - Fork 169
Basic PowerShell tricks and notes
This page is designed for beginners and newcomers to PowerShell who want to learn the essential basics and the most frequently used syntaxes elements and tricks fast. It should help you jump start your journey as a PowerShell user.
The main source for learning PowerShell is Microsoft Learn website. There are extensive and complete guides about each command/cmdlet with examples.
PowerShell core at Microsoft Learn
$_
is the variable for the current value in the pipeline.
?
which is an alias for Where-Object
, is used to filter all the data given to it.
Example
Get-PSDrive | ?{$_.free -gt 1}
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 | ?{$_.free -gt 1} | select *
Get-PSDrive | ?{$_.free -gt 1} | select root, used, free
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.
i.e. For every item in the pipe, run this line.
Examples:
Get-PSDrive | ?{$_.free -gt 1} | select root, used, free | ForEach-Object{"zebra"}
Get-PSDrive | ?{$_.free -gt 1} | select 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.
Opens the webpage for the specified command
Get-help cmdlet –online
Example:
Get-Help ForEach-Object –online
Get-Help dir –online
Shows the full help on the PowerShell console
Get-help get-service -full
Opens a new window showing the full help content and offers other options such as Find
Get-help get-service -ShowWindow
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.
-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
Careful when using -ErrorAction Stop
, If using it in loops like with ForEach-Object
, then 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.
This will check all of the files in the current directory and show an error for folders, you can add -ErrorAction SilentlyContinue
to the Get-AuthenticodeSignature
cmdlet to ignore the errors.
Get-ChildItem | ForEach-Object -Parallel {Get-AuthenticodeSignature $_.Name}
This will recursively check only the files in the current directory and sub-directories, no folder is piped.
Get-ChildItem -Recurse -File | ForEach-Object -Parallel {Get-AuthenticodeSignature $_.Name}
> output.txt
Example:
ipconfig /all > mynetworksettings.txt
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
Using native PowerShell cmdlet
Stop-Process -Name "Photoshop"
Using taskkill.exe
taskkill /IM "photoshop app.exe" /F
Use –force
at the end of the command
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
netstat -a
Add | clip
at the end the command
Example:
Get-TimeZone | clip
Example:
rg -i -F URL: | clip
$File1 = "C:\Scripts\Txt1.txt"
$File2 = "C:\Scripts\Txt2.txt"
$Location = "C:\Scripts\Txt3.txt"
Compare-Object (get-content $File1) (get-content $File2) | format-list | Out-File $Location
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.
- 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
$string =@"
Some string text
"@
$string
the markers @"
and "@
indicating the beginning and end of the string must be on separate lines.
Using GetType()
Examples:
(Get-BitlockerVolume -MountPoint "C:").KeyProtector.keyprotectortype.GetType()
(get-nettCPConnection).GetType()
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
- Create AppControl Policy
- Create Supplemental Policy
- System Information
- Configure Policy Rule Options
- Simulation
- Allow New Apps
- Build New Certificate
- Create Policy From Event Logs
- Create Policy From MDE Advanced Hunting
- Create Deny Policy
- Merge App Control Policies
- Deploy App Control Policy
- Get Code Integrity Hashes
- Get Secure Policy Settings
- Update
- Sidebar
- Validate Policies
- View File Certificates
- Introduction
- How To Generate Audit Logs via App Control Policies
- How To Create an App Control Supplemental Policy
- The Strength of Signed App Control Policies
- How To Upload App Control Policies To Intune Using AppControl Manager
- How To Create and Maintain Strict Kernel‐Mode App Control Policy
- App Control Notes
- How to use Windows Server to Create App Control Code Signing Certificate
- Fast and Automatic Microsoft Recommended Driver Block Rules updates
- App Control policy for BYOVD Kernel mode only protection
- EKUs in App Control for Business Policies
- App Control Rule Levels Comparison and Guide
- Script Enforcement and PowerShell Constrained Language Mode in App Control Policies
- How to Use Microsoft Defender for Endpoint Advanced Hunting With App Control
- App Control Frequently Asked Questions (FAQs)
- Create Bootable USB flash drive with no 3rd party tools
- Event Viewer
- Group Policy
- How to compact your OS and free up extra space
- Hyper V
- Overrides for Microsoft Security Baseline
- Git GitHub Desktop and Mandatory ASLR
- Signed and Verified commits with GitHub desktop
- About TLS, DNS, Encryption and OPSEC concepts
- Things to do when clean installing Windows
- Comparison of security benchmarks
- BitLocker, TPM and Pluton | What Are They and How Do They Work
- How to Detect Changes in User and Local Machine Certificate Stores in Real Time Using PowerShell
- Cloning Personal and Enterprise Repositories Using GitHub Desktop
- Only a Small Portion of The Windows OS Security Apparatus
- Rethinking Trust: Advanced Security Measures for High‐Stakes Systems
- Clean Source principle, Azure and Privileged Access Workstations
- How to Securely Connect to Azure VMs and Use RDP
- Basic PowerShell tricks and notes
- Basic PowerShell tricks and notes Part 2
- Basic PowerShell tricks and notes Part 3
- Basic PowerShell tricks and notes Part 4
- Basic PowerShell tricks and notes Part 5
- How To Access All Stream Outputs From Thread Jobs In PowerShell In Real Time
- PowerShell Best Practices To Follow When Coding
- How To Asynchronously Access All Stream Outputs From Background Jobs In PowerShell
- Powershell Dynamic Parameters and How to Add Them to the Get‐Help Syntax
- RunSpaces In PowerShell
- How To Use Reflection And Prevent Using Internal & Private C# Methods in PowerShell