Skip to content

Instantly share code, notes, and snippets.

@kliemohn
Created March 6, 2015 16:23
Show Gist options
  • Save kliemohn/0eeb2d15a1206f496ea1 to your computer and use it in GitHub Desktop.
Save kliemohn/0eeb2d15a1206f496ea1 to your computer and use it in GitHub Desktop.
Parses a file full of user name and user IDs and outputs only the domain names found.
# Parses display name w/ user IDs (e.g., "John Doe [mydomain\jdoe]") to get the domain name
# Handles multiple per line if separated by semicolons
# Input is the filename that contains the rows of display names with user IDs
# Outputs only the domain name (does not output duplicates for the same row)
$currentPath=Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path
$filename = Join-Path $currentPath $args[0]
foreach ($line in [System.IO.File]::ReadLines($filename)) {
$users = $line.ToLower().Split(';')
$domains = new-object System.Collections.ArrayList
foreach ($user in $users)
{
$domainName = $user # Default domain name to entire user string as a fallback
$index = $user.IndexOf('[')
if ($index -ge 0)
{
# We know where the domain name starts, now find out where it ends
$userIdPart = $user.Substring($index + 1)
$index = $userIdPart.IndexOf("\")
if ($index -ge 0)
{
# We know where the domain ends - so get it
$domainName = $userIdPart.Substring(0, $index)
}
}
if ($domainName.length -gt 0 -and -not $domains.Contains($domainName))
{
# Add the domain name to our array, but only if it isn't a duplicate
$domains.Add($domainName) | out-null
}
}
# Sort the domain names for this row
$domains.Sort()
# Join the domain names for this row and have them separated by a semicolon
$domainsForRow = [System.String]::Join(";", $domains.ToArray([System.Type]::GetType("System.String")))
# Output the domain names for this row
Write-Output $domainsForRow
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment