Tell me, please, as in Poweshell, “humanely” handle an array of strings, which is obtained as a result of the output of some external command. Here and on other sites you can find complete examples of how to convert an array of objects into an array of strings. But to perform the reverse operation? For example, an external exe-shnik gives such a conclusion, you need to determine uuid by name:

uuid : 111-111-111 name : name1 description : description1 uuid : 222-222-222 name : name2 description : ... uuid : 123-123-123 name : name21 description : description21 ... 

Solution to the forehead:

 for ( $i = 0; $i -lt $exe_result.Count; $i++ ) { if ($exe_result[$i].endswith("искомое имя")) { $exe_result[$i-1]} } 

But this method is only suitable for a given set of parameters, when we know for sure that the name follows the uuid and only look for one parameter. How to make the sampling procedure more universal? Convert to an array of objects, a two-dimensional array?

    1 answer 1

    If we know that we have a specific set of fields that repeats and does not change, we can build a HashTable from the string data using the required parameters. From HashTable we can build a PSObject and work with it already.

    As a draft (born 2 minutes, perhaps there are more optimal algorithms).

    1. Let the output of the program go to a variable for convenience:

       $data = " uuid : 111-111-111 name : name1 description : description1 uuid : 222-222-222 name : name2 description : ... uuid : 123-123-123 name : name21 description : description21 ... " 
    2. Now parse the resulting strings in the HashTable (look for specific parameters in the array of strings):

       $hashtable = @{ UUID = @(([regex]::Matches($data, 'uuid.+')).value -replace 'uuid\s+:\s(.+)','$1') names = @(([regex]::Matches($data, 'name.+')).value -replace 'name\s+:\s(.+)','$1') descr = @(([regex]::Matches($data, 'description.+')).value -replace 'description\s+:\s(.+)','$1') } 
    3. We calculate the number of HashTable values ​​and pop in PSObject separately:

       $obj = 1..$hashtable.UUID.Count | ForEach-Object { New-Object -TypeName psobject -Property @{ UUID = $hashtable.UUID[$_ - 1] Name = $hashtable.names[$_ - 1] Description = $hashtable.descr[$_ - 1] } } 

    We get a standard PSObject at the output, from which we can already ask, for example, by name:

     PS C:\> $obj | Where-Object {$_.name -eq 'name2'} UUID Description Name ---- ----------- ---- 222-222-222 name2