powershell - 使用 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
笔记:
- 如果未使用 $IncludeExt,则将其指定为 $Null,如果使用,则列表如下所示 " .csv"," .docx"
- $Filename 对于所有文件名都指定为“*”。还将测试从 -match 更改为 -like,因此部分文件名应包含 *,例如“部分名称”。
- 请注意,我更改了扩展检查的位置以使用 Get-ChildItem 的 -Include 参数与检查 Where-Object 的位置。
- 将数据管道更改为连续的 Where-Object 子句并替换为 -and 运算符,效果相同且效率更高。
- 更改了目录测试以使用 PIsContainer 属性,看不到您从哪里获得 $Folder 的值。
- 从 Select-Object 中删除了连续字符,因为逗号用于此目的并且更简洁。
推荐阅读
- javascript - 如何使用带有 discord.js 的 api 发送图像
- php - 根据php中的条件更新或插入
- django - Django 查询集自定义顺序
- typescript - 有什么区别
和 ? - c - qperf C github https://github.com/rbruenig/qperf
- bash - Jenkins - If Else 语句未在脚本块中执行
- java - VSCode 在尝试运行命令时不断出现 Invalid string length 的错误
- javascript - 如何使单个组件具有与链接路径相同的图像(Angular)
- html - 如何更改所有编写的 VS Code 的选项卡大小?
- reactjs - Tailwind css 在构建和部署后无法在 Vercel 上运行