首页 > 解决方案 > 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}

但我不知道如何将监控设置为多个文件,而不仅仅是一个。

标签: powershellfileactionmonitoring

解决方案


这应该适合你。不要忘记在使用/测试后取消注册事件!

#--------------------------------------------------
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

推荐阅读