I recently had a request for a PowerShell script that could be run as a Windows scheduled task to download a file each night to a network share. As is typical, there's more than one way…
The PowerShell / .Net approach:
This is a ".Net approach" as it does not use any PowerShell cmdlets (beyond New-Object). The following will work from all versions of PowerShell and SharePoint 2007 – 2013, but not Office 365. It will work from any client PC as long as you have permissions to access the file. Why not Office 365? O365 requires an authentication cookie. (When I get some time I'll post an O365 version.)
$fromfile = "http://yourserver/sites/yoursite/shared%20documents/yourfile.xlsx" $tofile = "c:\somedirectory\yourfile.xlsx" $webclient = New-Object System.Net.WebClient $webclient.UseDefaultCredentials = $true # or # $webclient.Credentials = …
The SharePoint Approach:
This approach must be run from a SharePoint server and uses the Get-SPWeb cmdlet to access a site. As it is much more complicated, why would you ever use it? To do more complex things! Things like getting all of the files from a library and then downloading them (in a foreach loop), ZIPing the file(s) before download or otherwise manipulating the files before download.
The following will work from the SharePoint 2010 and 2013 Management Shells (but not for Office 365). Why not Office 365? The following needs to be run on the SharePoint server, and you are not allowed to do that with O365.
$fromsite = "http://yourserver/sites/yoursite" $fromfile = "yourlibrary/yourfile.xlsx" $tofile = "c:\test\yourfile.xlsx" $web = Get-SPWeb $fromsite $file = $web.GetFile($fromfile) $filebytes = $file.OpenBinary() $filestream = New-Object System.IO.FileStream($tofile, "Create") $binarywriter = New-Object System.IO.BinaryWriter($filestream) $binarywriter.write($filebytes) $binarywriter.Close()