Read and Search elements in any XML files with PowerShell

I am working on a automation where We have to read XML files to search for Site Admins of site collections.(these all are buried inside the XML files)

Good thing is that Powershell behaves with XML files same as we explore properties of the objects, We will go thru the live & practical example to understand how to browse thru XML files with ease.

In the below example we have a XML file and it has details of all administrators of site collections across the SharePoint farm, We will read it via powershell and find Admins for particular site collection.

Load the XML file using get-content but prepend [XML] to the variable.

[xml]$XmlDocumentMyteam = Get-Content -Path .\Temp\Myteam-SPAdministratorsReport.xml #read XML file
Now as XML has been loaded you can start using it in a powershell way 🙂
$XmlDocumentMyteam
$XmlDocumentMyteam.AdministratorsReport   (same as you browse properties in Powershell)
$XmlDocumentMyteam.AdministratorsReport.Farm.WebApplications.WebApplication
Follow this approach till you reach a level where the data you are looking (or you can also open the XML in any XML editor to have a idea on where you need to search the data)
XML Editor (use Expand/collapse to look for the levels) – I generally use Notepad++
Now you can use where clause to filter out the webapp you are intrested in.
$webapp = $XmlDocumentMyteam.AdministratorsReport.Farm.WebApplications.WebApplication | where{$_.url -like “http://SharePoint/“}
You can use the same technique now and find all site collections under http://SharePoint/ and than browse thru the site administrators as shown below.
$webapp.SiteCollections.SiteCollection
$admins = $webapp.SiteCollections.SiteCollection | where{$_.url -like “http://Sharepoint“}
$admins.SiteCollectionAdministrators.SiteCollectionAdministrator
You can use this simple approach and play with XML files and do lot of automatons.
Thanks for reading
Sukhija Vikas
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s