问题描述
总的来说,我对 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 运算符,效果相同且效率更高。
- 将目录的测试更改为使用 PSIContainer 属性,无法看到您从何处获取 $Folder 的值。
- 从 Select-Object 中删除了连续字符,因为逗号用于此目的并且更干净。