In a previous tip we explained how PSCustomObject can create new objects really fast:
$o = [PSCustomObject]@{ Date = Get-Date BIOS = Get-WmiObject -Class Win32_BIOS Computer = $env:COMPUTERNAME OS = [Environment]::OSVersion Remark = 'Some remark' }
In reality, [PSCustomObject] is not a type, and you are not casting a hash table, either. What truly happens behind the scenes is the combination of two steps that you can also execute separately:
#requires -Version 3.0 # create an ordered hash table $hash = [Ordered]@{ Date = Get-Date BIOS = Get-WmiObject -Class Win32_BIOS Computer = $env:COMPUTERNAME OS = [Environment]::OSVersion Remark = 'Some remark' } # turn hash table in object $o = New-Object -TypeName PSObject -Property $hash
Since the code uses ordered hash tables which were introduced in PowerShell 3.0, you cannot use either approach in PowerShell 2.0. To support PowerShell 2.0: use a non-ordered (conventional) hash table instead:
#requires -Version 2.0 # create a hash table $hash = @{ Date = Get-Date BIOS = Get-WmiObject -Class Win32_BIOS Computer = $env:COMPUTERNAME OS = [Environment]::OSVersion Remark = 'Some remark' } # turn hash table in object $o = New-Object -TypeName PSObject -Property $hash $o