Since active directory does not have an attribute like parent or directory you will have to use either the DistinguishedName or the CanonicalName and cut the desired pieces from it.
Assumed your Common Names do not have commas or slashes in them you could use something like this:
$Server_list = Get-Content 'C:\scripts\servers.txt'
$sqlcmd1 = @'
SELECT name
FROM sys.server_principals
WHERE TYPE IN ('U')
ORDER BY name, type_desc
'@
$Result=
foreach ($Server in $Server_list) {
$myarray1 = Invoke-Sqlcmd -serverInstance $Server -Database master -Query $sqlCmd1
Foreach ($user in $myarray1.Login) {
$ADUser = Get-ADUser -Identity $user -Properties CanonicalName
[PSCustomObject]@{
ComputerName = $Server
UserName = $ADUser.Name
ParentOU = ($ADUser.CanonicalName -split '\/')[-2]
}
}
}
$Result
I’d recommend to output it as CSV or any other kind of structured data. This way you can easily read it again with PowerShell and process it as needed.
Now I’m trying to get recursive list of users from AD group using same code format but not working.
Not sure where I’m going wrong? Can you please help?
Incorrect Output
Servername System.Object
Expected Output
Servername username ParentOU
Code
$Server_list = Get-Content 'C:\scripts\servers.txt'
$ErrorActionPreference = ‘SilentlyContinue’
$sqlcmd2 = @"
SELECT name
FROM sys.server_principals
WHERE TYPE IN ('G')
ORDER BY name, type_desc
"@
$Result2=
foreach ($Server in $Server_list) {
$myarray2 = Invoke-Sqlcmd -serverInstance $Server -Database master -Query $sqlCmd2
foreach ($group_name in $myarray2.Login) {
$ADGroup = Get-ADGroupMember -Identity $group_name -Recursive
foreach ($name in $ADGroup.name) {
$ADUser2 = Get-ADUser -Identity $name -Properties CanonicalName
[PSCustomObject]@{
ComputerName = $Server
UserName = $ADUser2.Name
ParentOU = ($ADUser2.CanonicalName -split '\/')[-2]
}
}
}
}
You’re lacking the fundamentals. I’d recommend to do a big step back and start with learning the very basics of PowerShell first. It will save you from a lot of wasted time and frustrations.
It is not the purpose of this forum to iteratively and interactively develop your scripts step by step for you.
Since Get-ADGroupMember does not return a CanonicalName like it Get-ADUser does you cannot use the same method like before. But I actually showed 2 ways to get the parent OU of a given account.