1

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

我正在使用 powershell 7,并且 Split-Path -extension 似乎工作得很好。但我似乎无法使用 if 语句来选择正确的占位符文件。

任何帮助将不胜感激。

# 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 

}
4

2 回答 2

1

这将是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: $_" }
}
于 2020-10-05T15:31:51.397 回答
0

另一种简短的单线方式:

$ext=Split-Path $FileLocation -Extension;if($ext -eq ".JPG"){$PlaceHolderJPG};if($ext-match"\.(TIF|TIFF|IMG)$"){$PlaceHolderTIF}
于 2020-10-05T16:04:07.697 回答