title: Upload file to Sharepoint Online (Microsoft 365) using Powershell (Option 4 - Using Microsoft.SharePoint.Client.ClientContext)
body: <p>I'm trying to upload a file into a Sharepoint Online (M365) library, but it keeps giving me errors. I have tried many scripts. This post is about using Microsoft.SharePoint.Client.ClientContext (I have posted questions about other scripts hoping someone can help me with any of them)</p>
  <p>This is the code:</p>
  <pre><code>$WebUrl = &quot;https://myDomain.sharepoint.com/sites/mySite/&quot;
  $LibraryName =&quot;myLibrary&quot;
  $SourceFile=&quot;C:\myFolder\myFile.csv&quot;
  $AdminName =&quot;mail@myDomain.com&quot;
  $AdminPassword =&quot;myPassword&quot;
    
  $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminName,(ConvertTo-SecureString $AdminPassword -AsPlainText -Force))
    
  $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()
  #Get File Name from source file path
  $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()
  </code></pre>
  <p>Just from the beggining, I have this error:</p>
  <p><em>New-Object : Cannot find type [Microsoft.SharePoint.Client.SharePointOnlineCredentials]: make sure the assembly containing this type is loaded.</em></p>
  <p>I suppose I must load them. I have seen this code:</p>
  <pre><code>#Load SharePoint CSOM Assemblies
  Add-Type -Path &quot;C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll&quot;
  Add-Type -Path &quot;C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll&quot;
  </code></pre>
  <p>But I don't have installed such libraries</p>
  <p>Curiously, if I, previously, execute this command (just execute, and cancel prompt asking for URL afterwards):</p>
  <pre><code>Connect-PnPOnline
  </code></pre>
  <p>Then, somehow, the references are loaded, because the script then works flawlesly.</p>
  <p>Could you tell me how to load those libraries?</p>