But that's how you learn.
In my last post I was trying to simplify the creation of objects in various way but I forgot about the golden rule, KISS (Keep It Simple, Stupid).
That is, if it looks complex, write a function...
So the only way to create an object in PowerShell v2 with ordered properties is like this, right?
$Kalle = New-Object PSObject$Kalle| Add-Member -MemberType NoteProperty -Name First -Value "Kalle"$Kalle| Add-Member -MemberType NoteProperty -Name Last -Value "Svensson"$Kalle| Add-Member -MemberType NoteProperty -Name Phone -Value "555-55 55 55"$Kalle
First Last Phone
----- ---- -----
Kalle Svensson 555-55 55 55
So lets make it a an advanced function.
function New-CustomObject
{
param (
[array]$PropertyArray
)
$Object = New-Object PSObject
foreach ($Property in $PropertyArray){
$Object | Add-Member -MemberType 'NoteProperty' -Name $Property -Value $null
}
return $Object
}
Then putting the new function to use
$Kalle = New-CustomObject -PropertyArray "First","Last","Phone"
$Kalle.First = "Kalle"
$Kalle.Last = "Svensson"
$Kalle.Phone = "555 - 55 55 55"
$Kalle
First Last Phone
----- ---- -----
Kalle Svensson 555-55 55 55
And I'm done
No comments:
Post a Comment