Download latest file from SharePoint Document Library

。_饼干妹妹 提交于 2019-12-23 05:35:06

问题


Caveat: Cannot use Microsoft.SharePoint.Powershell Snap-in.

I want create a PowerShell script that will search a SharePoint document library for the most recent file.

https://sharepoint.url.com/site/Your_Site_Name/Sub_Site/SharedDocuments/

I am trying to incorporate the Get-ChildItem to search for the latest file.

Here is an example:

$fromfile = "https://sharepoint.url.com/site/Your_Site_Name/Sub_Site/SharedDocuments/File_name*"
$tofile   = "c:\temp\temp_file.xlsx"

$latest = Get-ChildItem -Path $fromfile | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name

$webclient = New-Object System.Net.WebClient

$webclient.UseDefaultCredentials = $true

$webclient.DownloadFile($latest.name, $tofile)

My problem is that when I run this script, I get the following error:

Get-ChildItem : Cannot find drive. A drive with the name 'https' does not exist.
At line:4 char:11
+ $latest = Get-ChildItem -Path $fromfile | Sort-Object LastAccessTime

I am unable to use the UNC path on the server (Win 2012) I am using. I get "add site to 'trusted site' and try again, when I try to utilize 'Open with Explorer'.


回答1:


I've had a similar requirement as you, but I started with mapping the SharePoint UNC path first. The problem was that it doesn't always find it instantly, so a couple of retries might be needed:

$SharePoint  = '\\xxx.domain.net\site\Documents'
$LocalDrive  = 'S:'
$Credentials = Get-Credential


if (!(Test-Path $LocalDrive -PathType Container)) {
    $retrycount = 0; $completed = $false
    while (-not $completed) {
        Try {
            if (!(Test-Path $LocalDrive -PathType Container)) {
                (New-Object -ComObject WScript.Network).MapNetworkDrive($LocalDrive,$SharePoint,$false,$($Credentials.username),$($Credentials.GetNetworkCredential().password))
            }
            $Completed = $true
        }
        Catch {
            if ($retrycount -ge '5') {
                Write-Verbose "Mapping SharePoint drive failed the maximum number of times"
                throw "SharePoint drive mapping failed for '$($SharePoint)': $($Global:Error[0].Exception.Message)"
            } else {
                Write-Verbose "Mapping SharePoint drive failed, retrying in 5 seconds."
                Start-Sleep '5'
                $retrycount++
            }
        }
    }
}

Once the SharePoint Document Library is mapped, you can use all the CmdLets you need to filter out the files you're looking for (Get-ChildItem S:\, ...).

How can you find the UNC path?

By opening your site in the browser, going to View all site content, clicking Documents and select Actions and Open with Windows Explorer. The link in the address bar is the link you need.



来源:https://stackoverflow.com/questions/33791155/download-latest-file-from-sharepoint-document-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!