用于Active Directory用户的Csv导出脚本

时间:2017-04-19 11:32:04

标签: powershell active-directory

我用我的脚本提取我的活动目录的用户

Import-Module ActiveDirectory
Get-ADUser -Filter * -properties * | Select SAMaccountname, givenname, surname, DistinguishedName | Export-Csv c: \ users \ administrator \ desktop \ users.csv -notypeinformation -Encoding UTF8

在这个脚本中,我使用DistinguishedName命令返回CN,OU和DC。我的目标是在创建.csv时只保留第一个OU并删除其余的。

脚本返回的示例:

"SAMaccountname","givenname","surname","DistinguishedName"
"Jean-Yves.R","Jean-Yves","Raymond","CN=Jean-Yves Raymond,OU=Communication,OU=Direction Générale,OU=Elan & Co,OU=Domain Controllers,DC=ELAN-G1,DC=local"

我想要的例子:

"SAMaccountname","givenname","surname","DistinguishedName"
"Jean-Yves.R","Jean-Yves","Raymond","Communication"

TY:)

2 个答案:

答案 0 :(得分:1)

这将为您提供所需的OU属性。

Get-ADUser -Filter * -properties * | Select SAMaccountname, givenname, surname,@{Name='OU';Expression={$($_.DistinguishedName).Split(",")[1].Replace("OU=","")}}

修改

处理用户OU:

Get-ADUser -Filter * -properties * | Select SAMaccountname, givenname, surname,@{Name='OU';Expression={$($_.DistinguishedName).Split(",")[1].Replace("OU=","").Replace("CN=","")}}

答案 1 :(得分:0)

Get-ADUser -Filter * -properties * | Select SAMaccountname, givenname, surname,@{l='DistinguishedName';e={([adsi]"LDAP://$($_.DistinguishedName)").Parent}}

这使用Select语句中的计算属性通过LDAP获取DistinguishedName的Parent属性。