如何将Powershell从Outlook全局地址列表获取的用户名与邮箱配对存入数组
问题原因
你当前的写法是在ForEach-Object循环中依次输出用户名、邮箱两个独立值,PowerShell会自动将这两个值作为两个独立元素添加到数组中,因此输出时会各自占一行。
解决方法
方案1:直接生成空格分隔的字符串数组(符合你要求的输出格式)
[Microsoft.Office.Interop.Outlook.Application] $galSearch = New-Object -ComObject Outlook.Application $search = @($galSearch.Session.GetGlobalAddressList().AddressEntries | ForEach-Object { $exchangeUser = $_.GetExchangeUser() # 过滤无效条目,避免非Exchange用户对象报错 if ($null -ne $exchangeUser) { "$($exchangeUser.Name) $($exchangeUser.PrimarySmtpAddress)" } }) $search
输出结果直接就是你需要的每行包含用户名+对应邮箱的格式。
方案2:生成结构化对象数组(更便于后续二次处理)
如果后续还需要单独调用用户名或邮箱属性,更推荐存储为自定义对象:
[Microsoft.Office.Interop.Outlook.Application] $galSearch = New-Object -ComObject Outlook.Application $userList = @($galSearch.Session.GetGlobalAddressList().AddressEntries | ForEach-Object { $exchangeUser = $_.GetExchangeUser() if ($null -ne $exchangeUser) { [PSCustomObject]@{ 用户名 = $exchangeUser.Name 邮箱地址 = $exchangeUser.PrimarySmtpAddress } } }) # 需要输出空格分隔格式时再遍历转换即可 $userList | ForEach-Object { "$($_.用户名) $($_.邮箱地址)" }
内容的提问来源于stack exchange,提问作者foposo
相关产品推荐
相关产品推荐

