Friday, February 3, 2017

Powershell Howto: Arrays of Stucts/Objects Using [pscustomobject]

First off, I am not a regular powershell scripter, but I was writing a powershell script to automate some e2e (end to end) testing.  I recently finished a feature in one our DEHes (deployment extension handler used for installing appx packages in Windows), so we needed a test for our nightly test passes.

I wanted to make an array of appx packages that I wanted to test in different scenarios, I also wanted to keep track of other data in the element like expected outcomes for trying to deploy the app in various developer settings.  In C, I would simply define a structure with the data I wanted for each element, and then define a static array of these structs for each appx package.

In powershell, you can use a pscustomobject to make something like a C struct.  Thy syntax is like this:

$obj = [pscustomobject]@{name="good appx";canSideLoad=$true;canInstallDevMode=$true;path="c:\test\packages\test_app_1.1.34.0_good_appx\"}

Now, to make that an array of objects:
$packages = @(

Aside: You can use a hash table if you have a two item tuple.  The syntax for a hash table looks like this:
$packagePaths = @{"case1" = "\\path1..."; "case2" = "\\path2...";}

How do you walk the array of [pscustomobject] using a for loop?

for ($i = 0; $i -lt $packages.Count; $i++) {
    $basePath = $packages[$i].path