MG2016
MG2016

Reputation: 319

Powershell - checking for new files

This code seems to only work if a 'new' file is created. It seems it doesn't accept a file copied into the folder, which is what I need. We have an application which processes .csv files and puts them into a folder which I want to monitor via a scheduled task each day. Anything I can try to change in this code?

Param (
[string]$Path = "C:\Users\MG\Desktop\ScanFolder"
)                                                                        
$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge (Get-Date).AddHours(-1) }                                                                           
If ( $File ) {                                                          
Write-Output "Error File Found"                                              
}                                                                         
else { Write-Output "Nothing Found" }

Upvotes: 1

Views: 3248

Answers (1)

mklement0
mklement0

Reputation: 439193

Test the value of .CreationTime / .CreationTimeUtc instead:

  • for newly created files, it will reflect the creation time.

  • for newly copied files, it will reflect the time the file was copied to the folder (even though that will be more recent than the file's .LastWriteTime value).

Applied to your code:

Param (
  [string] $Path = "C:\Users\MG\Desktop\ScanFolder"
)                                                                        

$file = Get-ChildItem $Path | Where { $_.CreationTime -ge (Get-Date).AddHours(-1) }                                                                           

If ($file) {                                                          
  "Error File Found"                                              
} else { 
  "Nothing Found" 
}

Upvotes: 2

Related Questions