Get sAMAccountName of the AD user primary id

Hi everyone, I would need to convert the primary group ID to the corresponding sAMAccountName, but I can’t find anything.
With the script below I get the primary group ID, but I would need to get the sAMAccountName which corresponds to “UOC Gestione delle Infrastrutture Tecnologiche”

Get-AdUser -identity Perry -Properties PrimaryGroupID | select PrimaryGroupID

Can you help me?
Thank you

Have you tried changing the select clause to include both SamAccountName and PrimaryGroupID?

Get-AdUser -identity Perry -Properties PrimaryGroupID | select SamAccountName, PrimaryGroupID

I would not use PrimaryGroupId unless you absolutely have to.

Instead, I would use the PrimaryGroup attribute which is the distinguished name of the primary group. You can pass that straight to Get-ADGroup.

Get-ADUser -Identity Perry -Properties PrimaryGroup |
    Foreach-Object { Get-ADGroup $_.PrimaryGroup | Select-Object SAMAccountName }

Hi Iaage, with your solution the sAMAccountName is that of the user, not that of the PrimaryGroup

Yessss…it works perfectly.
I need to use the sAMAccountName because for the mappings we read an ini file, and for each mapping the sAMAccountName of the group to which the user belongs is defined.
I thank you

1 Like