使用 powershell 进行高级文件搜索

问题描述

总的来说,我对 Powershell 和编程还很陌生。我想使用具有多个条件的 Powershell 搜索文件。我已经设法编写了这段代码

$Drives = Get-PSDrive -PSProvider 'FileSystem' 
$Filename= 'Result'
$IncludeExt= '*csv,*docx'
$startDate= '11/1/20'
$EndDate= '1/26/21'

Get-ChildItem -Path $Drives.Root -Recurse  |Where-Object {$IncludeExt -match $_.Extension} |  Where-Object { $_.BaseName -match $Filename}  | Where-Object {$_.lastwritetime -ge $startDate -AND $_.lastwritetime -le $EndDate} |

foreach{ 
$Item = $_.Basename
$Path = $_.FullName 
$Type = $_.Extension
$Age = $_.CreationTime


$Path | Select-Object `
    @{n="Name";e={$Item}},`        
    @{n="Created";e={$Age}},`
    @{n="filePath";e={$Path}},`
    @{n="Folder/File";e={if($Folder){"Folder"}else{$Type}}}` 

}| Export-Csv D:\FFNew.csv -NoTypeinformation

当提到所有变量时,这很有效。但是我如何在

案例 1:如果 $Filename 为空,则它给出所有具有上述扩展名的文件和在日期范围内修改文件

案例 2:如果 $IncludeExt 为空,那么它给出所有提到 $Filename 的文件,目前它只给出在日期范围内修改文件夹和文件

案例 3:如果 $Filename 和 $IncludeExt 为空,则给出 $startDate 和 $EndDate 之间修改的所有文件

解决方法

普拉内,

[编辑] 好的,这是带有注释和示例输出的修订(精确)脚本。注意:您必须更改特定于我的机器的项目!

$Drives     = Get-PSDrive -PSProvider 'FileSystem' 
$Filename   = "*" #for all or "*partial name*"
$IncludeExt = $Null #for no ext. or "*.csv","*.docx",etc...
$StartDate  = '01/1/2020' #to ignore this use 1/1/1920
#For latest date use below otherwise specify date.
$EndDate    = (Get-Date).ToShortDateString() 

#Note: below uses only 3rd drive in the array remove [2] for all.
$GCIArgs = @{Path    = $Drives[2].Root
             Recurse = $True
            }

If ($Null -ne $IncludeExt) {
  $GCIArgs.Add("Include",$IncludeExt)
}

Get-ChildItem @GCIArgs   |
  Where-Object {($_.BaseName -Like $Filename)     -and 
                ($_.lastwritetime -ge $StartDate) -and
                ($_.lastwritetime -le $EndDate) } |

foreach{ 

$Item = $_.Basename
$Path = $_.FullName 
$Type = $_.Extension
$Type = & {if($_.PSIsContainer){"Folder"}else{$_.Extension}}
$Age  = $_.CreationTime


$Path | Select-Object @{n="Name"       ;e={$Item}},@{n="Created"    ;e={$Age}},@{n="filePath"   ;e={$Path}},@{n="Folder/File";e={$Type}}  
 }  | Export-Csv -LiteralPath 'G:\BEKDocs\FFNew.csv' -NoTypeInformation 

注意事项:

  1. $IncludeExt 被指定为 $Null,如果它没有被使用,如果使用,列表就像这样“.csv”,“.docx”
  2. $Filename 为所有文件名指定为“*”。还将测试从 -match 更改为 -like,因此部分文件名应包含 *,例如“部分名称”。
  3. 请注意,我将检查扩展的位置更改为使用 Get-ChildItem 的 -Include 参数,而不是检查 Where-Object。
  4. 将数据管道更改为连续的 Where-Object 子句并替换为 -and 运算符,效果相同且效率更高。
  5. 将目录的测试更改为使用 PSIContainer 属性,无法看到您从何处获取 $Folder 的值。
  6. 从 Select-Object 中删除了连续字符,因为逗号用于此目的并且更干净。

单个驱动器上的示例输出(根据上面显示的代码),出于空间考虑隐藏了一些行,但请注意最后一行编号。 enter image description here

所有驱动器上的示例输出(根据代码中的注释编辑代码),再次隐藏行以节省空间,但显示多个驱动器和最终行号。 enter image description here HTH