NullPointer
NullPointer

Reputation: 2184

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

Upvotes: 5

Views: 13698

Answers (2)

Naigel
Naigel

Reputation: 9644

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 $_ }

Upvotes: 7

ash
ash

Reputation: 3474

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() `
>>> ` }

Upvotes: 6

Related Questions