powershell - Powershell - 创建几个文件后如何开始操作
问题描述
我想循环一个 powershell 脚本来监视是否在文件夹中创建了一些 xml 文件。如果至少有 3 个,则应重新启动程序。这是我在这里使用 nixda 得到的:
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\DVNAV\11842596\nav2016\2019"
$watcher.Filter = "*.xml*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { Stop-Process -name dvnav -force
Start-Sleep -Seconds 8
Start-Process -FilePath 'C:\Program Files (x86)\DVNAV.exe' -verb RunAs
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {sleep 5}
但我不知道如何将监控设置为多个文件,而不仅仅是一个。
解决方案
这应该适合你。不要忘记在使用/测试后取消注册事件!
#--------------------------------------------------
function Stop-EventWatcher {
#--------------------------------------------------
# To stop the monitoring, run the following commands:
Unregister-Event FileCreated
}
$folderToWatch = 'C:\DVNAV\11842596\nav2016\2019'
$filter = '*.xml'
$script:counter = 0
# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher
$fsw.Path = $folderToWatch
$fsw.IncludeSubdirectories = $false
$fsw.EnableRaisingEvents = $true
$scriptBlock = {
$message = $event.MessageData # message data is how we pass in an argument to the event script block
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$script:counter++
if( $script:counter -eq 3 ) {
$script:counter = 0
# do special action here!
}
}
# Here, the event ist registered. You need only subscribe to events that you need:
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData 'Hello' -Action $scriptBlock
推荐阅读
- javascript - TypeError: (0 , _react.useEffect) 不是函数
- asp.net - IIS 7.5 在服务器重新启动后使用 Windows 身份验证时提示输入凭据
- flask-sqlalchemy - Flask-SQLAlchemy 查询返回数据库类和数据
- python - Beautiful Soup 如何使用 find_all 检查多个属性中的任何一个?
- mysql - MYSQL 更新列具有来自其他表的更高值
- javascript - TypeError: Cannot read property 'spirit' of undefined -- 该属性可以在页面刷新时读取
- image - Lua / Love 2d:用像素缩放图像
- react-native - React Native:您如何处理使屏幕顶部的图形时间等难以看到的问题?
- javascript - Kendo UI 网格过滤调用了两次
- python - 熊猫正向填充最后一个值的标量倍数