并行化powershell脚本执行

时间:2012-02-03 05:56:57

标签: powershell dependencies powerpoint parallel-processing

我有8个powershell脚本。他们中很少有依赖。这意味着它们不能并行执行。它们应该一个接一个地执行。

某些Powershell脚本没有依赖关系,可以并行执行。

以下是详细解释的依赖

    Powershell scripts 1, 2, and 3 depend on nothing else
    Powershell script 4 depends on Powershell script 1
    Powershell script 5 depends on Powershell scripts 1, 2, and 3
    Powershell script 6 depends on Powershell scripts 3 and 4
    Powershell script 7 depends on Powershell scripts 5 and 6
    Powershell script 8 depends on Powershell script 5

我知道通过手动硬编码可以实现依赖性。但是可以添加10个powershell脚本,并且可以添加它们之间的依赖关系。

有没有人通过寻找依赖来实现并行性?如果是这样,请分享我如何继续。

3 个答案:

答案 0 :(得分:5)

您需要查看PowerShell 3.0工作流程。它提供您所需的功能。像这样:

workflow Install-myApp {
    param ([string[]]$computername)
    foreach -parallel($computer in $computername) {
        "Installing MyApp on $computer"
        #Code for invoking installer here
        #This can take as long as 30mins and may reboot a couple of times
    }
}

workflow Install-MyApp2{
    param ([string[]]$computername)
    foreach -parallel($computer in $computername) {
        "Installing MyApp2 on $computer"
        #Code for invoking installer here
        #This can take as long as 30mins!
    }
}

WorkFlow New-SPFarm {
    Sequence {
        Parallel {
            Install-MyApp2 -computername "Server2","Server3"
            Install-MyApp -computername "Server1","Server4","Server5"
        }
        Sequence {
            #This activity can happen only after the set of activities in the above parallel block are complete"
            "Configuring First Server in the Farm [Server1]"

            #The following foreach should take place only after the above activity is complete and that is why we have it in a sequence
            foreach -parallel($computer in $computername) {
                "Configuring SharePoint on $computer"
            }
        }
    }
} 

答案 1 :(得分:2)

一般来说,对并行编程有多熟悉?您是否听说过并使用了mutual exclusion的概念?通常的概念是使用某种消息传递/锁定机制来保护不同并行线程之间的共享资源。

在你的情况下,你将分界线作为脚本本身 - 我认为这可能比维基百科文章中概述的大多数技术更简单。这个简单的模板是否可以满足您的需求?

  1. 在本地文件系统中定义文件夹。所有脚本都将知道此位置(默认参数)。
  2. 在运行任何脚本之前,请确保删除该目录中的所有文件。
  3. 对于每个脚本,作为执行的最后一步,他们应该在共享目录中编写一个文件,并将其脚本名称作为文件名。因此,例如,script1.ps1将创建script1文件。
  4. 任何依赖于另一个脚本的脚本都将根据脚本的文件名定义这些依赖关系。如果script3依赖于script1和script2,则会将其定义为script3中的依赖项参数。
  5. 所有具有依赖关系的脚本都将运行一个函数,检查它所依赖的脚本是否存在文件。如果是,则继续执行脚本,否则暂停直到完成。
  6. 所有脚本由主脚本/批处理文件同时启动。所有脚本都作为PowerShell作业运行,以便操作系统并行运行它们。大多数脚本将启动,看到它们具有依赖关系,然后耐心等待这些脚本在继续执行脚本体之前得到解决。
  7. 好消息是,这将允许灵活地更改依赖关系。每个脚本都写一个文件,不假设其他人是否在等待它们。更改特定脚本的依赖性将是简单的单行更改或输入参数的更改。

    这绝对不是一个完美的解决方案。例如,如果脚本失败会发生什么(或者您的脚本可以在多个不同的代码路径中退出但是您忘记在其中一个中写入文件)?这可能会导致死锁情况,其中没有依赖脚本将被启动。另一个坏处是在等待正确的文件被创建时忙着等待睡眠或旋转 - 这可以通过实施Event-based方法来纠正,其中操作系统会监视目录的更改。

    希望这会有所帮助,而不是垃圾。

答案 2 :(得分:1)

您只需要适当地订购电话。没有任何内置功能可以为您处理依赖项。

同时运行1,2,3 Start-Job

等待他们完成Get-Job -State Running | Wait-Job

同时运行4,5 Start-Job

等待他们完成Get-Job -State Running | Wait-Job

运行6并等待它。

同时运行7,8 Start-Job

相关问题