imageI was experimenting today with the PowerShell cmdlets for Citrix Provisioning Server. I was surprised to learn that the output of these cmdlets are not PowerShell types such as collections and objects with methods and properties but just plain text output.

A google search for a method to quickly convert the garbage output to objects led me to this blog post by Frank Peter. He describes a clever use of the switch statement with regular expressions with the Get-DiskInfo cmdlet.

Using Frank's code as a basis I wrote a generic function that converts Mcli output to an array of objects.

I slightly changed the regular expression for the name/value because my output was not indented.

Let's look at the code:

powershell Download
function ToObject {
    param(
     [Parameter(
          Position=0,
          Mandatory=$false,
          ValueFromPipeline=$true,
          ValueFromPipelineByPropertyName=$true)
    ]
    [Alias('Command')]
    [string]$cmd
    )

     $collection = @()
     $item = $null

     switch -regex (Invoke-Expression $cmd)
     {
          "^Record\s#\d+$"
          {
                if ($item) {$collection += $item}
                $item = New-Object System.Object
          }
          "^(?<name>\w+):\s(?<value>.*)"
          {
                if ($Matches.Name -ne "Executing")
                {
                     $item | Add-Member -Type NoteProperty -Name $Matches.Name -Value $Matches.Value
                }
          }
     }
     return $collection
}

Usage Example:

powershell Download
"Mcli-Get Device" | ToObject | foreach {$_.deviceName}

Please note that you need to pass the cmdlet and parameters to call as a string.