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

PowerShell正则提取Active Directory中ManagedBy属性的城市名

Hey there! Let's get that city name (PARIS) extracted from your Active Directory managedby attribute value—your initial approach of stripping special characters works, but it makes it hard to target exactly what you need. Let's use two straightforward methods, one with regex (for precision) and one without (for simplicity, since you mentioned being new to regex).

Method 1: No Regex (Easy to Follow)

This uses PowerShell's built-in splitting and filtering, which might feel more intuitive if regex feels intimidating:

# Store your managedby value in a variable
$managedByValue = 'CN=Marley\, Bob,OU=Users,OU=PARIS,DC=Domain,DC=com'

# Split the string into individual components using commas as separators
$rdnParts = $managedByValue -split ','

# Filter to get only the OU entries, then pick the second one (your city OU)
$cityRdn = $rdnParts | Where-Object { $_ -like 'OU=*' } | Select-Object -Index 1

# Remove the "OU=" prefix to get just the city name
$cityName = $cityRdn -replace 'OU=', ''

# Output the result
Write-Output $cityName

This will spit out PARIS directly. Here's why it works:

  • Splitting by commas breaks the long string into chunks like CN=Marley\, Bob, OU=Users, OU=PARIS, etc.
  • We filter for entries starting with OU= (since those are organizational units), then grab the second one (index 1, because PowerShell arrays start at 0).
  • Finally, strip off the OU= prefix to get your clean city name.

Method 2: Regex (More Concise)

If you want a one-liner, this regex targets exactly the OU that comes after another OU (which is your city in the example):

$managedByValue = 'CN=Marley\, Bob,OU=Users,OU=PARIS,DC=Domain,DC=com'
$cityName = [regex]::Match($managedByValue, 'OU=[^,]+,OU=([^,]+)').Groups[1].Value
Write-Output $cityName

Let's break down the regex:

  • OU=[^,]+ : Matches the first OU entry (like OU=Users) by looking for OU= followed by any characters that aren't a comma.
  • ,OU= : Matches the comma and next OU= prefix.
  • ([^,]+) : This is a capture group—it grabs all characters that aren't a comma (your city name, PARIS).
  • Groups[1].Value : Pulls the content from that first capture group, which is exactly what we need.

Both methods will work for your example, and you can adjust them if your OU structure changes (e.g., if the city is the last OU, just tweak the index in Method 1 or adjust the regex in Method 2).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:58:14