在PowerShell ForEach循环中内联命令执行

Hos*_*oss 2 powershell

我熟悉BASH语法如何处理此请求,但无法在PowerShell中找到实现此请求的方法。

BASH示例:

for x in `ls .`; do something with ${x}; done
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用PowerShell执行相同的操作(出于演示目的,语法不正确)...

ForEach ($group in `$wsus.GetComputerTargetGroups()`)
Run Code Online (Sandbox Code Playgroud)

...我显然收到语法错误。

从BASH到PowerShell的翻译是这里的问题。:D

bri*_*ist 5

对于您的示例,它可以正常工作(没有反引号):

ForEach ($group in $wsus.GetComputerTargetGroups()) {
    # do stuff
}
Run Code Online (Sandbox Code Playgroud)

如果是命令,则可以将其包装在子表达式中:

foreach ($process in $(Get-Process)) {
    # do stuff
}
Run Code Online (Sandbox Code Playgroud)

您可能还会看到ForEach-Object在PowerShell管道中可能更惯用的cmdlet:

Get-Process | ForEach-Object { Write-Verbose "This process is $_" -Verbose }
Run Code Online (Sandbox Code Playgroud)