I have a list of a few hundred files that I need to search for. Most do NOT have file extensions, some do. I can separate those and run the job multiple times if I have to.
I have a script that I have been trying to get right and it Does not seem to work.
I need to match on just the file names and NOT the extensions.
I'm using the "-Like" option but that is not getting me the results I need. If I include a file extension then it works. Unfortunately I have many file names with unknown extensions and I need to match on just the name.
Also, the script does not seem to be scanning the sub-directories for matches. Does -Recurse not work in my example?
And Finally, when testing and I FORCE a match, it does not display the subdirectory the match was found in.
Any assistance would be most welcome. Regards, -Ron
#Start in this DIR
$folder = 'C:\Workspace\'
#Get the file list here
$Dir2 = 'C:\Workspace\'
$files=Get-Content $Dir2\MISSING_BMS.txt
Write-Host "Starting Folder: $folder"
# Get only files and only their names
$folderFiles = Get-ChildItem -Recurse $folder -File -Name
#Read through Directory and sub-directories
foreach ($f in $files) {
if ($folderFiles -contains $f) {
Write-Host "File $f was found." -foregroundcolor green
} else {
Write-Host "File $f was not found!" -foregroundcolor red
}
}
Get-ChildItem
's -Name
switch doesn't just output names when combined with -Recurse
, it outputs relative paths for items located inside subdirectories.
Therefore, it is better not to use this switch and compare against the .Name
property of the [System.IO.FileInfo]
instances that Get-ChildItem
emits by default.
# Get only files and only their names - note the use of (...).Name
$folderFiles = (Get-ChildItem -Recurse $folder -File).Name
Note that if your $Dir2\MISSING_BMS.txt
file contains verbatim file names rather than wildcard patterns, you should use the -contains
operator rather than -like
, the wildcard matching operator.
Also, if you need to access the full paths later:
# Get the files as [System.IO.FileInfo] instances
$folderFileInfos = Get-ChildItem -Recurse $folder -File
# ...
# Access the .Name property now, using member enumeration, and see
# if the array of names contains $f
if ($folderFileInfos.Name -contains $f) { ...