Reputation: 23
The majority of code examples I can find for working with Powershell and C# involve the use of PSobjects to return data from the Powershell scripts. A large amount of examples on creating a PSObject involve taking data from Get-WMIObject and converting it to a PSObject. This is done manually specifying each property to be carried over into the new PSObject from the results. Is there anyway to dynamically convert the results from Get-WMIObject (whihc I believe is a ManagementObject) to a PSObject in Powershell?
Basically I'd want a function where regardless of what class of WMIObject I'd be using I'd be able to convert into a PSObject. I've come across the .PSObject.Members call that can be used on the results of a Get-WMIObject call (just .PSObject doesn't seem to actually be anything valid). So I am able to do the following:
$class = "Win32_ComputerSystem"
$psObject = New-Object PSObject
$properties = (Get-WMIObject -Class $class).PSObject.Members | where membertype -match "Property"
foreach($property in $properties)
{
$psObject | Add-Member NoteProperty $property.name -Value $property.value
}
$psObject
But this gives me a much larger amount of results I would normally get from just calling Get-WMIObject. Does anyone know a better way of converting or a way to further trim down these results to be closer to the standard output? I would want it to remain generic where I could change the value of $class to any of the other WMIObject classes and it would still work.
Upvotes: 0
Views: 1616
Reputation: 40818
The "standard properties" are stored in a property that is hidden on the original object, PSStandardMembers
.
$obj = gwmi Win32_ComputerSystem
$psObject = $obj | select $obj.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames
Projects only the standard members into the custom PSObject.
Upvotes: 1