1

The problem statment is at particular time user has to replace the file with older file (E.g File contains updated information). Here everday user has to be very alert since file needs to be shared on sharepoint and this is manual task. File format is excel.

Can we replace the file on particular time without invoking to sharepoint so program would pickup the file from desktop and replace the file on sharepoint folder. Thought of creating it from outlook vba but if you have other easier solutions please let me know. Thank you, Mangesh

2
  • You need to provide more information. Your post reads like you are halfway through introducing a topic, but you left out the first half.
    – teylyn
    Apr 6, 2020 at 21:08
  • Thanks terylyn, edited my post. Apr 6, 2020 at 21:37

2 Answers 2

0

Yes, this is possible. Create a PowerShell script and configure that script in Windows task scheduler which should run in the specific time where we have the flexibility to in which time and how frequently we have to execute.

If your file is available in SharePoint Server you can write the PowerShell script using the server-side object model or if your files are available in your local desktop you can write your PowerShell script using the client-side object model.

If you google around you will get plenty of ready-made scripts for file upload.

Below is the sample script which uploads files to SharePoint online library:

#Load SharePoint CSOM Assemblies
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
cls



$fileName = "File_Uploading_Report"
#'yyyyMMddhhmm   yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename =  $enddate + '_VMReport.doc'  
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path  

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))  
        {  
            New-Item -ItemType directory -Path $directoryPathForLog
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   


#$logPath = $directoryPath + "\" + $logFileName 

$logPath = $directoryPathForLog + "\" + $logFileName 

$isLogFileCreated = $False 



#DLL location

$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
        {  
            New-Item -ItemType directory -Path $directoryPathForDLL
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#DLL location

$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime


#Files to upload location

$directoryPathForFileToUploadLocation=$directoryPath+"\"+"Files To Upload"
if(!(Test-Path -path $directoryPathForFileToUploadLocation))  
        {  
            New-Item -ItemType directory -Path $directoryPathForFileToUploadLocation
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#Files to upload location ends here.



function Write-Log([string]$logMsg)  
{   
    if(!$isLogFileCreated){   
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
        {  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   
        else   
        {   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        }   
    }   
    else   
    {   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   
    }   
} 



#The below function will upload the file from local directory to SharePoint Online library.

Function FileUploadToSPOnlineLibrary()
{
    param
    (
        [Parameter(Mandatory=$true)] [string] $SPOSiteURL,
        [Parameter(Mandatory=$true)] [string] $SourceFilePath,
        [Parameter(Mandatory=$true)] [string] $File,
        [Parameter(Mandatory=$true)] [string] $TargetLibrary,
        [Parameter(Mandatory=$true)] [string] $UserName,
        [Parameter(Mandatory=$true)] [string] $Password
    )

    Try 
    {

        $securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force  
        #Setup the Context
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
        $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)

        $list = $ctx.Web.Lists.GetByTitle($TargetLibrary)
        $ctx.Load($list)
        $ctx.ExecuteQuery()     

        $tarGetFilePath=$siteURL+"/"+"$TargetLibrary"+"/"+$File

        $fileOpenStream = New-Object IO.FileStream($SourceFilePath, [System.IO.FileMode]::Open)  
        $fileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation  
        $fileCreationInfo.Overwrite = $true  
        $fileCreationInfo.ContentStream = $fileOpenStream  
        $fileCreationInfo.URL = $File  
        $uploadFileInfo = $list.RootFolder.Files.Add($FileCreationInfo)  
        $ctx.Load($uploadFileInfo)  
        $ctx.ExecuteQuery() 


        Write-host -f Green "File '$SourceFilePath' has been uploaded to '$tarGetFilePath' successfully!"
    }
    Catch 
    {

            $ErrorMessage = $_.Exception.Message +"in uploading File!: " +$tarGetFilePath
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 


    }
}

#Variables
$siteURL="https://globalsharepoint.sharepoint.com/sites/TestSite/"
$listName="TestDocumentLibrary"
$fromDate="2019-10-28"
$toDate="2019-11-09"
$filesFolderLoaction=$directoryPathForFileToUploadLocation;
$userName = "[email protected]"
$password = "YourPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force

#Variables ends here.


$filesCollectionInSourceDirectory=Get-ChildItem $filesFolderLoaction -File   

$uploadItemCount=1;

    #Extract the each file item from the folder.
    ForEach($oneFile in $filesCollectionInSourceDirectory)
    {            

            try
            {                            

                FileUploadToSPOnlineLibrary -SPOSiteURL $siteURL -SourceFilePath $oneFile.FullName -File $oneFile -TargetLibrary $listName -UserName $UserName -Password $Password

                $fileUploadingMessage=$uploadItemCount.ToString()+": "+$oneFile.Name; 
                Write-Host $fileUploadingMessage -BackgroundColor DarkGreen
                Write-Log $fileUploadingMessage

        $uploadItemCount++

        }
        catch
        { 
            $ErrorMessage = $_.Exception.Message +"in: " +$oneFile.Name
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 

        }

    }
    Write-Host "========================================================================"
    Write-Host "Total number of files uploaded: " $filesCollectionInSourceDirectory.Count 
    Write-Host "========================================================================"

Source article:

SharePoint Online Automation – O365 – Upload files to document library using PowerShell CSOM

2
  • I was trying to work around on powershell but getting below error { "status": 403, "message": "Access denied. You do not have permission to perform this action or access this resource.\r\nclientRequestId:...……………. "errors": [ "-2147024891", "System.UnauthorizedAccessException" ] } Whats the problem here, manually I can upload the document but getting error. Apr 7, 2020 at 13:32
  • This is awesome. I have tried this and it worked perfectly fine. Thank a ton. :) Apr 8, 2020 at 13:10
0

You could use flow/Automate or workflow to create daily work. This is very easy and doesn't need any custom codes.

Flow/Automate: Create a scheduled flow and repeat it everday. enter image description here

Workflow: Use loop and pause action to update the file everyday:

enter image description here

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.