Move SharePoint file by url

0

Move a SharePoint file from one library to another using the url to the file.

function Move-SPFileByUrl {

    param(
        [PARAMETER(Mandatory=1)][System.String]$url,
        [PARAMETER(Mandatory=1)][System.String]$targetUrl
    )

    try {
        
        # Load SharePoint PowerShell snapin
        Add-PSSnapIn Microsoft.SharePoint.PowerShell        
        
        # Get SPSite 
        [Microsoft.SharePoint.SPSite]$SPSite = New-Object -Type Microsoft.SharePoint.SPSite -ArgumentList $url

        # Get SPWeb
        [Microsoft.SharePoint.SPWeb]$SPWeb = $SPSite.OpenWeb()

        # Get SPFile
        $SPFile = $SPWeb.GetFile($url)

        # Check if file exists
        if ( $SPFile.Exists -ne $false ) {
            # Move file
            $SPFile.MoveTo($targetUrl)
            return [System.String]( "[SUCCESS] File '"+$url+"' moved successfully" )
        }
        else
        {
            return [System.String]( "[WARNING] File '"+$url+"' not found" )
        }

    }
    catch
    {
        return [System.String]( "[ERROR]   Moving '" + $url + "' " + $_ )
    }
}

$csv = "c:\input.csv"
$fileUrls = Import-Csv -Delimiter ";" -LiteralPath $csv

ForEach ( $fileUrl in $fileUrls ) {
    
    Move-SPFileByUrl -url $fileUrl.'SourceLink' -targetUrl $fileUrl.'DestinationLink'

}

Input.csv format:

SourceLink;DestinationLink
https://sharepoint/folder1/abc.pdf;https://sharepoint/folder2/abc.pdf
https://sharepoint/folder1/def.docx;https://sharepoint/folder3/def.docx
Share.

About Author

Christian Unnerstall

Christian Unnerstall, founder of devshooin.com, enjoys designing and building things that look nice and work well, whether it's websites or services within the interwebs. Have questions - feel free to reach out to him. Enjoy

Leave a Reply