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

PowerShell处理用户组字符串:添加转义双引号分隔符

解决AD用户报告中「成员所属组」字段的格式问题

我明白你需要调整用户组字段的输出格式,把连续双引号分隔的样式改成带转义双引号的形式。下面是修改后的完整代码,直接替换原代码就能实现需求:

修改后的完整代码

foreach ($server in $servers) { 
    $Comp = $server 
    if (test-connection -computername $Comp -count 1 -quiet) { 
        ([ADSI]"WinNT://$comp").Children | ?{$_.SchemaClassName -eq 'user'} | %{ 
            $groups = $_.Groups() | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} 
            $_ | Select `
                @{n='Server';e={$comp}}, 
                @{n='DistingishedName';e={$_.AdsPath}}, 
                @{n='Nombre';e={$_.FullName}}, 
                @{n='Departamento';e={$_.Department}}, 
                @{n='Email';e={$_.EmailAddress}}, 
                @{n='Active';e={if ($_.PasswordAge -like 0) {$false} else {$true}}}, 
                @{n='PasswordExpired';e={if ($_.PasswordExpired) {$true} else {$false}}}, 
                @{n='LastLogin';e={$_.LastLogin}}, 
                @{n='Description';e={$_.Description}}, 
                @{n='Groups';e={'"{0}"' -f ($Groups -join '"\"')}} 
        } | Export-Csv $ReportFile -Delimiter ';' -Force -Encoding UTF8 -NoTypeInformation -Append 
    } else { 
        Write-Warning "Server '$Comp' is Unreachable hence Could not fetch data" 3>> $LogFile 
    } 
}

关键修改点说明

原代码里Groups字段用$Groups -join '"'拼接组名,得到的是"GROUP1""GROUP2""GROUP3"这种连续双引号的格式。我把这部分逻辑改成了:

@{n='Groups';e={'"{0}"' -f ($Groups -join '"\"')}}

具体实现逻辑:

  1. 先用$Groups -join '"\"'把每个组名用"\"作为分隔符拼接,得到GROUP1"\"GROUP2"\"GROUP3
  2. 再通过字符串格式化"{0}"把整个拼接结果包裹在双引号中,最终输出就是你需要的"GROUP1"\"GROUP2"\"GROUP3"

修改后导出的CSV里「成员所属组」字段就会完全符合要求的格式了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:38:29