listpowershellforeach-object

get first char of each string in a list


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


Solution

  • Santiago Squarzon provided the crucial pointer in a comment:

    Provide the strings you want the ForEach-Object cmdlet 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):

    PS> 'tom', 'dick', 'harry' | ForEach-Object { $_[0] }
    t
    d
    h
    

    Alternatively, for values already in memory, use the .ForEach array method for better performance:

    ('tom', 'dick', 'harry').ForEach({ $_[0] })
    

    The foreach statement provides the best performance:

    foreach ($str in ('tom', 'dick', 'harry')) { $str[0] }
    

    As for what you tried: