【问题标题】:PowerShell - Unable to Search for [LIKE] File Names recursively through sub-directoriesPowerShell - 无法通过子目录递归搜索 [LIKE] 文件名
【发布时间】:2021-06-20 06:04:45
【问题描述】:

我有一个需要搜索的数百个文件的列表。大多数没有文件扩展名,有些有。如果需要,我可以将它们分开并多次运行该作业。

我有一个脚本,我一直在尝试正确,但它似乎不起作用。 我只需要匹配文件名而不是扩展名。
我正在使用“-Like”选项,但这并没有让我得到我需要的结果。如果我包含文件扩展名,那么它可以工作。不幸的是,我有许多扩展名未知的文件名,我只需要匹配名称。

此外,脚本似乎并未扫描子目录以查找匹配项。 -Recurse 在我的示例中不起作用吗?

最后,当测试和 I FORCE 匹配时,它不会显示找到匹配的子目录。

非常欢迎任何帮助。 问候, -罗恩

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

【问题讨论】:

    标签: powershell search regexp-like


    【解决方案1】:

    Get-ChildItem-Name 开关在与-Recurse 结合时不仅输出名称,它还输出相对路径对于位于子目录中的项目。

    因此,最好不要使用此开关,并与Get-ChildItem 默认发出的[System.IO.FileInfo] 实例的.Name 属性 进行比较。

    # Get only files and only their names - note the use of (...).Name
    $folderFiles = (Get-ChildItem -Recurse $folder -File).Name
    

    请注意,如果您的$Dir2\MISSING_BMS.txt 文件包含逐字 文件名而不是通配符模式,则应使用-contains 运算符而不是-like,@ 987654324@.

    另外,如果您以后需要访问完整路径:

    # 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) { ...
    
    

    【讨论】:

    • 行得通!我将更改上面的代码以反映您建议的更改。非常感谢! -罗恩
    猜你喜欢
    • 2019-05-11
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多