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 (likeOU=Users) by looking forOU=followed by any characters that aren't a comma.,OU=: Matches the comma and nextOU=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

