首页 > 解决方案 > 使用 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 之间修改的所有文件

标签: powershellmultiple-conditionsfile-search

解决方案


普拉奈,

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

$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. 更改了目录测试以使用 PIsContainer 属性,看不到您从哪里获得 $Folder 的值。
  6. 从 Select-Object 中删除了连续字符,因为逗号用于此目的并且更简洁。

单驱动器上的示例输出(上面显示的每个代码),出于空间考虑隐藏了一些行,但请注意最后一行号。 在此处输入图像描述

所有驱动器上的示例输出(根据代码中的注释编辑代码),再次为空间隐藏行,但显示多个驱动器和最终行号。 在此处输入图像描述 HTH


推荐阅读