I am trying to get the first char of each string in a List. The list contains:
hehee_one
hrhr_one
test_two
I am using a foreach-object to loop the list
ForEach-Object {($jsonRules.name[0])}
But what this does is getting only the first element, which makes sense. and if i do this:
ForEach-Object {($jsonRules.name[0][0])}
I only get the first char of the first element but not the rest..
so please help me.. thank you
Santiago Squarzon provided the crucial pointer in a comment:
Provide the strings you want the
ForEach-Objectcmdlet to operate on via the pipeline, which allows you to refer to each via the automatic$_variable (the following uses an array literal as input for brevity):Alternatively, for values already in memory, use the
.ForEacharray method for better performance:The
foreachstatement provides the best performance:As for what you tried:
ForEach-Object { ... }- without pipeline input - is essentially the same as executing...directly.Thus, expressed in terms of the sample input above:
You executed:
which is the same as:
which therefore extracts the first element from the input array (the first
[0]) and then applies the second[0]to that string only, and therefore only yields't'.In other words: use of
ForEach-Objectonly makes sense with input from the pipeline.