I frequently get requests to modify or lookup a list of user names in a CSV file where the username is NTDomain\SamAccountName. Get-ADUser will let you use the NT domain as a server name, but in my experience it is slower than using the domain’s FQDN. Before I import the list in my code, I run Get-DomainNameHashTable, which returns the hash object $domHash. The name in $domHash is the NT/NetBIOS domain name (CONTOSO), and the value is the DNS Root/FQDN for the domain (CONTOSO.COM).
Function Get-DomainNameHashTable { $Forest = ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()) $DomainList = ($Forest.Domains).Name #Bill Stewart function Invoke-Method([__ComObject] $object, [String] $method, $parameters) { $object.GetType().InvokeMember($method, "InvokeMethod", $NULL, $object, $parameters) } $NameTranslate = New-Object -ComObject "NameTranslate" #INITTYPE_GC Invoke-Method $NameTranslate "Init" ((3), "") $Script:domHash = @{} $domainList | ForEach-Object { $dn = "DC=" + $($_).replace(".", ",DC=") #Set is From Type 1779 Get is to Type NT4 Invoke-Method $NameTranslate "Set" ((1), $dn) $NTDom = [string](Invoke-Method $NameTranslate "Get" (3)).Replace("\", "") $domHash.Add($NTDom.ToUpper(), $_.ToUpper()) } [System.Runtime.Interopservices.Marshal]::ReleaseComObject($NameTranslate) | Out-Null $domHash }
After reading the CSV file, I split the user name name on “\”, then lookup up the DNS root for Contoso with $domHash[‘Constoso’], or $domHash.item(‘Constoso’). Here is an example:
$userlist = import-csv "$env:userprofile\Desktop\userlist.csv" Get-DomainNameHashTable ForEach-Object ($FullName in $$userList.Name){ $t = $FullName.split("\") $NTDom = $t[0] $SamName = $t[1] $Domain = $domHash[$NTDom] Get-ADUser -Server $domain -SamName }