Home > Blockchain >  Powershell script that looking for specific word in file which created in last 1 Min
Powershell script that looking for specific word in file which created in last 1 Min

Time:11-15

Just wrote Powershell script that will look in Sub-Folder about the file which include ".doc_" in it's name that created 1 Min ago then to move it to another Sub-Folder.

When I ran the powershell script it will move that file which having ".doc_" in it's name that created 1 Min ago but also it will move same files which had ".doc_" in it's name that created days ago which is not required.

Could you please let me know why my code take in consideration files which is more than 1 Min

get-childitem -Path "C:\Users\Administrator\Desktop\Test\Test2" | where-object {$_.Name -match ".doc_" -and $_.LastWriteTime -lt (get-date).Adddays(-0) -and $_.LastWriteTime -lt (get-date).AddMinutes(-1)}| move-item -destination "C:\Users\Administrator\Desktop\Test"

CodePudding user response:

In short, your filter for Get-Date is wrong in the sense of it grabbing everything before 1 minute ago. This is due to the -lt operator, which should work if you swap it with the -gt operator.

Okay, next subject. Since you're not actually searching for specific words inside files, but instead in the file names, we can use the FileSystem Provider to filter for that file name, which we will sacrifice RegEx (using -match), to using wildcard expressions; this will speed things up to 40x faster as sending anything down the pipeline is quite expensive:

Get-ChildItem -Path "C:\Users\Administrator\Desktop\Test\Test2" -Filter "*.doc_*" | 
    where-object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-1) } | 
    Move-Item -Destination "C:\Users\Administrator\Desktop\Test"

And if time is of the essence, we can try avoiding the pipeline using the the grouping operator ( .. ), and the .Where({}) operator/method.

  • It's considered more of an operator due to the fact that it doesn't perform any direct action against the object(s) themselves.
(Get-ChildItem -Path "C:\Users\Administrator\Desktop\Test\Test2" -Filter "*.doc_*").Where{ 
    $_.LastWriteTime -gt (Get-Date).AddMinutes(-1) 
} | Move-Item -Destination "C:\Users\Administrator\Desktop\Test"
  • Related