This PowerShell quick reference is a collection of handy PowerShell examples, some that I have found useful in my day to day tasks, others just illustrating their simplest usage as a reference. I use this page as a quick reference if I need to grab a working example for a given problem. Hopefully you will find them useful too. New examples will be added as I continue my PowerShell journey.
PowerShell Aliases
First, a word about aliases. In these examples I use both the PowerShell commands and aliases interchangeably. Here is a list of some of my favourites that you may find useful, you’ll see some of these used in the examples.
You’ll notice that a lot of these aliases look like DOS or Unix commands. This is a nice feature of PowerShell that lets new users from different backgrounds get up to speed quickly.
cat Get-Content
cd Set-Location
pwd Get-Location
cls Clear-Host
cp Copy-Item
mv Move-Item
del Remove-Item
rm Remove-Item
dir Get-ChildItem
ls Get-ChildItem
echo Write-Output
write Write-Output
foreach Foreach-Object
ps Get-Process
File and folder operations
This section contains handy PowerShell snippets for dealing with files and folders including a number of equivalents to common Unix commands.
Display last n lines of a file (Unix ‘tail’ equivalent)
This command will display the last 10 lines of a file. The optional -Wait flag will cause the command to wait for new lines to be added to the file in real time.
cat-Path /temp/test.log -Tail10-Wait
Display first n lines of a file (Unix ‘head’ equivalent)
This command will display the first 10 lines of a file.
cat-Path /temp/test.log -TotalCount10
Search for a string in a file (Unix ‘grep’ equivalent)
These two examples demonstrate the Select-String cmdlet – searching for the string ‘test’ in a file or recursively through all files in a set of child folders. The second example also displays the file the string is found in.
cat-Path /temp/test.log | Select-String-Pattern"test"Select-String-Path".\*"-Pattern"test"
Find a particular file in folders
This command searches recursively through folders to find the given file.
ls-Path .\* -Include my-script.js
Count the lines, words and characters in a file (Unix ‘wc’ equivalent)
This command will count the number of lines, words and characters in a file.
cat-Path /temp/test.log | Measure-Object-Character-Word-Line
Sort lines in a file (Unix ‘sort’ equivalent)
This command will sort the lines in a file and output the results.
cat-Path /temp/test.log | Sort-Object
Remove duplicate lines in a file (Unix ‘uniq’ equivalent)
This command will remove duplicate lines in a file and display the results.
cat-Path /temp/test.log | Get-Unique
Search and replace in a file (Unix ‘sed’ equivalent)
This command will search for a string in a file and and replace it with another.
cat-Path /temp/test.log | ForEach-Object { $_-replace"find", "replace" }
Write and read text to/from a file
This command will write text to a file and then read it back again.
"test" | Out-File-FilePath /temp/test.txt
Get-Content-Path /temp/test.txt
cat /temp/test.txt # alternative using cat alias
Recursively list all files in a directory
This command will recursively list all files in a directory.
Get-ChildItem-Path /temp -Recurse
Recursively list all files in a directory excluding/including specific directories and files, also include hidden and system files
Get-ChildItem-Path /temp -Recurse-Filter"test*.txt"-Exclude"testfolder1", "testfile1.txt"-Include"testfolder2", "testfile2.txt"-Force-File
Rename files in a folder to prepend name with a given string
This command will prepend all filenames in a directory with a string.
Get-ChildItem-Path /temp -Recurse | ForEach-Object { Rename-Item-Path$_.FullName -NewName"test-$_" }
Working with web content
Fetching content from a URL (Unix ‘curl’ equivalent)
Fetch web content from a given URL.
Invoke-WebRequest-Uri"https://www.codingthoughts.net"
This command will fetch the content from a URL into a file.
Invoke-WebRequest-Uri"https://www.codingthoughts.net"-OutFile /temp/test.html
Fetch the content from a URL into a variable.
$test = Invoke-WebRequest-Uri"https://www.codingthoughts.net"
Call a REST API endpoint
This command will call a REST API endpoint and display the results.
Invoke-RestMethod-Uri"https://api.github.com/users/your_github_username"
Call a REST endpoint and pass JSON parameters
$body = @{
param1 = "abc"
param2 = "def"
param3 = "ghi"
}
$params = @{
Method = "POST"
Uri = "https://www.codingthoughts.net/api/TestAction"
Body = ($body | ConvertTo-Json)
ContentType = "application/json"
}
Invoke-RestMethod @params
Working with databases
Connect to a SQL Server database
This command will connect to a SQL Server database and display the results.
$connectionString = "Server=.;Database=master;Trusted_Connection=True;"$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString$connection.Open()
$command = New-Object System.Data.SqlClient.SqlCommand
$command.Connection = $connection$command.CommandText = "SELECT * FROM mytable"$reader = $command.ExecuteReader()
$reader | Select-Object-Property *
$reader.Close()
$connection.Close()
Connect to a MySQL database
This command will connect to a MySQL database and display the results.
$connectionString = "Server=localhost;Database=master;Uid=root;Pwd=;"$connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$connection.ConnectionString = $connectionString$connection.Open()
$command = New-Object MySql.Data.MySqlClient.MySqlCommand
$command.Connection = $connection$command.CommandText = "SELECT * FROM mytable"$reader = $command.ExecuteReader()
$reader | Select-Object-Property *
$reader.Close()
$connection.Close()
Connect to a SQLite database
This command will connect to a SQLite database and display the results.
$connectionString = "Data Source=/temp/test.db"$connection = New-Object System.Data.SQLite.SQLiteConnection
$connection.ConnectionString = $connectionString$connection.Open()
$command = New-Object System.Data.SQLite.SQLiteCommand
$command.Connection = $connection$command.CommandText = "SELECT * FROM mytable"$reader = $command.ExecuteReader()
$reader | Select-Object-Property *
$reader.Close()
$connection.Close()
Working with environment variables
This command will display all environment variables and values.
Get-ChildItem Env:
Display the value of a specific environment variable.
Get-ChildItem Env:PATH
Set an environment variable
$env:PATH = "c:\temp\bin"
Append a string to an environment variable
$env:PATH += ";c:\temp\bin"
Delete an environment variable
Remove-Item Env:PATH
Windows processes
List all running processes
Get-Process
Stop a process
This command will stop a process given a process name or ID.
Stop-Process-Name"notepad"Stop-Process-Id1234
Display details of a running process
This command will display details of a running process.
Get-Process-Name"notepad"
Dates and times
Display the current date and time
This command will display the current date and time.
Get-Date
Display the current date and time in a specific format
This command will display the current date and time in a specific format.
Get-Date-Format"yyyy-MM-dd HH:mm:ss"Get-Date-DisplayHint Date
Get-Date-DisplayHint Time
Get various elements of the current date and time
$date = Get-Date"Date: " + $date.Date
"Hour: " + $date.Hour
"Minute: " +$date.Minute
"Second: " +$date.Second
"Ticks: " + $date.Ticks
"Year: " + $date.Year
"Day: " + $date.Day
"Day of week: "+ $date.DayOfWeek
"Day of year: "+ $date.DayOfYear
Add days, hours and minutes to a date
This command shows and example of performing arithmetic on dates.
Get-Date-Format"yyyy-MM-dd HH:mm:ss" | Add-Date-Days1-Hours1-Minutes1
Working with system metrics
Show CPU and memory usage
This command will show CPU and memory usage.
Get-Counter-Counter"\Processor(_Total)\% Processor Time", "\Memory\Available MBytes"
Disk usage for a specific drive
Get-PSDrive-Name C
Show network usage
Get-Counter-Counter"\Network Interface(*)\Bytes Total/sec"
Network usage for a specific interface
Get-Counter-Counter"\Network Interface(*)\Bytes Total/sec" | Where-Object { $_.Path -like"*Ethernet*" }
Windows events, tasks, software and services
Windows services
These commands will list all, start and stop a Windows service.
Get-ServiceStart-Service-Name"service_name"Stop-Service-Name"service_name"
Windows scheduled tasks
This command will list all, start and stop a Windows scheduled task.
Get-ScheduledTaskStart-ScheduledTask-TaskName"task_name"Stop-ScheduledTask-TaskName"task_name"
Windows event logs
This command will list all, clear and delete a Windows event log.
Get-EventLogClear-EventLog-LogName"log_name"Remove-EventLog-LogName"log_name"
List all installed software
This command will list all installed software.
Get-ItemProperty-Path"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-Object DisplayName, DisplayVersion
Parsing different file types
Parse an XML file
This command will parse an XML file and display the results.
[xml]$xml = Get-Content-Path /temp/test.xml
$xml.test.test2
Parse a JSON file
This command will parse a JSON file and display results.
$json = Get-Content-Path /temp/test.json | ConvertFrom-Json$json.test.test2
Parse a CSV file
This command will parse a CSV file.
$csv = Import-Csv-Path /temp/test.csv
$csv.test.test2
Parse a YAML file
This command will parse a YAML file.
$yaml = ConvertFrom-Yaml-Path /temp/test.yaml
$yaml.test.test2
Parse a INI file
This command will parse a INI file.
$ini = Get-IniContent-Path /temp/test.ini
$ini.test.test2
Parse a properties file
This command will parse a properties file.
$properties = Get-Content-Path /temp/test.properties | ConvertFrom-Properties$properties.test.test2
Lists, hashtables and objects
Create an object
This command will create an object.
$object = New-Object-TypeName PSObject -Property@{ test = "test" }
$object.test
View object members
These commands will display all members of various objects.
$object | Get-MemberGet-ChildItem | Get-MemberGet-Date | Get-Member
Create a hashtable
This command will create a hashtable.
$hashtable = @{ test = "test" }
$hashtable.test
Sort a list
This command will sort a list both ascending and descending.
$test = 9, 2, 1, 4, 5, 12$test | Sort-Object$test | Sort-Object-Descending
Comparing files
Compare two files
Compare-Object-ReferenceObject (Get-Content-Path /temp/test1.txt) -DifferenceObject (Get-Content-Path /temp/test2.txt)
Compare two directories
Compare-Object-ReferenceObject (Get-ChildItem-Path /temp/test1) -DifferenceObject (Get-ChildItem-Path /temp/test2)
Simple programming constructs
If / else / elseif statements
if ($true) {
"true"
} elseif ($false) {
"false"
} else {
"else"
}
For loop
This command will display the numbers 1 to 10.
for ($i = 1; $i-le10; $i++) { $i }
A simple for loop with a conditional statement
for ($i = 1; $i-le10; $i++) { if ($i-eq5) { break } $i }
Foreach loop
foreach ($iin1..10) {
$i
}
While loop
$i = 1while ($i-le10) {
$i$i++
}
Do while loop
$i = 1do {
$i$i++
} while ($i-le10)
Switch statement
switch ($i) {
1 { "first" }
2 { "second" }
default { "others" }
}
A simple example of a function with parameters
This command will display the numbers 1 to 10.
function test($parameter1) { for ($i = 1; $i-le$parameter1; $i++) { $i } }
test(10)
Exception Handling
Try / catch / finally
try {
throw"test"
} catch {
$_
} finally {
"finally"
}
Throw an exception
throw"test"
Catch an exception
try {
throw"test"
} catch {
$_
}
Throw an exception with a custom message
throw"test"-ErrorRecord$_
Throw an exception with a custom message and a custom error ID
throw"test"-ErrorId"test"-ErrorRecord$_
Creating simple UI elements
Display a MessageBox
This command will show a simple MessageBox.
[System.Windows.Forms.MessageBox]::Show("test")
Display a MessageBox with a custom title and a custom icon
[System.Windows.Forms.MessageBox]::Show("test", "test", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
A more complex MessageBox example
Display a MessageBox with a custom title, a custom icon and a custom button with click handler. Useful for user prompts and simple input fields.
$button = New-Object System.Windows.Forms.Button
$button.Text = "test"$button.Click += { [System.Windows.Forms.MessageBox]::Show("test") }
[System.Windows.Forms.MessageBox]::Show("test", "test", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, [System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly, $button)
Using PowerShell aliases
Show all aliases
Get-Alias
Set an alias
Set-Alias-Name"getchild"-Value"Get-ChildItem"
Remove an alias
Remove-Alias-Name"getchild"
Leave a Reply
You must be logged in to post a comment.