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

PowerShell脚本问题:如何拆分邮箱权限多行输出至CSV

解决邮箱权限CSV合并条目拆分问题

不用正则表达式也能搞定,而且直接在生成CSV的环节处理更靠谱——正则反而容易踩坑(比如权限名称里带逗号的情况)。给你两种可行方案:

方案一:生成CSV时直接拆分(推荐)

问题根源是你之前的脚本可能把同一个邮箱的所有权限合并到了一个对象里。其实Get-MailboxPermission返回的每个权限都是单独的对象,只要循环每个权限条目生成单独行就行:

# 导入用户UPN列表
Import-Csv "users.csv" | ForEach-Object {
    $currentUPN = $_.UserPrincipalName
    # 获取对应邮箱,处理邮箱不存在的异常情况
    $mailbox = Get-Mailbox -Identity $currentUPN -ErrorAction SilentlyContinue
    if (-not $mailbox) {
        # 输出错误提示行,方便后续排查
        [PSCustomObject]@{
            UserPrincipalName = $currentUPN
            Identity = "未找到对应邮箱"
            AccessRights = ""
            IsInherited = ""
            Deny = ""
        }
        return
    }
    # 循环每个权限条目,生成单独行数据
    Get-MailboxPermission -Identity $mailbox.Identity | ForEach-Object {
        [PSCustomObject]@{
            UserPrincipalName = $currentUPN
            Identity = $_.Identity.ToString()
            # 把AccessRights集合转成逗号分隔的字符串
            AccessRights = $_.AccessRights -join ", "
            IsInherited = $_.IsInherited
            Deny = $_.Deny
            InheritanceType = $_.InheritanceType
        }
    }
} | Export-Csv "mailbox_permissions.csv" -NoTypeInformation -Encoding UTF8

这样每个权限都会单独占一行,导出后直接就能在Excel里处理。

方案二:用正则处理已合并的CSV(应急用)

如果你已经有了合并后的CSV文件,非要用正则拆分的话可以试试这个,但要注意:如果Identity或AccessRights里包含逗号,会出现拆分错误:

Import-Csv "merged_permissions.csv" | ForEach-Object {
    # 去掉首尾大括号,拆分Identity和AccessRights为列表
    $identityList = $_.Identity -replace '^\{|\}$', '' -split ',' | ForEach-Object { $_.Trim() }
    $rightsList = $_.AccessRights -replace '^\{|\}$', '' -split ',' | ForEach-Object { $_.Trim() }
    
    # 循环生成每行数据(假设Identity和AccessRights数量一一对应)
    for ($i=0; $i -lt $identityList.Count; $i++) {
        [PSCustomObject]@{
            UserPrincipalName = $_.UserPrincipalName
            Identity = $identityList[$i]
            AccessRights = $rightsList[$i]
            IsInherited = $_.IsInherited
            Deny = $_.Deny
        }
    }
} | Export-Csv "split_permissions.csv" -NoTypeInformation

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:10:31