PowerShell Tips

Tech Talk Tuesday
August 28th, 2018

My Past

  • Linux since 2000
  • MacBook
  • Automation
  • Scripting

It's a Windows World

  • Denial
  • Anger
  • Bargaining
  • Depression
  • Acceptance

Topics

  • Editors
  • Pipelining
  • Object Conversion
  • Loops and Filters
  • Hidden Gems

Editors

  • PowerShell ISE
  • VS Code
  • Notepad
  • Notepad++
  • Others

Beware integrated consoles!!!

Pipelining

  • Chaining simple commands
  • Formatting
  • Use variables if too long/complex

Invoke-RestMethod `
 -Uri https://api.github.com/users/brendonthiede/repos `
  | Sort-Object updated_at `
  | Format-Table -Property clone_url,updated_at

Object Conversion

  • PowerShell native objects
  • JSON built-ins

("{'Name': 'Brendon', 'Details': {'Job': 'DevOps Engineer'}}" `
  | ConvertFrom-Json).Details.Job

(@{Name="Brendon";Details=@{Job="DevOps Engineer"}}).Details.Job

Loops and Filters

$ObjArray = @(@{Name="Brendon";Details=@{Job="DevOps Engineer"}};@{Name="Tom";Details=@{Job="Operations"}};@{Name="Tom";Details=@{Job="DevOps Engineer"}})
$ObjArray | `
  Where-Object {
    $_.Details.Job -eq "DevOps Engineer"
  } | ForEach-Object {
    Write-Output $_.Name
  }
1..10 | `
  ForEach-Object {
    Write-Output $_
  }

Hidden Gems

  • Save your place: Push-Location/Pop-Location
  • Environment variables: Get-ChildItem env:
  • .Net Code: [System.IO.Compression.ZipFile]::CreateFromDirectory("C:\tmp", "C:\tmp.zip")