Foreach Loop in Powershell on the Console

Foreach Loop in Powershell on the Console

Very simple question here, I want to see how can we process a bunch of commands using foreach on the command line (not through a PS1 script).

For instance, I display the directory listing on the console, now I want to execute 2 commands per object.

Get-ChildItem | ForEach-Object { Write-Host $_ $_}

This is ok, it shows the filename twice, but lets say I wanted to run 2 Write-Host commands for the same object, would that be possible on the console?

PS: I'm trying to achieve writing an output to 2 files using the out-file cmdlet, so I can read something and have 2 separate out-file calls per object

Thanks

2 Answers

you can script in the console windows just as you would in a powershell file. Use the "`" (backtick) key to separate lines. e.g.:

PS > Write-Host `
>>> hello, world!

So you could do

PS > Get-ChildItem | ForEach-Object { `
>>>    Write-Host $_ `
>>>    doFoo() `
>>>    doBar() `
>>> ` }
1

Basically you want to execute 2 commands in ForEach-Object statement, right? Just use ; to separate commands in this way ForEach-Object { command1; command2 }

In your code it should be something like this

Get-ChildItem | ForEach-Object { Write-Host $_; Write-Host $_ }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.