Thursday, December 24, 2015

Powershell: Ensuring Values Are Returned As Arrays

It's Christmas Eve and I'm in the office catching up on some work.  This year has flown by pretty quickly and I have realized I have not added any content this year despite being very busy with VDI deployments, scripting, a zero-downtime SAN migration (which really deserved/deserves an article), and other miscellaneous tasks.
When scripting today, I came across an challenge that I remember solving earlier in the year. It took a bit of searching through previous scripts for the answer and I finally found it. I decided to turn it into a post for easier recollection later. I also hope it helps someone that runs across the same issue. Others will read this and probably just shake their head as common knowledge.

The Problem:
I have a function that returns multiple values into an array that I can then run a ForEach loop on.  However, it is possible that the function may only return a single value.  In that case, the variable is no longer an array, but a string or integer (depending on what is returned).
Example:

   $files = Get-ChildItem -Path E:\music –File | Select-Object Name
The example would return all the file names in E:\music as Strings and store it in the variable $files. If there were multiple values returned, the $files variable would be an array but let's say there is only one file in E:\music named mysong.mp3. The output of $files[0] would be:
   m
Not the entire file name. It makes sense when you think about it.  When you only assign one string value to a variable, the variable is going to be a string. Weird, eh?

The Solution:
When you are declaring a variable as an array, you can do something like: 
   $myArray = @( )
So when you are assigning the value of a function to a variable and want to ensure it is stored as an array, you would use:
    $files = @(Get-ChildItem -Path E:\music –File | Select-Object Name)
The result of running $files[0] using the same scenario as above would be:
   mysong.mp3