I've imported an objects thats actually two different objects to a single variable:
PS> $object | gm
TypeName: Deserialized.System.Management.Automation.PSCustomObject
...
TypeName: System.Security.Cryptography.X509Certificates.X509Certificate2
...
I can only access information from the first object. Is there a way to split this into two variables based on TypeName?
PowerShell supports destructuring / parallel assignments, officially known as multiple assignments.
If you know the order of the objects contained in collection $object:
$custObj, $cert = $object # $custObj receives $object[0], $cert the rest.
$custObj will receive the 1st object contained in $object, and $cert the rest - which in the case of a 2-element collection is the 2nd element (as a scalar; if the collection had more elements, $cert would receive an array ([object[]])).
Otherwise, in PowerShell v4+, you can use the .Where() collection method to split a collection in two, based on a condition:
$cert, $custObj = $objects.Where(
{ $_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2] },
'Split'
)
From this question I assume you know the types in advance, but you do not necessarily know the order they will appear in the array $object.
The code below will extract the items of each known type from th list:
$customObject = $object | ? { $_.GetType().Name -like "*PSCustomObject" }
$certficate = $object | ? { $_.GetType().Name -like "*X509Certificate2" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With