【问题标题】:Check if file from list exist or have the same basename检查列表中的文件是否存在或具有相同的基本名称
【发布时间】:2022-10-04 21:21:44
【问题描述】:

我正在寻找一个函数来优化这个脚本

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

通常我每次都在寻找具有相同格式的文件:basename-revision

51713-0 51762-0 51780-0

现在我还想搜索基本名称(即 51713),并在找到时将其与基本名称和修订版一起报告(并将颜色更改为青色或其他东西) - 归档这个的最佳方法是什么?

【问题讨论】:

  • 我很困惑 - 这些文件没有扩展名吗? files.txt 是只包含基本名称,还是包含文件名的两个部分?

标签: list powershell file-exists


【解决方案1】:

这应该工作

# 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:iles.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
    }Else{

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多