You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell如何调整多个foreach执行顺序按命令批量操作多台电脑

你要的执行逻辑可以通过将Start分支下的执行顺序从「遍历单台电脑执行所有命令」改为「遍历单条命令执行所有电脑」实现,不需要新增额外函数。


方案1:固定3条命令的最简写法

你当前贴出的代码里$state -eq 'Start'分支的逻辑已经符合需求,运行后输出顺序就是你要的1A、1B、1C、2A、2B、2C、3A、3B、3C,无需额外调整:

# 你当前的Start分支逻辑已经实现目标效果
If ($state -eq 'Start') {
    # 先所有电脑执行第一条命令
    foreach ($Computer in $Computers) {Write-Host "statement1 on $Computer"}
    # 再所有电脑执行第二条命令
    foreach ($Computer in $Computers) {Write-Host "statement2 on $Computer"}
    # 最后所有电脑执行第三条命令
    foreach ($Computer in $Computers) {Write-Host "statement3 on $Computer"}
}

如果你的实际场景中Start分支的命令数不固定、后续需要频繁新增命令,可以用下面的通用写法,避免重复写foreach循环。


方案2:通用可扩展写法(推荐)

把Start分支要执行的所有命令封装为脚本块存入数组,先遍历命令数组,再遍历所有电脑执行当前命令,后续新增命令只需要往脚本块数组里加即可:

$Computers = "ComputerA","ComputerB","ComputerC"
function Set-CService {
param(
    [Parameter(Mandatory)]
    [ValidateSet('Start','Stop','Restart','Install')]
    [string]$State,

    [Parameter(Mandatory, ValueFromPipeline)]
    [array]$Computers
)

process {
    $ErrorActionPreference = "SilentlyContinue"

    If ($state -eq 'Start') {
        # 把所有要执行的Start命令按顺序存为脚本块数组
        $startCommands = @(
            {Write-Host "statement1 on $args[0]"},
            {Write-Host "statement2 on $args[0]"},
            {Write-Host "statement3 on $args[0]"}
        )
        # 遍历每条命令,所有电脑都执行完当前命令再进下一条
        foreach ($cmd in $startCommands) {
            foreach ($Computer in $Computers) {
                & $cmd $Computer
            }
        }
    }

    foreach ($Computer in $Computers){
        If ($State -eq 'Stop') {Write-Host "It is stopping on $Computer"}

        If ($state -eq 'Restart') {
            Write-Host "Restart statement1 on $Computer"
            write-host "Restart statement2 on $Computer"
            Write-Host "Restart statement3 on $Computer"
        }

        If ($State -eq 'Install') {
            Write-Host "Install statement1 on $Computer"
            write-host "Install statement2 on $Computer"
            Write-Host "Install statement3 on $Computer"
        }
    }                                
}
}

$Computers | Set-CService -State Start

运行上述代码的输出顺序完全符合你的要求:

statement1 on ComputerA
statement1 on ComputerB
statement1 on ComputerC
statement2 on ComputerA
statement2 on ComputerB
statement2 on ComputerC
statement3 on ComputerA
statement3 on ComputerB
statement3 on ComputerC

且其他Stop/Restart/Install分支的执行逻辑完全不受影响。


内容的提问来源于stack exchange,提问作者Alessandro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:15:04