如何用PowerShell提取AD中计算机的OU路径(移除CN前缀)
提取AD计算机DistinguishedName中的OU路径(移除CN部分)
你已经拿到了AD计算机的DistinguishedName,现在要去掉开头的CN=xxx部分,只留第一个逗号后面的内容,不管计算机名多长,这几种方法都能搞定:
方法一:字符串截取
直接定位第一个逗号的位置,从其后开始截取内容:
$testingThis = Get-ADComputer -Identity "ComputerExample" -Properties DistinguishedName | Select-Object -ExpandProperty DistinguishedName # 截取第一个逗号之后的所有内容 $ouPath = $testingThis.Substring($testingThis.IndexOf(',') + 1) Write-Output $ouPath
原理很简单:用IndexOf(',')找到第一个逗号的位置,再通过Substring从逗号的下一个字符开始截取,直接得到后面的OU和DC路径。
方法二:正则表达式替换
用正则精准匹配开头的CN段,直接替换为空:
$testingThis = Get-ADComputer -Identity "ComputerExample" -Properties DistinguishedName | Select-Object -ExpandProperty DistinguishedName # 替换掉开头的CN=xxx,部分 $ouPath = $testingThis -replace '^CN=.*?,', '' Write-Output $ouPath
正则表达式^CN=.*?,会匹配从字符串开头到第一个逗号的CN段,替换成空字符串后,剩下的就是你需要的路径。
测试效果
如果你的原始输出是:
CN=example,OU=example,OU=example,OU=example,DC=madeup,DC=madeup,DC=madeup,DC=madeup
经过上面任意一种方法处理后,会得到:
OU=example,OU=example,OU=example,DC=madeup,DC=madeup,DC=madeup,DC=madeup
内容的提问来源于stack exchange,提问作者skysthelimit91
相关产品推荐
相关产品推荐

