在最近 1 分钟内创建的文件中查找特定单词的 Powershell 脚本

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

刚刚编写的 Powershell 脚本将在子文件夹中查找 1 分钟前创建的名称中包含“.doc_”的文件,然后将其移动到另一个子文件夹。

当我 运行 powershell 脚本时,它将移动 1 分钟前创建的名称中包含“.doc_”的文件,但它也会移动名称中包含“.doc_”的相同文件几天前创建的,不需要。

能否请您告诉我为什么我的代码考虑了超过 1 分钟的文件

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"

简而言之,您对 Get-Date 的过滤器是错误的,因为它在 1 分钟前 之前抓取了所有内容。这是由于 -lt 运算符,如果您将它与 -gt 运算符交换,它应该可以工作。

好,下一题。由于您实际上并不是在文件中搜索特定单词,而是在文件名中搜索,我们可以使用 FileSystem 提供程序来过滤该文件名,我们将牺牲 RegEx使用-match),到使用通配符表达式;这将使速度提高 40 倍,因为在管道中发送任何东西都非常 昂贵:

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"

如果时间紧迫,我们可以尝试使用 grouping 运算符 ( .. ).Where({}) [=40] 来避开管道=].

  • 它被认为更像是一个运算符,因为它不会对对象本身执行任何直接操作。
(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"