Scripting Games Comments VIII: Creating Objects
One thing we have to do quite frequently is create an object and populate some variables. In PowerShell v1 we would do something like this
We get some data – in this case from WMI
We use New-Object to create an object – I’ve used the full type name deliberately
$system = New-Object PSObject
works just as well.
Add-Member is used to add three NoteProperties and then we display the object to get
SystemDevice SystemDrive SystemDirectory
------------ ----------- ---------------
\Device\HarddiskVolume2 C: C:\Windows\system32
Its a bit of a contrived example but it works.
It is possible to make this a bit easier and less typing
Add-Member has a –PassThru parameter that enables us to pipeline the property creations.
PowerShell v2 makes it even easier
New-Object does all the work for us – it even creates each property as a NoteProperty. All we do is give the property information as a hash table. If you want this all on one line then separate each pair by a semi-colon “;”