通过C#执行PowerShell时遇Outlook.Office365.com访问被拒错误
程序已稳定运行4年,自2022年8月4日起,仅在通过PSSession/PSCommands连接Exchange Online时出现访问被拒错误,其他如Connect-ExchangeOnline、Connect-AzureAD、Connect-MSOLService命令可正常执行:
- 代码在
runspace.Open()环节执行失败 - 直接运行PowerShell命令也触发相同报错:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Authentication Basic -AllowRedirection -Credential Get-Credential
错误提示:
New-PSSession : [outlook.office365.com] 连接远程服务器outlook.office365.com失败,错误信息:访问被拒。详情请查看about_Remote_Troubleshooting帮助主题
已排查账号密码有效性、更换多个测试用户,问题仍存在。
检查Basic认证状态
Microsoft 365逐步淘汰Basic认证,若租户已禁用Exchange Online的Basic认证,使用-Authentication Basic参数的New-PSSession会被拒绝。可通过以下命令检查(需先通过Connect-ExchangeOnline连接):Get-AuthenticationPolicy | fl Name,AllowBasicAuth*若
AllowBasicAuthPowerShell为False,需调整认证策略,或切换至现代认证方式。改用现代认证连接PSSession
替换原命令为支持现代认证的格式,或直接使用Connect-ExchangeOnline(已确认该命令可用):# 安装/更新ExchangeOnlineManagement模块 Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber # 用现代认证创建会话 $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Authentication Negotiate -AllowRedirection -Credential (Get-Credential)确认用户PowerShell访问权限
检查目标用户是否被启用Exchange Online PowerShell访问:Get-User -Identity "用户名" | fl RemotePowerShellEnabled若
RemotePowerShellEnabled为False,执行以下命令启用:Set-User -Identity "用户名" -RemotePowerShellEnabled $True检查租户IP限制与条件访问
排查Azure AD条件访问策略,确认是否存在针对Exchange Online PowerShell的IP阻止规则,或当前客户端IP是否在租户的受信任IP列表外。更新依赖环境
升级PowerShell至7.x版本,更新.NET框架到最新稳定版,同时确保ExchangeOnlineManagement模块为最新版本,避免兼容性问题。
内容的提问来源于stack exchange,提问作者Robert Shannon

