#PowerShell Flip-Array Function

# UPDATE # The more I played around, it noticed an undocumented feature Winking smile where the Property value from Get-Member could be a NoteProperty .. so updated the function to reflect this.

So I use Windows Powershell every day, and I have quite a few scripts that use ConvertTo-Html

Now this is cool, except when the array I want has a lot of properties which in turn generates lots of columns.

I knocked this up this morning to kinda get around that.  Essentially the function takes an array and a key as input and flips the array.

so ..

Name  Site                 ServerRole  Edition     AdminDisplayVersion
—-  —-                 ———-  ——-     ——————-
MSX   flaphead.local/Co… Mailbox,… Standard    Version 8.2 (Bui…

turns in to

Property                       MSX
——–                       —
AdminDisplayVersion            Version 8.2 (Build 176.2)
CurrentConfigDomainController
CurrentDomainControllers       {}
CurrentGlobalCatalogs          {}
CustomerFeedbackEnabled
DataPath                       C:Program FilesMicrosoftExchange…
DistinguishedName              CN=MSX,CN=Servers,CN=Exchange…
Domain                         flaphead.local

 

Enjoy

function Flip-Array{Param($Array, $key)
  $matrix =@()
  $KeyValue = @()
  $Array | ForEach{$KeyValue += $_.$key}
  $cols = @(); $cols += "Property" ; $cols += $keyValue
  $rows = @(); $array | Get-Member | Where {$_.MemberType –like "*Property"} | ForEach{$Rows += $_.Name}
  $rows | ForEach{
    $tmpMatrix = "" | Select $cols
    $tmpMatrix.Property = $_
    $Matrix += $tmpMatrix
  }

  ForEach($item in $Array){
    $ItemKey = $item.$key
    ForEach($Row in $Rows){
      ($Matrix | Where {$_.Property -eq $row}).$ItemKey = $Item.$Row
    }
  }

Return $Matrix
}

$msx = Get-ExchangeServer
$y=Flip-Array -Key Name -Array $msx

Leave a Reply

%d bloggers like this: