I would like to match files that contain one of the keywords in an array list $filterLists from a group of source folders $srcRoot$. Wildcards are being used in the array but having trouble making an actual match.
Edit: the desired result would return the filenames that include one of the words in $filterList if it ends up being a match.
This is my current code
#requires at least -version 3
$srcRoot = 'C:\parent\web\'
$dstRoot = $MyInvocation.MyCommand.Path
#Find subfolder within the source root folder path
$MyVariable = (Get-ChildItem -Path $srcRoot -Filter "views" -Recurse -Directory).Fullname
#Find sub-subfolder within the sub-folder paths above
$srcRoot = (Get-ChildItem -Path $MyVariable -Filter "graphics" -Recurse -Directory).Fullname
#Set the files name which eventually need to move to destination folder
$filterLists = @("*floor*","*flr*","*level*", "*lvl*", ,"*roof*", "*summary*")
#Get all the child file list with source folder
$fileList = Get-ChildItem -Path $srcRoot -Force -Recurse
#loop the source folder files to find the match
foreach ($file in $fileList)
{
$HasFileBeenMatchedYet = $false
foreach ($filterList in $filterLists)
{
if ($file -in $filterList)
{
$HasFileBeenMatchedYet = $true
break
}
}
if ($HasFileBeenMatchedYet -eq $true)
{
Write-Host "$file is a match"
}
else
{
Write-Host "$file not found in list"
}
}
Any help is greatly appreciated!
CodePudding user response:
Get-ChildItem has a -Include parameter meant exactly for what you're looking for:
Specifies an array of one or more string patterns to be matched as the cmdlet gets child items. Any matching item is included in the output. Enter a path element or pattern, such as "*.txt". Wildcard characters are permitted.
Note that -Filter in this case is looking for an exact match of folders with name views and graphics, if you're looking for a partial match use wildcard characters: * and / or ?.
$srcRoot = 'C:\parent\web\'
$dstRoot = $MyInvocation.MyCommand.Path
$filterLists = "*floor*", "*flr*", "*level*", "*lvl*", "*roof*", "*summary*"
Get-ChildItem -Path $srcRoot -Filter "views" -Recurse -Directory |
Get-ChildItem -Filter "graphics" -Recurse -Directory |
Get-ChildItem -Force -Recurse -Include $filterLists -File
$filterLists = '*floor*', '*flr*', '*level*', '*lvl*', '*roof*', '*summary*'
$srcRoot = 'C:\parent\web\'
$params = @{
Path = $srcRoot
Filter = 'views'
Recurse = $true
Directory = $true
}
# All folders under `$srcRoot` with name 'views'
$viewsFolders = Get-ChildItem @params
$params.Path = $viewsFolders.FullName
$params.Filter = 'graphics'
# All folders under `$viewsFolders` with name 'graphics'
$graphicsFolders = Get-ChildItem @params
# All files under `$graphicsFolders`
foreach($file in Get-ChildItem -Path $graphicsFolders -File -Recurse -Force)
{
# Where the file name contains one of these filters
foreach($filter in $filterLists)
{
if($file.Name -like $filter)
{
$file
# if you want to stop at the first finding
# add `break` here
}
}
}
