CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Struggling to Connect to Exchange Online Using MFA with Custom Scripts

šŸ‘€ Views: 117 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
PowerShell Exchange MFA Authentication

I've looked through the documentation and I'm still confused about I'm having trouble connecting to Exchange Online via PowerShell 7.3 using Multi-Factor Authentication (MFA) in a custom script. I have followed several guides and tried using the `Connect-ExchangeOnline` cmdlet, but I keep working with the behavior `"The remote server returned an behavior: (401) Unauthorized."`. Here's the code snippet I've been using: ```powershell $UserCredential = Get-Credential Connect-ExchangeOnline -Credential $UserCredential -ShowProgress $true ``` When I run this, I'm prompted for my username and password, but it doesn't seem to handle the MFA scenario correctly, and I never get to the authentication screen for MFA. I've tried enabling `-UserPrincipalName`, but it doesn't seem to change anything. After some digging, I found that `Connect-ExchangeOnline` has a `-UseWebLogin` switch, so I tried the following: ```powershell Connect-ExchangeOnline -UserPrincipalName myemail@domain.com -UseWebLogin ``` This opens a new browser window, but after logging in, I get redirected back to the terminal, and the connection still fails. I also checked the required modules and made sure I have the `ExchangeOnlineManagement` module installed and updated to the latest version. My current version is 2.0.5. Could the scenario be related to my account settings, or is there something I’m missing in my script? Any help would be appreciated! My development environment is Windows. Any help would be greatly appreciated!