Powershell Snippets
# Help on powershell commandpowershell -helppwsh -help
# Run a Specific Commandpowershell -Command "Get-Process"# Run commands, do not load profilepowershell -NoProfile -c
# Check hosts filenotepad C:\Windows\System32\drivers\etc\hosts
# Test network connection to a specific host## Test-Network-Connection (tnc)tnc google.com -Port 443
# See Powershell script that is run on new sessions$PROFILE# Check Powershell version$PSVersionTable$PSVersionTable.PSVersion
# Get Host name$env:computername
# Write text to consoleWrite-Host "Hello World"# Write new line and textWrite-Host "`nHello`nWorld"
# cd to user's local app datacd $env:LOCALAPPDATA
# Set a variable$variableName = "Hello World"
# Set a boolean$debugMode = $true
# List environment variablesGet-ChildItem Env:
# Write a specific environment variable, example temporarily remove proxy$env:https_proxy=""
# Temporarily set an environment variable$env:https_proxy="myproxy.com:3841"
# User's home directory$env:USERPROFILE
# Switch to a different Windows Active Directory domain which is on the same network# https://dba.stackexchange.com/questions/166638/how-to-connect-remotely-to-mssql-database-from-local-using-windows-authenticatirunas /netonly /user:mydomain\myusername powershell.exe# Then run programs and commands you need under the new domain login
# Shutdown ComputerStop-Computer# Shutdown local computer, can be used to name remote computers as wellStop-Computer -ComputerName localhost
# Start-Job - start a process in background that persists after shell is closedStart-Job -ScriptBlock { <commands> }Start-Job -ScriptBlock { dolphin.exe --stylesheet C:\Users\me\Code\dolpwin-dark\blue.qss --platform windows:darkmode=2 }
# Update Modules## Run from another shell so powershell is not in use## SkipPublisherCheckspwsh -NoProfile -Command 'Update-Module -Force'
# Open item with Operating System applicationInvoke-Item .\file.txt# Open item with default operating system application aliasii .\file.txt
# Check command and its locationGet-Command <command>
# Check if a command exists and use itif (Get-Command "zoxide.exe" -ErrorAction SilentlyContinue) { # Use command}
# Convert an object to CSVGet-Process -Name pwsh | ConvertTo-Csv -NoTypeInformation
# Get data information in long formGet-Date
# Start a transcript file at a specific location to log sessionStart-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber# -Path location of file# -NoClobber prevents existing files from being overwritten.
# Multiple line (multiline) command using backtick characterscoop install fzf `neovim `
# Function with mandatory parametersfunction Get-Square { param( [Parameter(Mandatory=$true)] [int]$number ) $Number * $Number}
# Remove file or directory and files under itRemove-Item -Force -Recurse -Path .\file_or_directory
Windows Specific
Section titled “Windows Specific”# Redirect command line output to Windows clipboard, assume cat is installedhostname | Clip# Copy computer hostname to clipboardhostname | Set-Clipboard
Start-Process (Administrative Rights)
Section titled “Start-Process (Administrative Rights)”Powershell Module Start-Process
# Open in new window the program to run as administratorStart-Process -Verb RunAs powershell.ext
# Start notepad as administratorStart-Process -FilePath "notepad" -Wait -WindowStyle Maximized
Shell history
Section titled “Shell history”# Get commands from historyGet-History
# Clear shell history for last 10 commandsClear History -Count 10 -Newest
# Clear shell history for commands containing string or pattern like Help, *SyntaxClear-History -CommandLine *Help*, *Syntax
# Clear PSReadline history## Check itGet-PSReadlineOption | select -expand historysavepath | Remove-Item -whatif## Delete itGet-PSReadlineOption | select -expand historysavepath | Remove-Item# Close terminal
# Open PS Readline history to edit itcode (Get-PSReadLineOption).HistorySavePath
# Got to previous working directorycd -
# Got forward in working directory historycd +
Get-Help (like man, get usage, switches)
Section titled “Get-Help (like man, get usage, switches)”# Get help for a specific commandGet-Help Get-Process
# Get help for a specific command with examplesGet-Help Get-Process -Examples
Get-Process, Stop-Process (List running processes, Stop running processes)
Section titled “Get-Process, Stop-Process (List running processes, Stop running processes)”# Get-Process, also known as ps## Query for a process that contains xdr in the nameGet-Process | Where-Object {$_.ProcessName -like "*xdr*"}Get-Process -Name firefox
# Stop-Process, also known as kill## Stop a process with given process ID(s)Stop-Process -Id <Process ID>## Stop multiple processesStop-Process -Id 1234,5678,9101
Stop-Process -Name firefox
Manage Modules
Section titled “Manage Modules”## Get-Module (List Powershell modules), Get-InstalledModule# Get all installed modulesGet-Module -ListAvailable# orGet-InstalledModule
# Install a specific moduleInstall-Module AzureADPreview
# Force install and skip certificate checksInstall-Module AzureADPreview -Force -SkipPublisherCheck
Get-ChildItem (List directory contents, alias ls)
Section titled “Get-ChildItem (List directory contents, alias ls)”# List contents of current directoryGet-ChildItem
# List contents of specific directoryGet-ChildItem ~
Web Cmdlets
Section titled “Web Cmdlets”# Invoke-WebRequest (Make web requests, alias wget)## Download a file at a specific URL## -UseBasicParsing = for compatibility## -OutFile = required output file locationInvoke-WebRequest -Uri https://github.com/MicrosoftLearning/dp-300-database-administrator/raw/master/Instructions/Templates/AdventureWorks2017.bak -UseBasicParsing -OutFile 'AdventureWorks.bak'
# DNS Lookupnslookup google.com
Environment Variables
Section titled “Environment Variables”Set Environment Variables, Add to Path
Section titled “Set Environment Variables, Add to Path”[Environment]::SetEnvironmentVariable("HOME", "C:\Users\user1", "User")[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Users\user1\usr\bin", "User")
Source Environment Variables
Section titled “Source Environment Variables”Using dot sourcing. Create a .ps1 file, declare your variables in it, then dot source the file. This will bring any variables declared in the file into the global scope.
Example:
Contents of Variables.ps1:
$env is required for current process to see it per https://stackoverflow.com/questions/66459734/cannot-read-environment-variable-set-with-powershell-with-os-environ-get
$env:foo = "blarg"$env:bar = "other blarg"
Dot source it:
. ./Variables.ps1Write-Host "$foo $bar"
# Check variable as above or usingGet-ChildItem Env:
Microsoft Graph PowerShell SDK
Section titled “Microsoft Graph PowerShell SDK”# Install Microsoft Graph PowerShell SDKSet-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUserInstall-Module Microsoft.Graph -Scope CurrentUser# VerifyGet-InstalledModule Microsoft.Graph# UpdateUpdate-Module Microsoft.Graph
# Get user display name from principal name$user = Get-MgUser -Filter "userPrincipalName eq 'first.last@email.ca'"$user.displayName$user.Id
Remove thumbs.db files
Section titled “Remove thumbs.db files”Source: PowerShell Command to Recursively Delete Thumbs.db - Networking HowTos
Get-ChildItem -Path . -Include thumbs.db -Recurse -Name -Force | Remove-Item -Force
See Also
Section titled “See Also”Resources
Section titled “Resources”- PowerShell Documentation - PowerShell | Microsoft Learn
- azure-tests - My GitHub repo testing Azure resources management using PowerShell