如何并行运行 Powershell 函数的多个实例?

问题描述 投票:0回答:1

下面是我在文件streamMonitor.ps1中的函数

function streamMonitor {
[cmdletbinding()]
    param(
        [string]$directoryPath,
        [string]$scriptToRestartPath
    )

while ($true) {
    Write-Host "Monitoring directory: $directoryPath"
    Write-Host "Script to restart: $scriptToRestartPath"
# Get the current time
$currentTime = Get-Date

# Get the latest creation time of any file in the directory
$latestCreationTime = Get-ChildItem -Path $directoryPath -Recurse |
                      Where-Object { !$_.PSIsContainer } |
                      Sort-Object CreationTime -Descending |
                      Select-Object -First 1 |
                      ForEach-Object { $_.CreationTime }

# Ensure $latestCreationTime is not $null
if ($null -eq $latestCreationTime) {
    Write-Host "No files found in the directory."
    return
}

# Check if the latest write time is within the last 30 seconds
$timeDifference = New-TimeSpan -Start $latestCreationTime -End $currentTime
if ($timeDifference.TotalSeconds -gt 30) {
    # No changes in the last 30 seconds, restart the specified script
    Write-Host "No changes detected within the last 30 seconds. Restarting script..."
     Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"$scriptToRestartPath`"" -NoNewWindow
} else {
    Write-Host "Changes detected within the last 30 seconds. No action taken."
}

    Start-Sleep -Seconds 30
    continue

}
}

我的streamMonitor功能工作正常,所以我很困惑问题是什么。

一个名为 invokingStream.ps1 的不同文件,我想在其中调用该函数的多个实例。为了让这些作业并行运行,我需要更改什么?

当我运行此文件时,没有任何反应,它只是完成了该过程,但是使用它调用的函数,它应该无限期地运行。我正在运行 PS 5.1

#Invoking Functions in Parallel

$job1 = Start-Job -ScriptBlock { 

    . C:\pathto\streamMonitor.ps1

    streamMonitor -directoryPath "C:\pathto\stream1" -scriptToRestartPath "C:\pathto\stream1.bat"
}

$job2 = Start-Job -ScriptBlock { 

    . C:\pathto\streamMonitor.ps1

    streamMonitor -directoryPath "C:\pathto\stream2" -scriptToRestartPath "C:\pathto\stream2.bat"
}

$job3 = Start-Job -ScriptBlock { 

    . C:\pathto\streamMonitor.ps1

    streamMonitor -directoryPath "C:\pathto\stream3" -scriptToRestartPath "C:\pathto\stream3.bat"
}
windows powershell cmd parallel-processing streaming
1个回答
0
投票

您的代码中缺少的东西是阻塞启动作业的线程,否则,您的脚本在调用它们后立即结束,因此作业也结束。您可以使用

Receive-Job -Wait
来实现此目的,它还允许您将
Write-Host
输出返回到主线程。

$streamMonitor = @(
    @{
        directoryPath       = 'C:\pathto\stream2'
        scriptToRestartPath = 'C:\pathto\stream2.bat'
    }
    @{
        directoryPath       = 'C:\pathto\stream3'
        scriptToRestartPath = 'C:\pathto\stream3.bat'
    }
    @{
        directoryPath       = 'C:\pathto\stream1'
        scriptToRestartPath = 'C:\pathto\stream1.bat'
    }
)

$streamMonitor | ForEach-Object {
    Start-Job {
        . C:\pathto\streamMonitor.ps1
        streamMonitor @using:_
    }
} | Receive-Job -Wait -AutoRemoveJob
© www.soinside.com 2019 - 2024. All rights reserved.