How can use use Microsoft.SharePoint.Client with an account that needs MFA

John Sparks 111 Reputation points
2023-02-23T17:21:23.5466667+00:00

Hi, I have a Powershell script that connects to a SharePoint Site to upload files. Works fine without MFA but fails when connecting to a site that requires MFA.

I use the code below as per https://www.sharepointdiary.com/2016/06/upload-files-to-sharepoint-online-using-powershell.html However, Get-Credential isnt MFA aware. I cant get a app Password, but if there is an interactive method that would be OK.

I tried some code from here: https://morgantechspace.com/2021/09/connect-to-sharepbut couldnt get it to work.

$Cred = Get-Credential    
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName, $Cred.Password)  
...Do the work...
$Ctx.ExecuteQuery() 

diary.com/2016/06/upload-files-to-sharepoint-online-using-powershell.html

However, Get-Credential isnt MFA aware.  I cant get a app Password, but using an interactive method would be OK.

I tried some code from here
https://morgantechspace.com/2021/09/connect-to-sharep

Microsoft 365 and Office SharePoint Development
Microsoft 365 and Office SharePoint For business Windows
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Emily Du-MSFT 51,836 Reputation points Microsoft External Staff
    2023-02-24T08:52:46.8566667+00:00

    Please try below PowerShell.

    $SiteUrl = "https://tenant.sharepoint.com\sites\test"  
    $SourceFilePath ="C:\test.docx"
    $DestinationPath = "Shared Documents" #Site Relative Path of the Library
    Try {  
         #Connect to PNP Online  
         Connect-PnPOnline -Url $SiteUrl -Interactive   
         #powershell pnp to upload file to sharepoint online 
         Add-PnPFile -Path $SourceFilePath -Folder $DestinationPath  
     }  
     catch {  
         write-host "Error: $($_.Exception.Message)" -foregroundcolor Red  
     }
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.