Created
September 5, 2024 20:25
-
-
Save futuremotiondev/a2dc5bf94e8732cccd5400244dc7287e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Convert-SVGCropWithInkscape { | |
[CmdletBinding()] | |
param ( | |
[parameter( Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName )] | |
[ValidateScript({ | |
if ($_ -notmatch '[\?\*]') { | |
$true | |
} else { | |
throw 'Wildcard characters *, ? are not acceptable with -LiteralPath' | |
} | |
})] | |
[ValidateNotNullOrEmpty()] | |
[Alias('PSPath')] | |
[String[]] $LiteralPath, | |
[Switch] $RenameOutput, | |
[Switch] $Overwrite, | |
[Switch] $PlaceInSubfolder, | |
[String] $SubfolderName = 'Cropped', | |
[Int32] $MaxThreads = 16 | |
) | |
begin { | |
$List = [System.Collections.Generic.HashSet[string]]::new() | |
try { | |
$InkscapeCmd = Get-Command inkscape.com -ErrorAction Stop | |
} | |
catch { | |
throw "Fatal: Inkscape isn't available in PATH." | |
} | |
} | |
process { | |
foreach ($Path in $LiteralPath) { | |
if(Test-Path -LiteralPath $Path -PathType Leaf){ | |
if([System.IO.Path]::GetExtension($Path) -eq '.svg'){ | |
$List.Add($Path) | Out-Null | |
} | |
else{ | |
Write-Error "Passed file is not an SVG. ($Path)" | |
continue | |
} | |
} | |
else { | |
Write-Error "Passed file doesn't exist on disk. ($Path)" | |
continue | |
} | |
} | |
} | |
end { | |
$List | ForEach-Object -Parallel { | |
$CurrentSVG = $_ | |
$RenameOutput = $Using:RenameOutput | |
$PlaceInSubfolder = $Using:PlaceInSubfolder | |
$SubfolderName = $Using:SubfolderName | |
$FinalOutput = $null | |
$Overwrite = $Using:Overwrite | |
$DestFilename = [System.IO.Path]::GetFileName($CurrentSVG) | |
$FileParent = [System.IO.Directory]::GetParent($CurrentSVG) | |
if($RenameOutput) { | |
$DestFilename += '_crop.svg' | |
} | |
$DestFile = $null | |
if($PlaceInSubfolder){ | |
$FileNewDir = [System.IO.Path]::Combine($FileParent, $SubfolderName) | |
if(-not(Test-Path -LiteralPath $FileNewDir -PathType Container)){ | |
New-Item -Path $FileNewDir -ItemType Directory -Force | Out-Null | |
} | |
$DestFile = Join-Path $FileNewDir -ChildPath $DestFilename | |
} else { | |
$DestFile = Join-Path $FileParent -ChildPath $DestFilename | |
} | |
$FinalOutput = $DestFile | |
if(-not($Overwrite)){ | |
$FinalOutput = Get-UniqueFileOrFolderNameIfDuplicate -Path $DestFile -IndexSeparator "_" | |
} | |
$Params = '-o', $FinalOutput, '-D', $CurrentSVG | |
& $Using:InkscapeCmd $Params | Out-Null | |
} -ThrottleLimit $MaxThreads | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment