Replace files based on extension using Split-Path

274 views Asked by At

Let me start out by saying I am a complete beginner when it comes to this stuff. I am trying to replace a bunch of missing files with a place holder. Problem is there are multiple file types each needing a different place holder file.

I am using powershell 7, and Split-Path -extension seems to work just fine. But I can't seem to an if statement to allow me to select the correct placeholder file.

Any help would be greatly appreciated.

# 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 

}
2

There are 2 answers

1
marsze On BEST ANSWER

This would be a perfect use case for a switch statement:

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

switch also has some advanced capabilities, e.g. you could use -Regex:

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

Another short one-liner way:

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