Based on a question on SOa question on SO I thought I'd knock up a cmdlet to perform an unpivot on an object. I've not yet considered all the options (e.g. what happens when objects with empty lists are passed), so there are likely a few issues, but I wanted to get it out to the community early / see if people think this is useful or if better alternatives already exist in PS natively.
cls
function UnPivot-Object
{
param
(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)][psobject]$InputObject
,[Parameter(
ValueFromPipelineByPropertyName=$true
)][string[]]$Properties
,[Parameter(
ValueFromPipelineByPropertyName=$true
)][string]$ExpandProperty
)
process
{
$InputObject | %{
$x = $_ ;
$_ | select -ExpandProperty $ExpandProperty | %{
$y = $_ ;
$x | select $Properties | select *, @{Name="$ExpandProperty";Expression={$y}}
}
}
}
}
$x = @(
(New-Object –TypeName PSObject –Prop @{Name='one'; Var='this'; Var2='How'; List=@('a','b','c');})
,(New-Object –TypeName PSObject –Prop @{Name='two'; Var='test'; Var2='now'; List=@('d','e','f');})
,(New-Object –TypeName PSObject –Prop @{Name='three'; Var='is' ; Var2='brown'; List=@('g','h','i');})
,(New-Object –TypeName PSObject –Prop @{Name='four'; Var='a' ; Var2='cow'; List=@('j','k','l');})
,(New-Object –TypeName PSObject –Prop @{Name='five'; Var='test'; Var2=$null; List=@('m','n','o');})
)
$x | UnPivot-Object -Properties Name, Var -ExpandProperty List