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 

param(
    [Parameter(Mandatory=$True)]
    [string] $ProjectName
)

Basic Objects 

$list = @(
    'item1'
    'item2'
)
$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 {
    Push-Location
    Set-Location $newDir
}
finally {
    Pop-Location
}

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

Not 

You can use -Not or simply !.

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

Block Comment 

<#This is
a commented
block#>

Static Method of .NET Type 

[string]::IsNullOrWhiteSpace($someString)

Create .NET Type 

[System.Drawing.SolidBrush]::new($theColor)

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 

https://docs.microsoft.com/en-us/powershell/developer/cmdlet/approved-verbs-for-windows-powershell-commands

PowerShell Version 

$PSVersionTable.PSVersion