PowerShell – Script to copy document, check out, overwrite, check in and publish

In PowerShell, SharePoint 2013 by rhodzyLeave a Comment

I recently had a request to that I hadn’t had before. 


  • Copy file from one location daily to overwrite an existing document
  • File has to be the only that that gets checked in
  • File is in some subfolders
  • Check out and approve needs to be left turned on
  • Versioning needs to be left on
  • It needs to run at 6:30pm daily.

Fairly simple, except the library had versioning on, required documents to be check out and to be published and approved. Now the document was part of an automation piece so it was correct and didn’t need checking. 


if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
        Add-PSSnapin Microsoft.SharePoint.PowerShell

    #Script settings


    $docLibraryName = "DOCUMENT LIBRARY NAME"
    $docLibraryUrlName = "DOCUMENT LIBRARY NAME\SUBFOLDER"    # specify your subfolder url here

    $localFolderPath = "\\NETWORKSHARE\FOLDER\"
    #Checkout existing file
    $Site = Get-SPWeb $Site

    #Open web and library

    $web = Get-SPWeb $webUrl
    write-host $webUrl

    $docLibrary = $web.Lists[$docLibraryName]
    write-host $docLibrary

    $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()

    write-host $files

    ForEach($file in $files)

    write-host $file

        #Open file
        $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

        #Add file
        $folder =  $web.getfolder($docLibraryUrlName)

        write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
        $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name,[System.IO.Stream]$fileStream, $true)
        write-host "Success"

        #Close file stream
        Write "Error: $file.name: $_" >>E:\LOCATIONFORLOGFILE\IMPORTlogfile.txt

     #Checkin and publish
     $pages | ForEach-Object {
     $item = $web.GetListItem($_)
    if ($item.File.CheckOutType -ne "None")
        $item.File.CheckIn("Automatically checked in by PowerShell", "MajorCheckIn");
    if ($item.Versions[0].Level -ne "Published")
        $item.File.Publish("Automatically published by PowerShell");
    if ($item.ModerationInformation.Status -ne "Approved")
        $item.File.Approve("Automatically approved by PowerShell");

    #Dispose web