[英]I need to get the first OU from a Distinguishedname
I have this PS query to get the Distinguishedname of servers:我有这个 PS 查询来获取服务器的专有名称:
$AD = get-adcomputer -filter {OperatingSystem -like '*Server*' -and OperatingSystem -notlike '*2003*'} -property name, description, DistinguishedName | Select name, description, DistinguishedName
and I want to get the first instance of the OU, so I want "OU=Web Servers"我想获得 OU 的第一个实例,所以我想要“OU=Web Servers”
CN=Server1,OU=Web Servers,OU=Servers,OU=HeadOffice Servers,etc
How can I do this?我该怎么做? Thanks
谢谢
Parsing DNs by splitting on commas is a fairly common practice, but can be unreliable because the names can contain embedded commas (they'll be escaped with a backslash).通过逗号分割来解析 DN 是一种相当普遍的做法,但可能不可靠,因为名称可以包含嵌入的逗号(它们将用反斜杠转义)。 Here's a regular expression solution that should be more reliable:
这是一个应该更可靠的正则表达式解决方案:
$dn = 'CN=Server1,OU=Web Servers,OU=Servers,OU=HeadOffice Servers,DC=domaain,DC=com'
$OU = $dn -replace '.+?,OU=(.+?),(?:OU|DC)=.+','$1'
$OU
Web Servers
If you split the DN string and use the comma as the seperator, the OU will then be the second element in the array.如果拆分 DN 字符串并使用逗号作为分隔符,那么 OU 将成为数组中的第二个元素。
This can then be returned using square brackets to access an individual element of the array.然后可以使用方括号返回它以访问数组的单个元素。 As it's the second element we use [1] to access it, as [0] is the first element.
因为它是第二个元素,我们使用 [1] 来访问它,因为 [0] 是第一个元素。
$DN = "CN=Server1,OU=Web Servers,OU=Servers,OU=HeadOffice Servers,DC=This,DC=Com"
$DN.Split(",")[1]
The regular expression solution provided works only if the first element is not OU.提供的正则表达式解决方案仅在第一个元素不是 OU 时才有效。 Here is a solution that will work in any scenario and is a bit more readable for the non-regex types.
这是一个适用于任何场景的解决方案,对于非正则表达式类型更具可读性。 If you have the following example the splitting by "," or the regular expression solution will return 'OU=Servers', 'Servers" respectively ( I assume you want to have the OU= removed from the string )
如果您有以下示例,则由“,”拆分或正则表达式解决方案将分别返回 'OU=Servers', 'Servers' (我假设您希望将 OU= 从字符串中删除)
$dn = 'OU=Web Servers,OU=Servers,OU=HeadOffice Servers,DC=domaain,DC=com'
($dn -split 'OU=|,OU=')[1]
If you don't have nested OUs then you might need to add some additional logic如果您没有嵌套的 OU,那么您可能需要添加一些额外的逻辑
(($dn -split 'OU=|,OU=')[1] -split ',')[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.