如何在Microsoft Graph PowerShell输出中同时获取UPN与MFA电话号码
解决方案
你只需要在Select语句中通过计算属性将当前用户的UserPrincipalName合并到输出结果里即可,修改后的完整脚本如下:
Install-Module Microsoft.Graph.Identity.Signins Connect-Graph -Scopes UserAuthenticationMethod.ReadWrite.All Select-MgProfile -Name v1.0 $mgUsers = Get-MgUser -All:$true | Select UserPrincipalName foreach ($user in $mgUsers) { Get-MgUserAuthenticationPhoneMethod -UserId $user.UserPrincipalName | Select ID, PhoneNumber, PhoneType, @{Name='UserPrincipalName'; Expression={$user.UserPrincipalName}} }
关键修改说明
- 新增的
@{Name='UserPrincipalName'; Expression={$user.UserPrincipalName}}是PowerShell的计算属性语法:Name指定输出的列名,这里就是UserPrincipalNameExpression定义该列的值来源,直接引用当前循环中$user对象的UserPrincipalName属性
可选优化:包含无MFA电话的用户
如果需要输出所有用户(包括未配置MFA电话的用户),可以添加错误处理并手动构造空结果:
Install-Module Microsoft.Graph.Identity.Signins Connect-Graph -Scopes UserAuthenticationMethod.ReadWrite.All Select-MgProfile -Name v1.0 $mgUsers = Get-MgUser -All:$true | Select UserPrincipalName foreach ($user in $mgUsers) { $phoneMethods = Get-MgUserAuthenticationPhoneMethod -UserId $user.UserPrincipalName -ErrorAction SilentlyContinue if ($phoneMethods) { $phoneMethods | Select ID, PhoneNumber, PhoneType, @{Name='UserPrincipalName'; Expression={$user.UserPrincipalName}} } else { [PSCustomObject]@{ UserPrincipalName = $user.UserPrincipalName ID = $null PhoneNumber = $null PhoneType = $null } } }
内容的提问来源于stack exchange,提问作者mannyfresh86
相关产品推荐
相关产品推荐

