Last active
April 26, 2017 07:02
-
-
Save eerohele/92308f7b3b4ddfe9b39a6588351dded6 to your computer and use it in GitHub Desktop.
Run an XSLT transformation on a glob of files with PowerShell and XslCompiledTransform
This file contains hidden or 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
Param( | |
[Parameter(Mandatory = $True)] [string] $Path, | |
[Parameter(Mandatory = $True)] [string] $Xsl, | |
[Parameter(Mandatory = $False)] [string] $Filter = "*.xml", | |
[Parameter(Mandatory = $False)] [string] $Target = (Join-Path (Convert-Path .) "target"), | |
[Parameter(Mandatory = $False)] [hashtable] $Params | |
) | |
Set-StrictMode -version 2.0 | |
Function Get-Transformer([System.IO.FileInfo] $stylesheet) | |
{ | |
$transformer = New-Object System.Xml.Xsl.XslCompiledTransform | |
$settings = New-Object System.Xml.Xsl.XsltSettings($True, $True) | |
$resolver = New-Object System.Xml.XmlUrlResolver | |
Try { | |
$transformer.Load($stylesheet, $settings, $resolver) | |
} | |
Catch { | |
Throw $_.Exception.Message | |
} | |
return $transformer | |
} | |
Function Main([string] $path, [string] $stylesheet, [string] $filter, [string] $outputDir, [hashtable] $params) | |
{ | |
New-Item -ItemType Directory -Force -Path $outputDir | Out-Null | |
$argList = New-Object System.Xml.Xsl.XsltArgumentList | |
ForEach ($key in $params.Keys) | |
{ | |
$value = $params[$key] | |
$argList.AddParam($key, $null, $value) | |
} | |
$stylesheet = [string] (Resolve-Path $stylesheet) | |
$transformer = Get-Transformer ([System.IO.FileInfo] $stylesheet) | |
Get-ChildItem -Path $path -Filter $filter | ForEach-Object { | |
$source = ([System.IO.FileInfo] $_.FullName) | |
$output = New-Object IO.FileStream (Join-Path (Resolve-Path $outputDir) $_.Name), ([System.IO.FileMode]::Create) | |
Try | |
{ | |
$transformer.Transform($source, $argList, $output) | |
} | |
Finally | |
{ | |
$output.Dispose() | |
} | |
} | |
} | |
Main $Path $Xsl $Filter $Target $Params |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment