I am working on a Powershell script that will return a list of files based on a filtered set of names and a specific extension, which in this case of the .pdf
extension file type. I currently have this set up in a foreach
control structure.
So far I have done this:
$MechDWGFilterList = @('*ifc*','*mech*', '*permit*', '*final*', '*CD*')
$MechDWGFile = @()
# $MechDWGFolder contains 1 or more filtered full path files
$MechDWGList = Get-ChildItem -Path $MechDWGFolder -Filter *.pdf -r | Sort-Object -Descending -Property LastWriteTime
$count = 0
foreach ($file in $MechDWGList)
{
# Where the file name contains one of these filters
foreach($filter in $MechDWGFilterList)
{
if($file.Name -like $filter)
{
$MechDWGFile = $file
$count = 1
}
}
}
But I would like to condense something like below where I can avoid having to create an additional object $MechDWGFile
from the above code.
$MechDWGFilterList = @('*ifc*','*mech*', '*permit*', '*final*', '*CD*')
$MechDWGFilterList2 = 'ifc|mech|permit|final|CD' #Tried this regex expression as well
$MechDWGList = Get-ChildItem -Path $MechDWGFolder -Filter ($MechDWGFilterList).pdf -r | Sort-Object -Descending -Property LastWriteTime
Write-Output $MechDWGList
I feel like I'm close, unless this is completely not doable without an iterative control loop. Help understanding this challenge would be greatly appreciated!
Some other background refernce info: PowerShell 5.1 is being used as Administrator, Windows 10 OS
CodePudding user response:
-Filter
only supports *
and ?
wildcards. In this case you could pipe the result of Get-ChildItem
to Where-Object
for filtering:
$MechDWGList = Get-ChildItem -Path $MechDWGFolder -Filter *.pdf -r |
Where-Object { $_.Name -match 'ifc|mech|permit|final|CD' } |
Sort-Object -Descending -Property LastWriteTime
This would be basically like doing this with a foreach
loop and an if
condition:
$MechDWGList = & {
foreach($file in Get-ChildItem -Path $MechDWGFolder -Filter *.pdf -r) {
if($file.Name -match 'ifc|mech|permit|final|CD') { $file }
}
} | Sort-Object -Descending -Property LastWriteTime