我需要一个PowerShell脚本来实时监控特定目录中的文本文件(以* .txt结尾的文件),将文件名导出到csv文件并开始捕获&仅在新目录中保存新文件时导出。请注意,同时在目录中保存了多个文件。
以下是我所写的内容,但显然这一直在反复写入相同的文本文件。我希望脚本第一次捕获文件,并从下一次捕获&仅在有新文件时导出
$x = 1
do {
$file1 = Get-ChildItem D:\Test\*.txt | Select-Object name,length,LastWriteTime
$file2 = $file1
foreach ($file2 in $file1) {
$file1 | Export-Csv -path D:\FileSize\TEMPTXT.csv
[System.IO.File]::ReadAllText("D:\FileSize\TEMPTXT.csv") |
Out-File D:\FileSize\TEXT.csv -Append -Encoding ascii
}
} until ($x=0)
答案 0 :(得分:1)
您可以使用system.io命名空间中的FileSystemWatcher .Net类来订阅监视新文件的事件(使用txt文件的过滤器)。只需设置所需的操作即可。
只需确保输出到您正在观看的文件夹中的其他文件夹(或使用specix前缀或后缀输出它们)以防止无限循环。
此示例代码:
$FSWatcher = New-Object System.IO.FileSystemWatcher
$FSWatcher.Path = "E:\MKV"
$FSWatcher.Filter = "*.txt"
$FSWatcher.IncludeSubdirectories = $false
$FSWatcher.NotifyFilter = "FileName", "CreationTime"
Register-ObjectEvent -InputObject $FSWatcher -EventName Created -SourceIdentifier NewFileCreated -Action {
$EventInfo = $Event.SourceArgs
$TextOutput = [string]::Format("{0} was {1}. Fullpath : {2}",$Eventinfo.Name,$EventInfo.ChangeType,$EventInfo.FullPath)
Write-Host $TextOutput
}
(我之前没有编写代码示例的主要原因是因为此类的一个示例已经包含了使用户脚本工作所需的95%的代码)
答案 1 :(得分:0)
$FSWatcher = New-Object System.IO.FileSystemWatcher
$FSWatcher.Path = "E:\Test"
$FSWatcher.IncludeSubdirectories = $false
$FSWatcher.NotifyFilter = "FileName", "LastWrite","Size"
Register-ObjectEvent -InputObject $FSWatcher -EventName Created -SourceIdentifier NewFileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Out-File -FilePath E:\FilesCreated\FilesCreated.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
$filesize = Get-Item E:\Test\$name | select-object name,length,LastWriteTime | export-csv E:\FileSize\TEMPTXT.csv
[System.IO.File]::ReadAllText("E:\FileSize\TEMPTXT.csv") | Out-File E:\FileSize\TEXT.csv -Append -Encoding ascii
}