PowerShell Basics and Snippets

18 Jan 2020 18 Jan 2020 2 min read PowerShell

Specifying Value for Switch Parameter 

.\script.ps1 -SwitchParam:$false

Required Parameters 

    [string] $ProjectName

Basic Objects 

$list = @(

$obj = @{
    Property1 = 'one'
    Property2 = 'two'
    Property3 = 'three'

1-Element List 

$list = @(, $onlyItem)

String Interpolation 

$x = "Some $my_var here" # simple
$y = "The length is: $($my_str.Length)" # expression
$z = "Variable with non-standard characters: ${env:PROGRAM_FILES(x86)}" # special

Variables with Non-Standard Characters 

${,,,} = 5 # Variable named ,,,

Multi-line Strings 

$str1 = @"
This string
is multi-line.

$str2 = @'
This string
is multi-line.

Number + KB, MB, GB, TB or PB 

Powershell understands standard notation for kilobytes, megabytes, gigabytes, terabytes and even petabytes.

1KB, 1MB, 1GB, 1TB, 1PB

Change Working Directory 

try {
    Set-Location $newDir
finally {

File Reading and Writing 

# Reading
$contents = Get-Content $sourceFile -Encoding 'utf8'

# Writing
# WARN: BOM with PowerShell 5; no BOM with PowerShell Core
$someString | Out-File $destFile -Encoding 'utf8' -NoNewLine


You can use -Not or simply !.

if (!$a) {
    Write-Host '$a is null'

Block Comment 

<#This is
a commented

Static Method of .NET Type 


Create .NET Type 


Module Loading 

Note: When using modules, you should also use Unload-Modules.ps1 from this repository.

Import-Module "$PSScriptRoot/MyModule.psm1" -DisableNameChecking

Read Registry Value 

Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'

Approved Verbs 


PowerShell Version