Yallabina
Yallabina

Reputation: 117

Get security groups members Domain\Username

I have script that get all members of security groups across domains and export to CSV file in this format: Name, username, security group. But I want to add another row for the domain so format will look like this: domain\username, name, security group.

I could get the DN but I am only interested in just domain\username. I search around in the internet and I couldn't find anything and I am not sure if this even possible

$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = @($objForest.Domains | Select-Object Name) $Domains = $DomainList | foreach {$_.Name}
$Groups = Import-Csv C:\ad.csv
$Table = @()
$Record = @{   "Group Name" = ""   "Name" = ""   "Username" = "" }

Foreach ($Group in $Groups) {
  $Arrayofmembers = Get-ADGroupMember -identity $Group.groupad
-recursive  -Server $Domain | select name,samaccountname
  foreach ($Member in $Arrayofmembers) {
    $Record."Group Name" = $Group.ad
    $Record."Name" = $Member.name
    $Record."UserName" = $Member.samaccountname
    $objRecord = New-Object PSObject -property $Record
    $Table += $objrecord
  } 
}

$Table | export-csv "C:\SecurityGroups3.csv" -NoTypeInformation

Upvotes: 1

Views: 1631

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59031

As Bum mentioned, you can use a regex to get the DC and combine it with the username:

$username = 'Michael'
$distinguishedName = 'CN=Domain Admins,CN=Users,DC=Fabrikam,DC=com'

$dc = [regex]::Match($distinguishedName, 'DC=([^,|$]+)').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username

Output of $domainuser:

$domainuser
Fabrikam\Michael

Upvotes: 1

Related Questions