Azure AD中PowerShell获取指定公司用户时Manager字段ID转字符串问题
问题:获取Azure AD用户经理信息时ID类型转换错误
我尝试运行以下PowerShell代码,获取Azure AD中公司名称为'Global Office'的账户信息:
get-mgbetauser -all -filter "CompanyName eq 'Global Office'" -ConsistencyLevel eventual -count test | select-object -Property DisplayName,Mail,JobTitle,Country,Id,@{Name='manager';Expression={(get-mgusermanager -userid $_.Id -property userprincipalname).userprincipalname}}
代码整体可正常运行,但获取Manager的Expression语句存在问题:ID是对象,需转换为字符串才能用于Get-MgUserManager命令。我曾尝试使用-userid $($_.Id | Out-String),但未能奏效,需在Expression语句范围内将$_.Id转换为字符串。
解决方案
问题出在Out-String会给转换后的字符串添加额外换行符,导致Get-MgUserManager无法识别正确的用户ID。直接使用类型转换或ToString()方法就能得到干净的字符串ID:
修正后的代码(方式一:类型转换)
Get-MgBetaUser -All -Filter "CompanyName eq 'Global Office'" -ConsistencyLevel eventual -Count test | Select-Object -Property DisplayName, Mail, JobTitle, Country, Id, @{ Name='manager'; Expression={(Get-MgUserManager -UserId [string]$_.Id -Property UserPrincipalName).UserPrincipalName} }
修正后的代码(方式二:ToString()方法)
Get-MgBetaUser -All -Filter "CompanyName eq 'Global Office'" -ConsistencyLevel eventual -Count test | Select-Object -Property DisplayName, Mail, JobTitle, Country, Id, @{ Name='manager'; Expression={(Get-MgUserManager -UserId $_.Id.ToString() -Property UserPrincipalName).UserPrincipalName} }
这两种方式都能将ID对象直接转换为不带多余字符的字符串,让Get-MgUserManager正确识别用户ID并返回经理信息。
内容的提问来源于stack exchange,提问作者Pete Mitchell
相关产品推荐
相关产品推荐

