Reading the contents of a SharePoint library file using PowerShell


I recently needed to read the text from a file in a SharePoint library using PowerShell. The only real challenge was converting the return ByteArray into a string. This might be a rare requirement, but just in case someone else might need it.


$site   = Get-SPSite http://yourserver/sites/yoursite
$web    = $site.RootWeb
$list   = $web.Lists["Shared Documents"]
$item   = $list.Items[0]
$file   = $item.File
$data   = $file.OpenBinary()
$encode = New-Object System.Text.ASCIIEncoding

$test   = $encode.GetString($data)

Yes, it can be done in fewer steps… but for completeness…


For SharePoint 2007 replace the first line with these two:


$site = New-Object Microsoft.SharePoint.SPSite("http://yourserver/sites/yoursite")


Daniel Williams said...

This is nice - thank you.
Now, if we know the data is a pure text file, is there any way we can perform a find and replace within the stream and send it back?

Mike Smith said...



Just add these two lines:

$data2 = $encode.GetBytes($test.Replace("aaaa","bbbbb")



Mike Smith said...

And just for fun, here's a three line version that opens the first file, does the text replace and saves it back:

$encode = New-Object System.Text.ASCIIEncoding

$file = $site.RootWeb.Lists["Shared Documents 2"].Items[0].File

$file.SaveBinary( $encode.GetBytes( $encode.GetString( $file.OpenBinary() ).Replace("aaaaa","bbb")))


Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.