This month’s T-SQL Tuesday is being hosted by Pat Wright (blog | twitter). He selected the topic of automation with T-SQL or PowerShell. As it happened, I’d just had a scenario come up that seemed appropriate for a little PowerShell, so I went with it for this post.
The Varigence toolset is based on a language called BIML (Business Intelligence Markup Language), which is an XML-based language for creating BI solutions. We needed to make some mass updates to some of our sample files, but there were quite a few individual ones to update. I already had an XSLT transform that would update each file individually, so all I needed was a quick way to run it on each file in a directory.
I’m pretty new to PowerShell, but it seemed like a good fit for this. So, after a little trial and error, I came up with the following script:
[sourcecode language="powershell" padlinenumbers="true"] $path = "C:tempxml*.xml" get-childItem $path | rename-item -newname { $_.name -replace '.xml','_backup.xml' } $files = Get-ChildItem $path $xslt = New-Object System.Xml.Xsl.XslCompiledTransform $xslt.Load("C:tempxmlDataType.xslt") foreach ($file in $files) { $oldFileName = $file.FullName $newFileName = $file.FullName -replace '_backup.xml', '.xml' $xslt.Transform($oldFileName, $newFileName) } [/sourcecode]
Basically, it goes through a directory, renames all the existing .XML files to create a backup, and then gets a list of the files. It then loads an XSLT transformation (used to transform XML documents by inserting or removing markup). Finally, it loops through the files in the folder, and uses the XSLT transform to create an updated version of the file with the original filename.
There are probably better ways to do this, but it does exactly what I needed, and it let me learn a little more about PowerShell. It also struck me that this could be very useful to transform XML into a friendlier shape for processing in SSIS.