You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell高效输出含子对象的Get-MsolUser查询结果?

PowerShell 单行管道实现嵌套对象列表输出

需求场景

PowerShell命令返回的对象包含命名字段及值,其中部分值为带有下级结构的子对象。需要以列表形式输出结果,且包含子对象的值。

现有实现代码(通过foreach循环):

foreach ($user in (Get-MsolUser | ?{$_.StrongAuthenticationmethods -ne $null})){
Write-host "$($user.UserPrincipalName) :: $($user.DisplayName)"
foreach($method in $user.StrongAuthenticationMethods){
write-host "`t$($method.MethodType)"
}}

尝试的非功能性代码(无法实现需求):

Get-msolUser|?{$_.StrongAuthenticationmethods -ne $null} | select UserPrincipalName,Displayname,isLicensed,(StrongAuthenticationmethods | fl)

解决方案

方法1:用ForEach-Object替代foreach循环(单行管道实现控制台输出)

Get-MsolUser | Where-Object { $_.StrongAuthenticationMethods -ne $null } | ForEach-Object { "$($_.UserPrincipalName) :: $($_.DisplayName)"; $_.StrongAuthenticationMethods | ForEach-Object { "`t$($_.MethodType)" } }
  • 直接在管道中处理每个用户对象,先输出用户主体名和显示名,再遍历子对象输出缩进的认证方法类型
  • 替换Write-Host为直接输出字符串,输出内容可被捕获或重定向(Write-Host仅输出到控制台,无法后续处理)

方法2:用计算属性展开子对象,结合Format-List格式化输出

如果需要保留对象结构同时展开子属性,可使用Select-Object的计算属性:

Get-MsolUser | Where-Object { $_.StrongAuthenticationMethods -ne $null } | Select-Object UserPrincipalName, DisplayName, IsLicensed, @{Name='StrongAuthenticationMethods'; Expression={ $_.StrongAuthenticationMethods.MethodType -join "`n`t" }} | Format-List
  • 通过哈希表定义计算属性,将子对象的MethodType提取并拼接成带缩进的字符串
  • 用Format-List输出,每个属性单独一行,可读性更强

原代码问题说明

你尝试的代码中(StrongAuthenticationmethods | fl)是错误写法:

  • Select-Object中自定义属性必须使用@{Name=; Expression=}的哈希表格式
  • fl(即Format-List)会返回格式化后的输出对象,而非原始属性值,无法作为有效属性添加到结果中

内容的提问来源于stack exchange,提问作者ScriptoPoco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:27:28