[英]Run a powershell Script on multiple folders in parallel
我目前正在编写一个脚本,脚本中有两个启动作业,我将此文件保存为drifter.ps1。 目前,该脚本一次只能在一个路径上工作。 我希望这个脚本同时在多个路径上工作。 这是我的代码
漂流者.ps1
#Some Code#
#run terraform init as job
Start-Job -InitializationScript $initJob -ScriptBlock { init } | Wait-Job | Receive-Job
#run terraform plan as a job
foreach ($item in $workspaces) {
if ($item -ne "") {
Start-Job -InitializationScript $planJob -ScriptBlock { CheckChanges -workspace $args[0] } -ArgumentList "$item" | Wait-Job | Receive-Job
}
}
<# function folders {
$path = (Get-Item -Path ".\").FullName
$d = Get-ChildItem –path $path -Directory
foreach ($item in $d) {
#set-location $item.fullname
& "/home/aquinosj/tf-aws-ptml-dev/env/aquinos/drifter.ps1"
}
}
#>
我希望这段代码在多条路径上工作,因为我是 PowerShell 的新手,所以我完全不知道如何去做。
<# function folders {
$path = (Get-Item -Path ".\").FullName
$d = Get-ChildItem –path $path -Directory
foreach ($item in $d) {
#set-location $item.fullname
& "/home/aquinosj/tf-aws-ptml-dev/env/aquinos/drifter.ps1"
}
}
#>
我编写了这段代码,以便我的脚本(drifter.ps1)适用于多个路径,但我不确定这是否合乎逻辑。 无论如何,我们可以将两个启动作业调用到 function “文件夹”或任何其他方式以并行运行多个路径中的脚本。 仅供参考,我正在研究 Linux 环境。 如果你们能帮助我,那将非常有帮助..谢谢
不确定您要通过工作完成什么,但正如我的评论中所述, Wait-Job
将阻塞当前线程,直到通过管道传递的工作完成,这意味着这就像一个线性循环( foreach
)但是速度较慢,因为您正在开始需要时间的工作,然后在每次迭代时等待它:
foreach($item in $workspaces) {
....
}
还值得指出的是,PowerShell 内置的正常Start-Job
可以说比线性循环慢,并且还消耗大量 memory。 这已经在一些帖子中讨论过,并在一些文章中指出。
更好的替代品是 Microsoft 或Runspace
的ThreadJob
模块,如果您使用的是 PS Core,您还可以包含ForEach-Object -Parallel {... }
)。
现在,为了向您展示如何同时运行多个作业的可重现示例,您可以尝试下面的代码。 请注意在创建所有作业后如何使用Wait-Job
:
$job1 = Start-Job {
0..10 | ForEach-Object {
"Iteration $_"
Start-Sleep -Milliseconds 500
}
}
$directories = Get-ChildItem . -Directory | Select-Object -First 3
# This will start 3 jobs, 1 per directory and get the files of each one
$job2 = $directories | ForEach-Object {
Start-Job {
# This is all happening while $job1 is running at the same time
Get-ChildItem -Path $using:_ -File | Select-Object -First 10
}
}
"- Number of Jobs Running: $( $job1.Count + $job2.Count )"
# Here we wait for the 4 jobs to complete
$null = $job1, $job2 | Wait-Job
"- Result of Job 1:"
$job1 | Receive-Job -AutoRemoveJob -Wait
""
"- Result of Job 2:"
$job2 | Receive-Job -AutoRemoveJob -Wait | Select-Object -Expand FullName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.