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
| 001 002 003 004 005 006 007 008
| $r = Get-WmiObject -Class Win32_OperatingSystem $system = New-Object System.Management.Automation.PSObject Add-Member -InputObject $system -MemberType Noteproperty -Name SystemDevice -Value $r.SystemDevice Add-Member -InputObject $system -MemberType Noteproperty -Name SystemDrive -Value $r.SystemDrive Add-Member -InputObject $system -MemberType Noteproperty -Name SystemDirectory -Value $r.SystemDirectory $system |
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
| 001 002 003 004 005 006 007 008
| $r = Get-WmiObject -Class Win32_OperatingSystem $system = New-Object System.Management.Automation.PSObject $system | Add-Member -MemberType Noteproperty -Name SystemDevice -Value $r.SystemDevice -PassThru | Add-Member -MemberType Noteproperty -Name SystemDrive -Value $r.SystemDrive -PassThru | Add-Member -MemberType Noteproperty -Name SystemDirectory -Value $r.SystemDirectory $system |
Add-Member has a –PassThru parameter that enables us to pipeline the property creations.
PowerShell v2 makes it even easier
| 001 002 003 004 005 006 007 008
| $r = Get-WmiObject -Class Win32_OperatingSystem $system = New-Object System.Management.Automation.PSObject -Property @{ SystemDevice = $r.SystemDevice SystemDrive = $r.SystemDrive SystemDirectory = $r.SystemDirectory } $system |
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 “;”