微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Powershell 在自己的 Powershell Windows 上并行运行作业

如何解决Powershell 在自己的 Powershell Windows 上并行运行作业

在我们的办公环境中,我们使用 Powershell 清理所有 Windows PC(不是很多,只有 20 台左右)

目前我在 ForEach 块中运行脚本,如下所示:

$RemoteComputers = @("Bliep","Bloep")

ForEach ($Computername in $RemoteComputers) {
    Try {
        Write-Host "======================================== Running for $Computername ========================================"
   
        If (Test-Connection -ComputerName $Computername -Quiet) {
            .\Somescript.ps1 -ComputerOBJ ""$Computername""
        else {
            Write-Error "PC not available: $Computername"
        }         
    }
    Catch {
        Write-Error $_.Exception          
    }
}

然后例如 Somescript 代码

Param
(
    [String]$ComputerOBJ = ""
)

Write-Host "Computername = [$ComputerOBJ]"

Invoke-Command -ComputerName $ComputerOBJ -ScriptBlock {
    Hostname
    # ======== Do some heavy lifting ===========
    Start-Sleep 10000
}
Write-Host "Done!"

在这方法运行良好,只是它是顺序的。我想改进此例程以并行/ AsJob 运行它。我想要的方式是 ForEach 每台计算机在一个单独的/自己的带有窗口的 powershell 实例上启动脚本。这样,当我启动“根”脚本时,它会在这种情况下启动 20 个子脚本,而不是单独运行,因此我可以监控每个脚本。

我试图替换这一行:

.\test.ps1 -ComputerOBJ ""$Computername""

有这样的行,但我似乎无法让它正常工作:

$MaintananceJob = .\test.ps1 -ComputerOBJ ""$Computername"""
Invoke-Command -ComputerName $Computername -Scriptblock $MaintananceJob -asJob

$scriptPath =  "$PSScriptroot\test.ps1"
$argumentList =  "-ComputerOBJ $Computername"
Invoke-Expression "& `"$scriptPath`" $argumentList"

start-process Powershell.exe -Argumentlist "-Command .\test.ps1 -ComputerOBJ ""$Computername"""

我的 powershell 技能还很新,所以要温柔;-)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。