gpt4 book ai didi

powershell - 检查文件夹是否也已完成复制

转载 作者:行者123 更新时间:2023-12-03 01:09:11 24 4
gpt4 key购买 nike

我想运行一个脚本,该脚本在使用一堆文件(例如一堆.pdf的文件)的Windows上执行特定程序。问题是我正在从另一个位置接收这些文件到共享文件夹。因此,仅在所有文件都已从我无法控制的另一个驱动器完成复制后,我才需要检查此共享文件夹并执行程序。

无论如何要这样做?我所有的搜索都使我开始使用Powershell和类似这样的脚本,除了代替记录文件的操作外,我还需要执行程序,但是我不知道该怎么做,因为最后复制的文件/文件夹已经完成了。

 ### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\User\Desktop\monitor_this"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "C:\Users\User\Desktop\log.txt" -value $logline
}
### 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}

最佳答案

基于wOxxOm的评论,我尝试扩展上述示例:

 ### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\User\Desktop\monitor_this"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

### Create timer
$timer = new-object timers.timer
$timer.Interval = 5000 #5 seconds
$timer.Enabled = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$fileWatcherAction = {
# Reset the timer every time the file watcher reports a change
write-host "Timer Elapse Event: $(get-date -Format ‘HH:mm:ss’)"
$timer.Stop()
$timer.Start()
}

$timerAction = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "C:\Users\User\Desktop\log.txt" -value $logline
}

### When timer fires timerAction is called
Register-ObjectEvent $timer "Elapsed" -Action $timerAction

### DECIDE WHICH EVENTS SHOULD BE WATCHED, every call of below events resets the timer
Register-ObjectEvent $watcher "Created" -Action $fileWatcherAction
Register-ObjectEvent $watcher "Changed" -Action $fileWatcherAction
Register-ObjectEvent $watcher "Deleted" -Action $fileWatcherAction
Register-ObjectEvent $watcher "Renamed" -Action $fileWatcherAction
while ($true) {Start-Sleep 5}


我实际上不确定 $timer的闭包处理,也许您需要对Powershell和闭包进行一些其他研究。

希望能有所帮助。

关于powershell - 检查文件夹是否也已完成复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com