使用FileSystemWatcher监视文件

时间:2017-08-08 20:24:03

标签: powershell events monitor

我正在尝试创建一个PowerShell程序来监视某个路径中某个文件的修改时间,并且只有当它现在包含“已成功加载”字符串时才会显示Write-Host。如果在一定时间内找不到字符串,最终将添加电子邮件组件。

$folder = 'C:\Users\afila\Desktop\TEST' # Enter the root path you want to monitor. 
$files = Get-ChildItem $folder
$filter = '*.txt'  # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $false;
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}

# Function to search folder contents for a string
function Search-Folder {
    $SearchTerm = "Loaded successfully"

    foreach ( $file in $files) {
        $text = Get-Content "$folder\$file"
        if ($text | where {$text -like "*$SearchTerm*" }) {
            Write-Host "The file '$file succeeded" -fore white
            Out-File -FilePath C:\Users\afila\Desktop\SucceededLog.txt -Append -InputObject "The file '$file' completed at $timeStamp"
        }
    }
}

# Here, all the Changed event is registerd. 
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType 
    $timeStamp = $Event.TimeGenerated  
    $searchTerm = "Loaded successfully"
    foreach ($file in $files) {
        $text = Get-Content "$folder\$file"
        if ($text | where {$text -like "*$searchTerm*"}) {
                Write-Host "The file '$name' was $changeType at $timeStamp" -fore magenta 
                Out-File -FilePath C:\Users\afila\Desktop\TestLogItems\TestLog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
        }
    }
}

# To stop the monitoring, run the following commands: 
Unregister-Event FileChanged

1 个答案:

答案 0 :(得分:0)

FileSystemWatcher已经通过属性$Event.SourceEventArgs.Path为您提供了文件的完整路径,因此您无需循环遍历文件列表。

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
    $path = $Event.SourceEventArgs.Path
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    $searchTerm = 'Loaded successfully'

    if ((Get-Content $path) -like "*$searchTerm*"}) {
        Write-Host "The file '$name' was $changeType at $timeStamp"
    }
}