Skip to content
All quick references

PowerShell

17 snippets · 4 sections

Everyday PowerShell - the pipeline, objects, filtering, error handling, REST calls, and the Active Directory cmdlets that make up most Windows automation.

01

Pipeline & Objects

The pipeline passes objects, not text

  • Each cmdlet outputs .NET objects with properties/methods - the next cmdlet in the pipeline receives those objects, not printed text
  • Use Get-Member to see what properties and methods an object exposes
  • Filter left, format right - narrow the object set before formatting, since formatting for display makes objects harder to reuse

Filter, sort, select, format

Get-Process |
  Where-Object { $_.CPU -gt 50 } |
  Sort-Object CPU -Descending |
  Select-Object -First 5 Name, Id, CPU |
  Format-Table -AutoSize

Common comparison & logical operators

OperatorMeaning
-eq / -neEqual / not equal
-gt / -ltGreater than / less than
-ge / -leGreater or equal / less or equal
-like / -notlikeWildcard match (*, ?)
-match / -notmatchRegex match
-contains / -inCollection contains value / value in collection
-and / -or / -notLogical operators
Comparison operators are case-insensitive by default; prefix with c (e.g. -ceq, -clike) to force case-sensitive.

Error handling

try {
  Get-Item -Path 'C:\does-not-exist.txt' -ErrorAction Stop
} catch {
  Write-Warning "Failed: $($_.Exception.Message)"
} finally {
  Write-Host "Done."
}
02

Active Directory Module

Import the module

Import-Module ActiveDirectory

Find a user

Get-ADUser -Identity jdoe -Properties *

Get-ADUser -Filter "Department -eq 'IT'" -Properties Title, EmailAddress |
  Select-Object Name, Title, EmailAddress

Create / modify a user

New-ADUser -Name "Jane Doe" -SamAccountName jdoe `
  -UserPrincipalName jdoe@contoso.com `
  -Path "OU=Users,OU=Corp,DC=contoso,DC=com" `
  -AccountPassword (Read-Host -AsSecureString "Password") `
  -Enabled $true

Set-ADUser -Identity jdoe -Title "IT Analyst" -Department "IT"

Groups & membership

Add-ADGroupMember -Identity "IT-Staff" -Members jdoe
Remove-ADGroupMember -Identity "IT-Staff" -Members jdoe -Confirm:$false

Get-ADGroupMember -Identity "IT-Staff" -Recursive |
  Select-Object Name, SamAccountName

Common filters & lookups

TaskCommand
Locked-out usersSearch-ADAccount -LockedOut
Disabled usersSearch-ADAccount -AccountDisabled
Accounts expiring soonSearch-ADAccount -AccountExpiring
Password never expiresGet-ADUser -Filter 'PasswordNeverExpires -eq $true'
Computers by OSGet-ADComputer -Filter "OperatingSystem -like '*Server*'"
Unlock an accountUnlock-ADAccount -Identity jdoe
Reset a passwordSet-ADAccountPassword -Identity jdoe -Reset -NewPassword (Read-Host -AsSecureString)

Organizational units

Get-ADOrganizationalUnit -Filter 'Name -like "*Sales*"' |
  Select-Object Name, DistinguishedName

New-ADOrganizationalUnit -Name "Contractors" -Path "OU=Corp,DC=contoso,DC=com"
03

Group Policy & Results

Export a Group Policy report

Get-GPOReport -Name "Default Domain Policy" -ReportType HTML -Path "C:\GPOExport\DefaultDomainPolicy.html"

Generate a computer policy results report

gpresult /h C:\Reports\gpreport.html
04

Microsoft Graph & Azure

Connect with the Microsoft Graph SDK

Install-Module Microsoft.Graph -Scope CurrentUser

Connect-MgGraph -Scopes "User.Read.All", "Group.ReadWrite.All"
Get-MgContext | Select-Object Account, Scopes

Read users & groups via Graph cmdlets

Get-MgUser -Filter "startsWith(displayName,'Jane')" -Property DisplayName, Mail, Id

Get-MgGroupMember -GroupId $groupId |
  ForEach-Object { Get-MgUser -UserId $_.Id }

App-only auth for unattended scripts

$cert = Get-ChildItem Cert:\CurrentUser\My\<thumbprint>

Connect-MgGraph -ClientId $appId -TenantId $tenantId -Certificate $cert

Raw calls with Invoke-MgGraphRequest

Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/me"

Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/users" -Body @{
  accountEnabled    = $true
  displayName       = "Jane Doe"
  mailNickname      = "jdoe"
  userPrincipalName = "jdoe@contoso.com"
  passwordProfile   = @{ forceChangePasswordNextSignIn = $true; password = "P@ssw0rd1!" }
}

Az module - resource management

Connect-AzAccount
Set-AzContext -Subscription "Contoso Prod"

Get-AzResourceGroup | Select-Object ResourceGroupName, Location

Get-AzVM -Status |
  Select-Object Name, PowerState, ResourceGroupName