简体   繁体   English

检查列表中的文件是否存在或具有相同的基本名称

[英]Check if file from list exist or have the same basename

I'm looking to optimize this script with a function我希望使用 function 优化此脚本

$Folder = 'K:\dxf\dxf50000-60000'
$filenames = Get-Content -Path .\files.txt
    
$missingFilesList = New-object System.Collections.ArrayList
Write-Host "Folder: $folder."
Write-Host "Searching for files"
    
foreach ($filename in $filenames) {
    $found=$false; 
    Get-ChildItem -Path $Folder -Recurse | ForEach-Object {if($filename -eq $_.BaseName) {Write-Host 'FILE ' $filename ' Ok' -foregroundcolor green; $found=$true;CONTINUE }$found=$false;} -END {if($found -ne $true){ Write-Host 'FILE ' $filename ' missing in the folder' -foregroundcolor red}}
}

Generally I'm looking for files with the same format everytime: basename-revision通常我每次都在寻找具有相同格式的文件:basename-revision

51713-0 51762-0 51780-0 51713-0 51762-0 51780-0

Now I also want to search for the basename (ie 51713) and report this back with the basename and revision if found (and change the color to cyan or something) - what would be the best way to achieve this?现在我还想搜索基本名称(即 51713),如果找到基本名称和修订版(并将颜色更改为青色或其他颜色),则将其返回报告 - 实现此目的的最佳方法是什么?

This should work这应该工作

My C:\files.txt contains the following content:我的 C:\files.txt 包含以下内容:

51713-0 51714-0 51714-1 51714-2 51714-3 51799-0 51713-0 51714-0 51714-1 51714-2 51714-3 51799-0

Outputs the following输出如下

# Define the folder where we look for the files
$FilesFolder = 'C:\dxf50000-60000'

# Define the list of files to check for
$FileNameList = Get-Content -Path c:\files.txt

# Get all the files in the FilesFolder
$ContainingFiles = Get-ChildItem $FilesFolder

Write-Host "Folder: $FilesFolder."
Write-Host "Searching for files"

# Go through each file in the FilesFodler
foreach ($FileName in $FileNameList) {

    # Define basename
    $BaseName = $FileName.Split("-")[0]

    # Define revision
    $Revision = $FileName.Split("-")[1]

    # If the folder contains a matching basename AND revision, write output GREEN
    If ($ContainingFiles.Name -like "*$BaseName-$Revision*"){

        Write-Host "Successfully found file basename [$BaseName] with revision [$Revision]" -ForegroundColor Green
            
    # If the folder contains a matching basename but NOT revision, write output CYAN
    }ElseIf ($ContainingFiles.Name -like "*$BaseName*"){

        Write-Host "Successfully found file basename [$BaseName] with revision [$Revision]" -ForegroundColor Cyan
    
    # If no matching basename was found, write output RED
    }Else{

        Write-Host "Failed to find file with basename [$BaseName]" -ForegroundColor Red
    
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM