I recently had a need to read data from an xml configuration file that was stored within a SharePoint library. To make things easier I of course went to Google (or Bing) and checked to see if someone else had yet blogged this. Couldn’t find anything, so in order to help out someone else that may need to do the same at some point, I wrote up a quick little blog. Note: this will only work for on-premises versions of SharePoint. I’ll update with a SharePoint Online version in the future. I’ll also write up how to add and delete contents in a future post as well.
Read XML Data Files Stored in a SharePoint Library with PowerShell
Basically the steps are as follows:
- Get the SPWeb object of the site where the file is contained
- Get the file using the URL
- Open the file
- Apply ASCII Encoding to the open file
- Cast the file object as xml
- Profit…
Here’s the code to accomplish what you need:
$spWebURL = <URL of Web site> $spFileURL = <URL of file> try { $spWeb = Get-SPWeb $spWebURL; $spFile = $spWeb.GetFile($fileURL); } catch { $ErrorMessage = $_.Exception.Message; Write-Host ("{0}: An error accessing the file at: {1}. Error received: {2}" -f ` (get-date).ToString("yyyy-MM-dd HH:mm:ss"), $fileURL, $ErrorMessage) -ForegroundColor Red } if($spFile) { $configFile = $spFile.OpenBinary(); $encodeObj = New-Object System.Text.ASCIIEncoding; $xmlConfigFile = [xml]($encodeObj.GetString($configFile)); } else { write-host("The file at {0} returned null when opened" -f spFileURL ) -ForegroundColor Yellow }
Once you have completed the above you now have an xml object you can use for what ever you need.
Thanks for reading!!
Comments