首页 > 解决方案 > PowerShell FileSystemWatcher 退出 while ($true)

问题描述

我需要这个脚本循环直到它执行操作,但我似乎无法打破循环。

# SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\TransX\InputTriggers\"
$watcher.Filter = "IVANS_TRIGGER_FILE.trig"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

# DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = {
    $path = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType
    $logline = "$(Get-Date), $changeType, Ivans File Arrived"
    Add-Content "C:\TransX\InputTriggers\ProcessLog.txt" -Value $logline
    Start-Process C:\TransX\Transxdl.bat
    Remove-Item C:\TransX\InputTriggers\IVANS_TRIGGER_FILE.trig

    break
}

# DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
#Register-ObjectEvent $watcher "Changed" -Action $action
#Register-ObjectEvent $watcher "Deleted" -Action $stopScript
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {sleep 5}

中的break命令$action不起作用。

标签: powershell

解决方案


BREAK并且CONTINUE只有在循环内使用时才会以这种方式工作,您的操作不在循环本身中。

您可以尝试的是使用类似$ContinueWatchingfor 您的循环的变量并将其从操作中切换。

例子:

$ContinueWatching = $true

$Action = {

    # <Your code here>
    # <Remove break>

    # StopWatching and Exit Script
    $global:ContinueWatching = $false
}

While ($ContinueWatching) {
    Start-Sleep -s 1
}

推荐阅读