0
votes

I need a PowerShell script to monitor text files (files ending with *.txt) real time in a particular directory, export the file names to a csv file and start capturing & exporting ONLY if new files are saved in that directory. Please note that more than one file is saved in the directory simultaneously.

Below is what I have written, but obviously this keeps writing the same text files over and over again. I want the script to capture files the first time, and from the next time, capture & export only if there is a new file

$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)
2

2 Answers

1
votes

You can use the FileSystemWatcher .Net class from the system.io namespace to subscribe to an event that monitors new files (with a filter for txt files). Just setup the desired action and you're ready.

Just make sure that you output to a different folder as the one you are watching (or output them with a specifix prefix or suffix) to prevent infinite loops.

Sample code for this :

$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
}

(the main reason for me not writing a code example earlier was because an example of this class already containts 95% of the code needed to have the user's script working)

0
votes
$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
}