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
}
This would be a perfect use case for a switch statement:
switch
also has some advanced capabilities, e.g. you could use-Regex
: