1

We are trying to upload a daily generated file to SharePoint portal using PowerShell. The script has to be in such a way that it should run daily at a scheduled time

i.e using Task scheduler. The task scheduler should also be automated using PowerShell. After the file has been uploaded it should circulate a mail accordingly.

Can anyone suggest some ideas or some sample scripts so that we can proceed further?

  • The given PnP-PowerShell answer seems valid, but it's also completely possible to do this with regular PowerShell script ran by Task Scheduler's trigger. You are likely looking for a script which copies your daily generated file to path x. You can also implement e.g. size comparison, date created comparison or such to find out whether there is a new file to be added. These however are pure PowerShell, and should be discussed within StackOverflow instead. – moe Jul 20 '17 at 8:48
3

For this, I would download and install PnP-Powershell

For credentials, on the machine you want to run the script on, open Windows Credential Manager and create a Generic Credential with the credentials you want to use. Give this a name like SPO_Uploader

Create a .ps1 file with the following contents (update to suit your file names etc)

Connect-PnPOnline -Url "https://tenancy.sharepoint.com/sites/sitename" -Credentials SPO_Uploader

$filepath = "C:\temp\filetobeuploaded.txt"
$destinationfolder = "LibraryName"

Add-PnPFile -Path $filepath -Folder $destinationfolder

Disconnect-PnPOnline

Now, you can create a scheduled task on the machine to launch PowerShell with this file as an argument, run this with an account that has access to the file that you want to upload.

Note if the filename does not change, the file will be overwritten on SharePoint each time you run this.

Edit:

If you want to upload a new file each time, rather than overwriting the existing one, ensure that your files have different names, and put them into a folder as they get generated. Make your script like this instead:

Connect-PnPOnline -Url "https://tenancy.sharepoint.com/sites/sitename" -Credentials SPO_Uploader

$destinationfolder = "LibraryName"

$files = Get-ChildItem c:\temp\uploadlocation

foreach ($file in $files){
    Add-PnPFile -Path $file -Folder $destinationfolder
    Move-Item -Path $file -Destination c:\temp\uploadlocation\processed -Force
}

Disconnect-PnPOnline

This will get all files within your upload folder, and upload them to the site in turn. Useful if you generate files every day, but your scheduled task fails for whatever reason. Note if the file name is the same as an existing one in SharePoint, it will still get overwritten. Files will be moved to the processed folder as they are copied up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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