powershell - 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
不起作用。
解决方案
BREAK
并且CONTINUE
只有在循环内使用时才会以这种方式工作,您的操作不在循环本身中。
您可以尝试的是使用类似$ContinueWatching
for 您的循环的变量并将其从操作中切换。
例子:
$ContinueWatching = $true
$Action = {
# <Your code here>
# <Remove break>
# StopWatching and Exit Script
$global:ContinueWatching = $false
}
While ($ContinueWatching) {
Start-Sleep -s 1
}
推荐阅读
- ios - 如何更改表格视图中单元格的删除动画持续时间?
- php - 创建新数据时可以保存,但不能按类别计算数据
- angular - 我可以在我的组件中使用 antd less 变量吗?
- python - openCV:试图从相机代码中理解捕获视频
- dax - 尝试返回第 N 个排名的文本值时出现 DAX“多列”错误
- java - Redmine SHA1 密码确认问题(Kotlin 和 Java)
- powershell - 选择对象-ExpandProperty 问题
- arrays - 如何在矩阵中找到最大数量为1的行
- c# - 检索不同站点的项目时,Sitecore GetItem 返回 null
- python - 无法使用 pandas 或 openpyxl 在任何 .xlsx 文件的单元格中检测到 EUR