0
votes

Task: I need to loop thru all files on Sharepoint site and download them to local folder.

Script:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$s = Get-SPSite “https://abc.abctools.consumer.abc.net/sites/rtc/report/SitePages/Forms/AllPages.aspx”
$files = $s.RootWeb.GetFolder("Shared Documents").Files
foreach ($file in $files) {
    Write-host $file.Name
    $b = $file.OpenBinary()
    $fs = New-Object System.IO.FileStream(("C:\SP Document Library files\"+$file.Name), [System.IO.FileMode]::Create)
    $bw = New-Object System.IO.BinaryWriter($fs)
    $bw.Write($b)
    $bw.Close()
}

Errors: I get when i try to run/execute above script. 1. "You cannot call a method on a null-valued expression."

  1. New-Object: Exception calling ".ctor" with "2" agrument(s): "Could not find a part of the path 'C:\SP Document Library files\'

  2. New-Object: Constructor not found. Cannot find an appropriate constructor for the type system.IO.BinaryWrite.

  3. The term 'Get-SPSite' is not recognized as a cmdlet, function, operable program or script file. verify the term and try again.

Response on Error #2: I have created the folder & named "SP Document Library files" so that path is correct C:\SP Document Library files not sure why i see that msg.

Library files (.csv,.xls) exists in a folder. Folder name : 2014-01-31. 1. What to do to in order resolve above error message(s). 2. I'm not sure if i need to use whole sharepoint url or part of it.Educate me on that.

Thanks!!

1
Make sure, that your scirpt is being run on x64 version of powershell.Marek Kembrowski

1 Answers

0
votes

Try by giving ReadWrite FileAccess.

And you can get the root web directly if you know the Url instead of using SPSite.

Here's my script I use and has always worked

$siteUrl = '“https://abc.abctools.consumer.abc.net/sites/rtc”'
$listUrl = '“https://abc.abctools.consumer.abc.net/sites/rtc/Shared Documents”'
$folderPath = 'C:\\....'

$web = Get-SPWeb -Identity $siteUrl
$list = $web.GetList($listUrl)
$items = $list.Items
ForEach ($item in $items)
{
    $binary = $item.File.OpenBinary();
    $folderPathToSave = $folderPath + "\\" + $item.Name;
    if ($binary -ne $null)
    {
        $stream = New-Object System.IO.FileStream($folderPathToSave,[System.IO.FileMode]::Create,[System.IO.FileAccess]::ReadWrite);
        $writer = New-Object System.IO.BinaryWriter($stream);
        $writer.Write($binary);
        $writer.Close();
    }
}

$web.Dispose()

The original post: http://naimmurati.wordpress.com/2012/06/07/backup-documents-from-document-library-with-powershell-script/