0

i have a skript to check a users groups but what would be nice to have is the owner of the group ("managed by") as well.

$Username = Read-Host "Enter User ID"
$date = Get-Date -format "yyyy-MM-dd"
$name = Get-ADUser "$Username" | select name

write-output "Status: $date $Username $name"
Get-ADPrincipalGroupMembership $Username | Get-ADGroup -Properties * | select name, description  | export-csv C:\temp\$date-$Username-$name.csv
ii C:\temp\

Very appreciated for any kind of help.

:-)

DWeber
  • 1
  • you are getting all the props for each group ... and then throwing away all but two. so ... why don't you just keep the additional one you want? – Lee_Dailey Jan 24 '22 at 10:18

1 Answers1

1

As Lee_Dailey commented it is a waste to ask for all properties when you only want a few..

Also, you should always test if the user entered in the Read-Host can be found at all, because anyone can type just about anything there.

Try

$Username = Read-Host "Enter User ID"

# try and find the user in AD
$user = Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue
if ($user) {
    # Get-ADGroup already returns these properties by default:
    # DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
    # so only ask for the extra properties you need
    $user | Get-ADPrincipalGroupMembership | Get-ADGroup -Properties Description, ManagedBy | ForEach-Object {
        # try and get the group manager from the DistinguishedName in the ManagedBy property
        $manager = if ($_.managedBy) { (Get-ADUser -Identity $_.managedBy).Name } else { 'Not set' }
        [PsCustomObject]@{
            Name        = $_.Name
            Description = $_.Description
            ManagedBy   = $manager
        }
    } | Export-Csv -Path (Join-Path -Path 'C:\Temp' -ChildPath ('{0:yyyy-MM-dd}-{1}.csv' -f (Get-Date), $user.Name )) -NoTypeInformation
}
else {
    Write-Warning "User '$Username' not found.."
}
Theo
  • 57,719
  • 8
  • 24
  • 41