#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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.