Get-Childitem - 在文件夹中查找部分文件名

问题描述 投票:0回答:1

如何使用 Get-ChildItem 命令在文件夹结构中查找部分名称?如果我在 input.txt 文件中指定确切的文件名,我的脚本就可以工作,但我不知道确切的名称,只知道文件名的前几个字符。

脚本是:

# 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
                }
            }
        }
    }

在 input.txt 中,我有一个在源文件夹中查找的文件列表,例如

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

但我只需要搜索文件名的 5457 和 236149 。我只是找不到一种方法让 powershell 来做到这一点?任何帮助表示赞赏。

get-childitem
1个回答
0
投票

你可以尝试这个powershell脚本

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"
© www.soinside.com 2019 - 2024. All rights reserved.