Skip to content

Instantly share code, notes, and snippets.

@tahir-hassan
Created October 1, 2019 10:27
Show Gist options
  • Save tahir-hassan/3ae77593656105b9811378e0e7508335 to your computer and use it in GitHub Desktop.
Save tahir-hassan/3ae77593656105b9811378e0e7508335 to your computer and use it in GitHub Desktop.
PowerShell function `Invoke-XslTransform` for invoking an XSLT
# source: https://paregov.net/blog/19-powershell/24-xslt-processor-with-powershell
function Invoke-XslTransform {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$StylesheetUri
, [Parameter(Mandatory = $true)][string]$InputUri
, [string]$Destination
, [switch]$PassThru
, [switch]$Overwrite
)
$ErrorActionPreference = 'Stop';
if (-not (Test-Path $StylesheetUri)) {
throw "$StylesheetUri does not exist";
}
elseif (-not (Test-Path $InputUri)) {
throw "$InputUri does not exist";
}
$resolvePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath;
$xsl = [System.Xml.Xsl.XslCompiledTransform]::new();
$xsl.Load($resolvePath.Invoke($StylesheetUri));
$passThruOnly = ($PassThru -and (-not ($PSBoundParameters.ContainsKey("Destination"))));
if ($passThruOnly) {
$sb = [System.Text.StringBuilder]::new();
$xmlSettings = [System.Xml.XmlWriterSettings]::new();
$xmlSettings.Indent = $true;
$xmlWriter = [System.Xml.XmlWriter]::Create($sb, $xmlSettings);
$xsl.Transform($InputUri, $xmlWriter);
$xmlWriter.Dispose();
$sb.ToString();
}
else {
$resultsPath = & {
$destinationObj = Get-Item $Destination -ErrorAction SilentlyContinue;
if ($null -ne $destinationObj) {
if ($destinationObj -is [System.IO.FileInfo]) {
if ($Overwrite) {
Remove-Item $Destination;
}
else {
throw "$Destination already exists";
}
}
elseif ($destinationObj -is [System.IO.DirectoryInfo]) {
$stylesheetUriName = (Get-Item $StylesheetUri).BaseName;
$inputUriName = (Get-Item $InputUri).BaseName;
Join-Path $Destination "${inputUriName}${stylesheetUriName}$([DateTime]::Now.ToString("yyyyMMdd-HH-mm-ss")).xml";
}
}
else {
$Destination;
}
}
Write-Verbose "Writing to $($resolvePath.Invoke($resultsPath))";
$xsl.Transform($resolvePath.Invoke($InputUri), $resolvePath.Invoke($resultsPath));
if ($PassThru) {
Get-Content $resultsPath;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment