Here is my function, on file 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
}
}
Here is the script at which I invoking parallel instances of my function on a separate PowerShell file:
$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
This is the error I am getting:
[localhost] There is an error processing data from the background process. Error reported: Cannot process
an element with node type "Text". Only Element and EndElement node types are supported..
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : 2102,PSSessionStateBroke