r/PowerShell • u/Bronson_R_9346754 • Apr 29 '26
Question ForEach-Object code block - multiple lines
So you can do this;
$mySet = 1..5
$mySet | ForEach-Object {$_}
..and does that simple $_ comand (prints the object)
Can you add multiple commands inside that {} code block ?
Eg
$mySet = 1..5
[int]$total = 0
$mySet | ForEach-Object {$_ , $total = $total + $_ }
(That code doesn't work of course, but I'm wondering if its possible to perform multiple actions inside each iteration of ForEach-Object ?
Any help is appreciated :)
_____________________________________________________________________________________________
UPDATE: Thank you all. This works;
[int]$sum = 0
$numbers = 1..5
$numbers | ForEach-Object {
$sum = $sum + $_
$_
}
Write-Host "Total of all those numbers is $sum"
The output is .......................................
1
2
3
4
5
Total of all those numbers is 15
3
u/PinchesTheCrab Apr 29 '26 edited Apr 29 '26
Sounds like you already got your answer, just wanted to point out that PWSH already has an operator to do this a bit more concisely, and there's also some other cmdlets to help with aggregate values:
Or for your other example with output for each line:
9
u/dathar Apr 29 '26
You can. You can break it up into multiple lines inside of the squiggly brackets like a normal code block or just use ; where the second line would be.
1
u/jimb2 Apr 29 '26
Learning how to insert code into Reddit shows respect for the people you want to respond to your post.
There's a button in the rich text editor. In markdown, there's indenting, or a line of four backticks at the start and end of the pasted code.
2
u/Just_Conclusion8890 Apr 29 '26
Yes, that is precisely what the code block is for. You are performing a command or several commands inside of the loop (one iteration for each item in the collection).
2
u/arslearsle Apr 29 '26
Yes
1
u/reidypeidy Apr 29 '26
You can just hit enter after every line. PowerShell accepts carriage returns for a new line in code blocks.
1
u/AgonisingPeach Apr 29 '26
If you’re doing it all on one line within the terminal you’ll want to seperate each command with a semi-colon
;But if you are within ISE or press Shift+Enter you can write commands on a new line. Just remember to close out the bracket.
1
u/jr49 Apr 29 '26
With a line break or semicolon you can for sure. I’d use $total += $_ to add all the sums. You can do anything you want pretty much in each loop.
1
u/mrmattipants Apr 29 '26 edited Apr 29 '26
Sure. You can make it as simple or complex as you wish.
In theory, your existing code should work. You may want to try experimenting with the variable output, etc.
1
u/420GB Apr 29 '26
Foreach-Objectcan also take two additional scriptblocks,BeginandEndthat only run once at the very beginning and once at the very end respectively.So this works too:
1
u/jsiii2010 May 07 '26 edited May 07 '26
You can also do it with a for loop:
Or another form of foreach-object:
1
u/dodexahedron Apr 29 '26 edited Apr 29 '26
In general, in powershell (and most languages), constructs that open a multi-line context do so everywhere they are valid.
But just to break this one down, think about what you are writing:
$mySet | ForEach-Object { $_ }You have an outer pipeline that starts with enumeration of a collection
$mySetIn a pipeline, each command is still independent and writes to output as it normally would. But being in a pipeline like that lets you write it in a more natural order. Otherwise it's still just as if it wasn't written in a pipeline.
So next is
ForEach-Object { $_ }This is one command, by itself, with one parameter.
The parameter is -Process and it is an array of ScriptBlock objects.
Because it is a scriptblock, it is bound as such and its contents are not executed or evaluated in place, which is why the $_ survives each iteration rather than getting replaced by something right now and being a constant when the block runs (that's also important when nesting them, which would be difficult otherwise).
But, for the part relevant to your question, youve opened a new scope with an unescaped curly brace. The parser sees that, and is now in the state for defining that scope. It will stay in that state until it is told to leave that scope. The closing curly is one such way. Anything written until a matching closing curly will be in this scope or a descendent of it.
When writing multi-line/multi-statement foreach blocks, it's common (and cleaner) to write it with the opening curly being the last thing on that line and then writing the contents of the block one statement per line like any other script block, then closing it with the closing curly on its own line, like this:
There is also a shortcut/alias for ForEach-Object, btw:
$mySet |% { $_ }is identical. Totally optional and mostly a style choice.But also be aware that simple iteration over a set like your example is far less efficient in a pipeline than inside an actual
foreachloop statement. If you don't need the pipeline, and it isn't just an ad-hoc command (ie it's part of a script/function), it's a good idea to avoid instantiating it.0
u/Enochrewt Apr 29 '26 edited Apr 29 '26
Yes, You can just do multiple lines of code in one {} Block. But you should really look at doing
$NewSet = @()
$mySet | ForEach-Object {
write-output "$_"
$NewSet += $total + $_
}
You have to initialize the array $NewSet first, before you can store things in it. += adds each $_ to $total and stores it in $Newset. It will keep $mySet and NewSet in the same object format with the same count of objects.
If you just put it to $Newset the way you are doing with only =, only the last $_ will be stored in $NewSet.
Edit: and specify where you are outputting things. It will become flummoxing and confusing later if you don't. Write-Host, Write-output, Out-Default. Just to start with basics.
Edit2: Also, you can just do
$NewSet = @()
foreach ($Thing in $mySet){
write-output "$thing"
$NewSet += $total + $thing
}
Using the pipeline can get confusing when you are nesting things and have to use it. This way reads cleaner and is easier to go back and understand what you wrote a year later.
0
u/kagato87 Apr 29 '26
Yes.
{} is a code block, and absolutely can be multi statement, multi line.
$_ is the "each" object for every iteration.
Your example is syntactic sugar for
Foreach-object is syntactic sugar for foreach, and any object that mimics a simple variable (like a string) prints itself if you just call it directly.
You can absolutely have many statements. I do exactly this quite often. $_ is the "self" reference - so for each item in the array you passed in, you can do whatever you need.