Skip to content

Instantly share code, notes, and snippets.

@JonasReich
Last active December 2, 2019 22:42
Show Gist options
  • Save JonasReich/0a4bf909c8d9f05c14c7919120db2d9f to your computer and use it in GitHub Desktop.
Save JonasReich/0a4bf909c8d9f05c14c7919120db2d9f to your computer and use it in GitHub Desktop.
A cheat sheet for the power shell syntax and behavioral quirks I stumble across the most

PowerShell Cheat Sheet

When coming from other scripting environments (CMD, Python) it can sometimes be a bit confusing how PowerShell does things. These are the 10 points that surprise me the most after not using PowerShell for a while:

1. Execution Policy

By default PS is configured not to load any configuration files and not to allow running of .ps1 script files. This can be changed by either changing the ExecutionPolicy, or by unblocking a specific script file:

# Change the execution Policy (requires launching PowerShell with admin rights):
Set-ExecutionPolicy RemoteSigned

# Temporarily unblock a script file:
Unblock-File -Path .\SampleScript.ps1

2. ErrorAction

By default PowerShell continues script execution even after an Error occured. You can change this at the begging of your script to stop whenever any error occurs:

$ErrorActionPreference = "Stop"

3. File IO

Get-Content returns file contents split by lines as array of strings. If you want one continuous string with linebreaks, you need to add the -raw switch:

$file_content = Get-Content -raw "some/text/file.txt"

4. Documentation

PowerShell exports documentation written in comments that begin with certain keywords to be available in the Get-Help commandlet:

function Add-Extension
{
param ([string]$Name,[string]$Extension = "txt")
$name = $name + "." + $extension
$name

<#
.SYNOPSIS

Adds a file name extension to a supplied name.

.DESCRIPTION

Adds a file name extension to a supplied name.
Takes any strings for the file name or extension.

.PARAMETER Name
Specifies the file name.

.PARAMETER Extension
Specifies the extension. "Txt" is the default.

.INPUTS

None. You cannot pipe objects to Add-Extension.

.OUTPUTS

System.String. Add-Extension returns a string with the extension
or file name.
...
#>
}

5. Parameters

PowerShell scripts and functions have very verbose parameter declarations compared to other scripting languages. However they also allow to be declared as optional/mandatory, with default values, etc. One property I've only recently discovered was how you set a parameter to take its value from the pipeline:

Param(
	[Parameter(Mandatory=$true,
	ValueFromPipeline=$true)]
	[String]
	$ComputerName
)

6. Sharing functionality across scripts

The two easiest to use ways to share code is to either to put functions into PowerShell modules files (ending in .psm1) and calling those or to call another powershell script using "dot-sourcing", meaning calling it with a . before the script path. The former is encouraged over the second alternative, because it makes handling with variable scope and similar problems a bit easier.

# Using a PowerShell module:
Import-Module .\Path\To\ASharedModule.psm1
FunctionFromModule()

# Dot Sourcing:
. .\Path\To\AnotherScript.ps1

7. Variable scope

If you have a function that should modify a variable that was created in script scope, you can prefix it with script. Otherwise the script will only have access to locally created variables (including function parameters).

function Foo()
{
    $script:x = 1
}
$x = 0
Foo()
$x // will output 1

If you want to access the same variable across scripts, you can use global variables:

# Use Set-Variable to set global variables:
Set-Variable -Name VariableName -Value 42 -Scope Global

# Use global: prefix to read global variables:
$global:VariableName // will output 42

8. Escaping characters

The escape character in PowerShell is not the backslash (unless it is - in regular expressions, you still have to use the backslash to escape regex control characters). Instead, powershell uses the backtick: `

9. Logging and Output

If you come from CMD, it's tempting to use "echo" in order to add debug information and logs to your script. This will work quite fine, until you add functions to the mix. This is because echo is just an alias for PowerShell's Write-Output which sends the specified ipnut to the next command in the pipeline. Essentially this means the object/string/whatever is passed to the calling level and if not caught will bubble up to the terminal level where it's displayed. However in the context of a function which's output is caught in a variable like so...

$result_variable = Foo()

...everything that is "logged" with Foo() will be stored in the variable instead of being displayed on-screen. You can use Write-Host to display those messages but those cannot be redirected to file output.

10. Comparison Operators

The most standard comparison operators ==, <, > do not work in PowerShell. Instead you have to use the following comparison operators:

-eq equals
-ne not equals
-gt greater than
-ge greater than or equal
-lt less than
-le less than or equal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment