Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split two objects from one

Tags:

powershell

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?

like image 495
Bennett Avatar asked Jul 21 '26 16:07

Bennett


2 Answers

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'
)
like image 168
mklement0 Avatar answered Jul 24 '26 01:07

mklement0


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" }
like image 28
Andrew Shepherd Avatar answered Jul 24 '26 00:07

Andrew Shepherd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!