PS script for uploading files to Sharepoint Online

Brass Contributor

Hello friends...

 

This process of uploading files from some local storage to Sharepoint Online seems to be the simplest to be carried out via Powershell Script... However, a command/routine in which the password is posted clearly, in plain text, is not " should be" permanent.

 

 

#Copia Arquivos para o Sharepoint Site
    $FILESP = (Get-ChildItem .\$EXECFOLDER\ -File | Sort-Object LastWriteTime -Descending| Select-Object -First 3).Name
    foreach ($FILESP in $FILESP) {
        Write-Host "Arquivo .......... " -NoNewline 
        Write-Host "" $FILESP  -foregroundcolor Yellow -NoNewline 
        Write-Host " foi carregado/enviado com êxito!!!"
    Write-Host ""

$WebUrl = "https://organizacao.sharepoint.com/sites/name-site"
        $LibraryName ="library"
        $SourceFile=".\$EXECFOLDER\$FILESP"

        $AdminName ="MY-USER@MY-DOMAIN"
        $AdminPassword = "my password"

        #$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminName,(ConvertTo-SecureString $AdminPassword -AsPlainText -Force))
        $Credential = new-object System.Management.Automation.PSCredential $AdminName, $AdminPassword



        $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
        $Context.Credentials = $Credentials

        $Library = $Context.Web.Lists.GetByTitle($LibraryName)
        $FileStream = ([System.IO.FileInfo] (Get-Item $SourceFile)).OpenRead()
        $SourceFileName = Split-path $SourceFile -leaf

        $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
        $FileCreationInfo.Overwrite = $true
        $FileCreationInfo.ContentStream = $FileStream
        $FileCreationInfo.URL = $SourceFileName
        $FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)

        $Context.Load($FileUploaded)
        $Context.ExecuteQuery()

        $FileStream.Close()

    #Write-Host ""
    }

 

 

Do you have any alternative to this?

 

Contextualizing: A routine/script executes locally, generates some files that must be placed on a website, in a library, on Sharepoint Online

 

Well, I believe this can shed some light

1 Reply
Use the PnP PowerShell module. Instead of hard-coding the password in script, it can connect interactively where you provide the username/password when the script is running.

https://pnp.github.io/powershell/articles/connecting.html

Also, it has methods for interacting with Sites, Libraries, Lists, etc. so you'll be able to upload files with the same module.