Cheat Sheet: PowerShell
powershell

Series of short snippets of FUC. This one is for PowerShell.
March 6, 2019

A few snippets of PowerShell I've found useful over and over again. Most of them are just syntax/functions that I'm unable to remember, some of them might be more complex.

It’s a living document, I keep updating it.

XML parsing

$xmlDoc = [XML](Get-Content $filePath)
$xmlDoc.Element.Subelement.setAttribute("Attr", $value);
$xmlDoc.Save($filePath)

JSON parsing

$jsonDoc = Get-Content $filePath | Out-String | ConvertFrom-Json

Convert from JSON to object and don't shrink single-element arrays into non-array objects:

$jsonDoc = $jsonText | ConvertFrom-Json -NoEnumerate

HTTP requests

Invoke-WebRequest with authentication bearer token:

Invoke-WebRequest "https://myurl.mydomain.cz/api/test " -Authentication Bearer -Token (ConvertTo-SecureString $bearerToken -AsPlainText)

Remove item from an array

Arrays in PowerShell are immutable, so changes need to be done through creating a new, modified array instead. The += operator does it for addition, but there's no -= for removal.

$oldArray = @("A", "B", "C")

$newArray = $oldArray | Where-Object { $_ -ne "B" }

Generate self-signed certificate

$cerPath = Join-Path -Path $ExportDirectoryPath -ChildPath "$($CertificateName).cer"
$pfxPath = Join-Path -Path $ExportDirectoryPath -ChildPath "$($CertificateName).pfx"

$cert = New-SelfSignedCertificate `
  -Subject "CN=$CertificateName" `
  -CertStoreLocation "Cert:\CurrentUser\My" `
  -KeyExportPolicy Exportable `
  -KeySpec Signature `
  -KeyLength 2048 `
  -KeyAlgorithm RSA `
  -HashAlgorithm SHA256

# Get CER
Export-Certificate `
  -Cert $cert `
  -FilePath $cerPath

$generatedPassword = "SomeRandomPassword"
$mypwd = ConvertTo-SecureString -String $generatedPassword -Force -AsPlainText

# Get PFX
Export-PfxCertificate `
  -Cert $cert `
  -FilePath $pfxPath `
  -Password $mypwd

# Cleanup local store.
$certInstore = Get-ChildItem -Path "Cert:\CurrentUser\My" | Where-Object { $_.Subject -Match $CertificateName } | Select-Object Thumbprint, FriendlyName
Remove-Item -Path Cert:\CurrentUser\My\$($certInstore.Thumbprint) -DeleteKey

Azure CLI output parsing

Output type of Azure CLI has to be set to JSON (default). Then ConvertFrom-Json can be used to process the result:

$variableGroupId = (az pipelines variable-group create --name "test" --variables "delete=me" --organization "https://dev.azure.com/testorg" --project "test" | ConvertFrom-Json).Id

Environment variables

Create an environment variable and assign value:

$env:TF_LOG = "TRACE"

Remove environment variable:

Remove-Item Env:TF_LOG

(Env is without the $)

Found something inaccurate or plain wrong? Was this content helpful to you? Let me know!

📧 codez@deedx.cz