Starting to Learn PowerShell

For a variety of reasons, I've started dipping my toe in the PowerShell pool to start writing development tooling at my workplace. From what I've seen so far, I'm impressed. There's a lot of flexibility in how you write scripts and modules and, like Python, it can do anything from short one line scripts to large GUI applications.


Array Unpacking

If you return an array with 0 or 1 elements from a function in PS, it will unpack the array and just return the 1 element in the array. If you are then iterating over the result, you can be iterating ocer a subarray instead of the array. This is very unintuitive and requires you wrap every function call that returns an array in code that converts it back to an array if there's only one element.

# May Cause Problems
$FileLines = Get-FileLines $FilePath
# Ensures array result
$FileLines = @(Get-FileLines $FilePath)

In this example, Get-FileLines returns an array of lines in the file given by $FilePath. In the case where the file contains a single line, the first example would be an array of characters in the line in the file instead of an array of lines!

I lost several hours trying to track down why a script was failing in production, but succeeding on my test data.

Show Comments