PowerShell foreach how to skip the last element

I have the following array with elements

$list = "A","B","C","1","2","3"

using foreach I can view all the elements in an array.

foreach ( $item in $list ) { $item }

I would like to print all the elements in the array, but the latter. Since I need to add ;at the end.

How can i do this?

+4
source share
2 answers

Is this what you are looking for?

$List = "A","B","C","1","2","3";
($List[0..($List.Length-2)] -join '') + ';';

Result

ABC12;
+4
source

This can also be done as a single line:

-join $List -replace [Regex]'.$',';'

The first -joincombines all the elements in the array. Then -replaceand regexreplace the last element with ;.

Regex ( '.$')

  • .= Matches any character except line breaks.
  • $= .
0

Source: https://habr.com/ru/post/1536020/


All Articles