Split a string into an Object array

1k views Asked by At

I have this string in PowerShell:

$filter = "Name;Server;Mounted;ObjectCategory;Guid;WhenChangedUTC;WhenCreatedUTC;ObjectState"

I want to split it to get an object array, I tried:

$stringArray = $filter.Split(';')

but it's a string array.

At the end I would like to call:

... | Select-Object -Property @{Name = 'Command'; Expression = { "Insert" } }, $filterObjectArray

The $filterObjectArray doesn't work when it's a string array.

But it works if $filterObjectArray = 'Name', 'Server' ...

The problem is my custom property called Command because if I only use :

    ... | Select-Object -Property $filterObjectArray

it works.

Thank you for your help.

1

There are 1 answers

0
mklement0 On BEST ANSWER

Your -Property argument must be passed as a flat array, which requires use of an expression:

# Note: Target parameter -Property is positionally implied.
Select-Object (, @{Name = 'Command'; Expression={ "Insert" }} + $filterObjectArray)

Note:

  • Because an expression is required that is to serve as a command argument, it must be enclosed in (...), the grouping operator.

  • ,, the array constructor operator, is used to wrap the script block ({ ... }) in a single-element array so that applying the + operator on it performs array concatenation, which means that the elements of the RHS array, $filterObjectArray, directly become elements of the resulting array, resulting in the necessary flat array of calculated properties and property names.


As for what you tried:

@{Name = 'Command'; Expression = { "Insert" } }, $filterObjectArray

This argument, parsed in argument mode, results in a nested array: the first element is the script block ({ ... }), and the second and last element is the $filterObjectArray array as a whole, which is why the names stored in it weren't recognized.

Note that in argument mode - one of PowerShell's two fundamental parsing modes - only a small subset of operators can be used, such as , and @, the splatting operator; to use others, such as +, a grouping expression ((...)) is needed, as shown (or, for using the output from entire statements as arguments, $(...) or @(...))