简体   繁体   English

控制台上Powershell中的Foreach循环

[英]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). 这里的问题很简单,我想看看我们如何在命令行上使用foreach(而不是通过PS1脚本)处理一堆命令。

For instance, I display the directory listing on the console, now I want to execute 2 commands per object. 例如,我在控制台上显示目录列表,现在我想每个对象执行2条命令。

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? 没关系,它两次显示文件名,但是可以说我想为同一对象运行2个Write-Host命令,在控制台上可以吗?

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 PS:我正在尝试使用输出文件cmdlet将输出写入2个文件,因此我可以读取内容,并且每个对象有2个单独的输出文件调用

Thanks 谢谢

you can script in the console windows just as you would in a powershell file. 您可以像在powershell文件中一样在控制台窗口中编写脚本。 Use the "`" (backtick) key to separate lines. 使用“`”(反引号)键分隔行。 eg: 例如:

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

So you could do 所以你可以做

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

Basically you want to execute 2 commands in ForEach-Object statement, right? 基本上,您想在ForEach-Object语句中执行2条命令,对吗? Just use ; 随便用; to separate commands in this way ForEach-Object { command1; command2 } 以这种方式分离命令ForEach-Object { command1; command2 } ForEach-Object { command1; command2 }

In your code it should be something like this 在您的代码中应该是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM