使用 Split-Path 根据扩展名替换文件

Replace files based on extension using Split-Path

首先让我说,在这方面我是一个完全的初学者。我正在尝试用占位符替换一堆丢失的文件。问题是有多种文件类型,每种类型都需要不同的占位符文件。

我使用的是 powershell 7,Split-Path -extension 似乎工作得很好。但是我似乎无法通过 if 语句来 select 正确的占位符文件。

如有任何帮助,我们将不胜感激。

# List of Files to be replaced
$CSVFile ="C:\FileList.csv"
# Header for file location column
$FileLocationHeaderInCSV ="FileLocation"
#PlaceHolderFile Location
$PlaceHolderJPG ="C:\MissingFile.jpg"
$PlaceHolderTIF ="C:\MissingFile.tif"


Import-Csv $CSVFile | ForEach-Object {

    #CSV File Header Row
    $FileLocation = $_.$($FileLocationHeaderInCSV)

    $DestinationFolder= (Split-Path -Path $FileLocation)
   
    #Test if the folder exists, if it doesn't create it!
    if (!(Test-Path -path $DestinationFolder)) {
    
    New-Item $DestinationFolder -Type Directory
    
    Write-Host "Creating Folder '$DestinationFolder'" -ForegroundColor Green
    }

    else {
    
         }
    
    $FileExtension =(Split-Path -Extension $FileLocation)

    if ($FileExtension -eq ".JPG") {
        $PlaceHolderFile= $PlaceHolderJPG
        }
    elseif ($FileExtension -eq ".TIF") {
        $PlaceHolderFile= $PlaceHolderTIF
        }
        
    elseif ($FileExtension -eq ".TIFF") {
        $PlaceHolderFile= $PlaceHolderTIF
        }
        
    elseif ($FileExtension -eq ".IMG") {
        $PlaceHolderFile= $PlaceHolderTIF
        }
        
    else {
        Write-Host "Unknown File Type!!!!" -ForegroundColor Red
        }           
   

    Write-host "Replacing File '$FileLocation'" -ForegroundColor Cyan
    Copy-Item $PlaceHolderFile -Destination $FileLocation 

}

这将是 switch 语句的完美用例:

$PlaceHolderFile = switch (Split-Path $FileLocation -Extension) {
    ".JPG" { $PlaceHolderJPG }
    ".TIF" { $PlaceHolderTIF }
    ".TIFF" { $PlaceHolderTIF }
    ".IMG" { $PlaceHolderTIF }
    default { throw "Unknown file type: $_" }
}

switch 也有一些高级功能,例如你可以使用 -Regex:

$PlaceHolderFile = switch -Regex (Split-Path $FileLocation -Extension) {
    '^\.JPG$' { $PlaceHolderJPG }
    '^\.(TIFF?|IMG)$' { $PlaceHolderTIF }
    default { throw "Unknown file type: $_" }
}

另一个简短的one-liner方式:

$ext=Split-Path $FileLocation -Extension;if($ext -eq ".JPG"){$PlaceHolderJPG};if($ext-match"\.(TIF|TIFF|IMG)$"){$PlaceHolderTIF}