Tuesday, February 26, 2008

Dynamically create Powershell objects

I wrote a sweet powershell script today that dynamically generated a custom object.  To create an object in Powershell, you basically edit an existing object by adding new methods and properties.  In my case, I used System.Object and added some properties. 

Suppose you are in the middle of a powershell script and you realize that you need a cat class.  Cat's have claws, fur and multiple output devices, but let's limit ourselves to just one.

$myCat = New-Object -TypeName System.Object
$myCat | Add-Member -MemberType noteProperty -Name "Fur" -Value "Soft"
$myCat | Add-Member -MemberType noteProperty -Name "Claws" -Value "Sharp"
$myCat | Add-Member -MemberType ScriptMethod GenerateHairBall { $hairball = "Hmmph, hmmph, ack, aaaaaack! There you go!"; $hairball }

And there you go.  If you have more than one cat, you can store them in an array.  Like this:

$cardboardBox += $myCat
$cardboardBox += $SarahsCat


No comments: