Get-Childitem - find partial filename in folders

45 Views Asked by At

How can I get the Get-ChildItem command to find a partial name within folder structures? My script works if I specify the exact filename in my input.txt file, but I won't know the exact name, only the first few characters of the file name.

Script is:

# source and destionation directory
    $source      = "C:\Data_Files\Source"
    $destination = "C:\Data_Files\Output"

# list of files from source directory that I want to copy to destination folder
$file_list = Get-Content "C:\Data_Files\Input.txt" 
      
#foreach file in the text
foreach ($file in $file_list) {
    # foreach file in the folders
    foreach($dir in (Get-ChildItem $source -Recurse )){
        # if the file name is in diretocry listed
        if($file -eq $dir.name){
            # copy only once, if the document name already 
    exists, skip
            if(-not(test-path "$destination\$file")){
                # copy the file
                Copy-Item $dir.fullname -Destination 
    $destination -Verbose
                }
            }
        }
    }

In input.txt I have a list of files I'm looking for within the source folder like

5457-2100-03071HHM.xxx 236149-3400-03853CPM.xxx

But I need to search for 5457 & 236149 of the filename only. I just can't find a way to get powershell to do this? Any help appreciated.

1

There are 1 best solutions below

2
Ricardo Gellman On

You could try this powershell script

param (
    [string]$rootFolderPath = "C:\Your\Root\Folder\Path",
    [string]$grepPartialFileName = "PartialFileName"
)

# Get all files recursively
$files = Get-ChildItem -Path $rootFolderPath -File -Recurse

# Filter files by partial name
$filteredFiles = $files | Where-Object { $_.Name -like "*$grepPartialFileName*" }

# Display the file structure
foreach ($file in $filteredFiles) {
    Write-Host $file.FullName
}
.\YourScript.ps1 -grepPartialFileName "PartialFileName"