Wednesday, January 27, 2016

How To: Filter an XML file using Powershell

Once again I've been using Powershell to work around a problem. A few thousand users have been serialised into an XML file that needs to be imported into an external system. The problem is that there are many users that need to be removed from this file and the system that generated the file in the first place isn't able to filter them out before doing the export, don't ask.

Fortunately Powershell makes this laborious task fairly straight forward. Using just a few lines of code, I've loaded in the export file along with a file of users that should be removed; then filter through the user objects in the XML and write the results out to a new file.

$usernames = Get-Content excludedUsers.txt
[xml]$xmlFile = Get-Content ".\users-export.xml"
$xmlFile.Application.Users.User | where-object {$usernames -notcontains $_.username} | % {$_.ParentNode.RemoveChild($_)}
$xmlFile.OuterXml | Out-File .\users-export-filtered.xml

No comments: