0
votes

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
And your problem is...?Mathias R. Jessen
Have you tried using a UNC file path instead of a web address? For example: \\sharepoint.url.com\site\your-site-name...Thriggle

1 Answers

0
votes

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.

enter image description here