I'm querying AD groups outside our local domain. When searching for the groups in PS I've got all the members that are displayed with their SID and not with their User ID.
What I basically want is to enter the user ID and get all the group memberships the user's SID is linked with.
Below is what I've already tried but with no result...
Write-Host "enter user id"
$user = Read-Host
# Forrest were groups are nested
$LDAPServer = 'wwg00m.rootdom.net'
# Get SID from user
$adUsr = Get-ADUser $user -Properties SID | Select-Object SID
# Get all groups from Query in AD
$Groups = Get-ADObject -server $LDAPServer -LDAPFilter '(&(objectCategory=group)(name=*_EN))' | Select Name
# Get all Members from each group, replacing characters to get equal SID ID like $adUser
$Members = (Get-ADGroup -Identity $Groups -Server $LDAPServer -Properties Members).Members -Replace ("CN=", "") -Replace (",ForeignSecurityPrincipals,DC=wwg00m,DC=rootdom,DC=net", "")
foreach ($adUsr in $members) {
[pscustomobject]#{
GroupName = $Members.Name
}
}
Based on conversation in comments this might work. Basically, first we get the SID of the user in the Current Domain, then once we get it we can get the user's DistinguishedName on the Trusted Domain and finally with this information we can perform an LDAP Query searching for all Groups this DN is a member.
try {
# Get user input
$user = Read-Host "Enter User ID"
# Forrest were groups are nested
$LDAPServer = 'wwg00m.rootdom.net'
# Get the SID of the user in the Current Domain
$sid = Get-ADUser $user
# Get the DistinguishedName of the user in the other Domain
$dn = (Get-ADUser $sid.SID -Server $LDAPServer).DistinguishedName
# Search for all groups where this DN is a member
Get-ADGroup -LDAPFilter "(member=$dn)" -Server $LDAPServer | ForEach-Object {
# here we can combine the user's data in the Current and Trusted Domain
# change the output as needed
[pscustomobject]#{
GroupName = $_.Name
UserName = $sid.Name
UserDistinguishedName = $dn
}
}
}
catch {
# Error handling here...
Write-Error $_
}
Related
I am trying to get a script to run that checks if User within an OU and added to the same named Security Group,
If the user moves to another OU it needs to be removed from the group and added to the new group
I understand the concept of what I need to do but I cannot get it into PowerShell.
The User will move from OU to OU, and will need to be removed from the current group and added to the New group
OU's and Security Groups are named the Same:
OU Structure is
You need to use the Compare-object cmdlet.
Try this on some Test OUs and Test user accounts to be safe:
(Update the variables in the beginning of the script to match your environment...)
$VerbosePreference = "continue"
$UserOULocation = "OU=Test unit,OU=OU1,DC=Domain,DC=local" # please update
$DCServerName = "<servername>" # please update
$ADUsers = Get-ADUser -SearchBase $UserOULocation -filter * -Properties * -Server $DCServerName
$OUNames = Get-ADOrganizationalUnit -SearchBase $UserOULocation -Filter *
Foreach ($ADUser in $ADUsers)
{
$Groups = $ADUser.MemberOf | % {Get-ADGroup $_}
$CurrentOU = $ADUser.distinguishedname.Split(",")[1].replace("OU=","")
If ($Groups)
{
# You need to comapre the list of OUs to the groups that the account is a member of
$Comparing = Compare-Object $CurrentOU $Groups.name
foreach ($compare in $Comparing | Where-Object {$OUNames.name -contains $_.inputobject})
{
If ($Compare.SideIndicator -eq "<=")
{
$GroupName = $Compare.InputObject
Write-Verbose "Adding user $($aduser.name) to group $GroupName"
Add-ADGroupMember -Identity $Compare.InputObject -Members $ADUser.SamAccountName -Verbose
}
else
{
$GroupName = $Compare.InputObject
Write-Verbose "Removing user $($aduser.name) from group $GroupName "
Remove-ADGroupMember -Identity $GroupName -Members $ADUser.SamAccountName -Verbose
}
}
}
else
{
Write-Verbose "No - No groups found for user $($aduser.name)"
Write-Verbose "ACTION - Adding user to groups"
Add-ADGroupMember $CurrentOU -Members $ADUser.samaccountname
}
}
If this question is about you wanting to move user 'X' to another OU and by doing so:
remove him from the group with the same name as the OU he is in currently
add him to the group with the same name as the OU he is moved to
Then you could do something like this:
# change these to match your configuration
$userToMove = 'jdoe'
$destinationOU = 'OU=Accounting,DC=Europe,DC=Fabrikam,DC=com'
$user = Get-ADUser -Filter "SamAccountName -eq '$userToMove'" -ErrorAction -SilentlyContinue
if (!$user) { Write-Warning "User '$userToMove' does not exist" }
else {
# parse the OU from the users DistinguishedName property
$currentOU = [regex]::Match($user.DistinguishedName, '(?i)(?=OU=).*$').Value
# use the OU names to get the names for the groups
$currentGroup = (Get-ADOrganizationalUnit -Identity $currentOU).Name
$newGroup = (Get-ADOrganizationalUnit -Identity $destinationOU).Name
# if you need the DisplayNames instead,add parameter -Properties DisplayName
# and get the DisplayName property value. ie:
# $currentGroup = (Get-ADOrganizationalUnit -Identity $currentOU -Properties DisplayName).DisplayName
# $newGroup = (Get-ADOrganizationalUnit -Identity $destinationOU -Properties DisplayName).DisplayName
# remove the user from the group with the same name as the OU he's currently in
Remove-ADGroupMember -Identity $currentGroup -Members $user
# add the user to the new group
Add-ADGroupMember -Identity $newGroup -Members $user
# finally move the user to the new OU
$user | Move-ADObject -TargetPath $destinationOU
}
Regex details used in parsing the OU from the users DistinguishedName:
(?= Assert that the regex below can be matched, starting at this position (positive lookahead)
OU= Match the characters “OU=” literally
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ Assert position at the end of the string (or before the line break at the end of the string, if any)
I am new to powershell and wanted to learn how to get the groups belonging to a user as well as other user object properties in the format below (repeating the user and email for each group):
username user_email user_groups
user1 user1#domain.com group1
user1 user1#domain.com group2
user1 user1#domain.com group3
user2 user2#domain.com group1
user2 user2#domain.com group2
...
I understand that this gets the groups of a user but unsure of how to include other user objects and have it repeated in the above format:
Get-ADPrincipalGroupMembership username | select name
You'll want to get your ADUser objects, expand their memberof property, iterate through those, and get the ad group of each.
$username = "PowerShellGuy"
$adUserObj = Get-ADUser -Filter "SamAccountName -eq '$username'" -properties memberof
$groups = $adUserObj.MemberOf | Get-ADgroup
You can one-line it like this
Get-ADUser -Filter "SamAccountName -eq 'PowerShellGuy'" -properties memberof | % memberof | Get-ADgroup
If you want custom formatting, you can build a custom psobject, or a custom class. I prefer the class method
Class CustomAdInfo
{
$UserName
$Email
$Group
}
If you want one group per, then you can do something like this
Class CustomAdInfo
{
$UserName
$Email
$Group
}
$listOfUsers = #("foo","bar")
$customObjects =
foreach($user in $listOfUsers)
{
$adUserObj = Get-ADUser -Filter "SamAccountName -eq '$user'" -properties memberof, emailaddress
$groups = $adUserObj.MemberOf | Get-ADgroup
foreach($group in $groups)
{
New-Object -TypeName CustomAdInfo -Property #{
UserName = $adUserObj.SamAccountName
Email = $adUserObj.EmailAddress
Group = $group
}
}
}
No reason to overcomplicate it. I've added the Get-ADOU call in case you want to use the name of the group instead of the distinguished name.
$ouname = "Some OU"
$OU = Get-ADOrganizationalUnit -Filter "name -eq '$ouname'"
Get-ADUser -Filter * -SearchBase $OU -Properties mail | Foreach-Object {
Foreach($group in Get-ADPrincipalGroupMembership $_)
{
[PSCustomObject]#{
UserName = $_.samaccountname
User_Email = $_.mail
User_Group = $group.name
}
}
}
I would like to ask if anyone could help me with a script to extract all the AD groups with their members and their email addresses. I'm running the script bellow which I found it in one of the posts which extracts all the AD Groups and their members but I don't know how to include their email addresses also. Thank you very much for your help.
$Groups = Get-ADGroup -Filter * -SearchBase 'OU,OU,OU,OU,OU,DC,DC,DC' #creates a variable with the name Groups and stores all the groups into it
$Results = foreach( $Group in $Groups ){ #looks for members in each group and stores them in Results
Get-ADGroupMember -Identity $Group | foreach {
[pscustomobject]#{
GroupName = $Group.Name
Name = $_.Name
}
}
}
$Results| sort -Property GroupName | Export-Csv -Path c:\temp\groups.csv -NoTypeInformation #stores results in a csv
You'll need to capture the user's email address in your foreach loop, and you'll need to do that by looking up the user properties - a listing of group members only has the member DN and name.
Get-ADGroupMember -Identity $Group | foreach {
$u = get-aduser $_ -properties mail ##plus any other user properties you need
[pscustomobject]#{
GroupName = $Group.Name
Name = $u.Name
Email = $u.mail
}
}
I try to add every User of an AD with a special description to a group wich contains the Department Attribute (up to 3 digits) as a suffix.
For Example
A User "Sam Test" has the Description "Boss" and the Department "123".
He should be added to Testgroup_123.
My Goal
Write a Script to add the Users to their associated Testgroup_???.
There can only be one Boss(User) in a Testgroup_???.
For testing reasons I only try to output the name.
This is my Code so far:
import-module ActiveDirectory
$user =
Get-ADUser -filter {(description -like "Boss") -or
(description -like "boss") -or
(description -like "Assistant")} -searchbase "OU=TestOU,DC=TE,DC=ADS" -Properties Enabled, description, sAMAccountName, Department | select Department | Foreach {Write-Host "Testgroup_$user<-empty?"}
If I understand your right, try this code:
$Users = Get-ADUser -Filter * -Properties Description,Department
foreach ($user in $Users)
{
if ($user.Description -match "Boss|Assistant")
{
$Dep = $User.Department
if (-not(Get-ADGroup "Testgroup_$Dep"))
{
New-ADGroup -Path "OU=TestOU,DC=TE,DC=ADS" -Name "Testgroup_$Dep" -GroupScope Global
}
else
{
$GroupMembers = Get-ADGroupMember -Identity "Testgroup_$Dep" | Select -ExpandProperty SamAccountName
if ($User.SamAccountName -notin $GroupMembers)
{
Add-ADGroupMember -Identity "Testgroup_$Dep" -Members $User
}
}
}
}
First it gets all the users
Check for each user for description match of "Boss" or "Assistant"
Get the department attribute for the user (just for example 666)
Check if Group name "Testgroup_666" Exist, if not Create new one in the path you defined
Check if the user is not already a member of this group, if not add add the user to the group
I want to get all the users in my OU and list only the names of the users that are a member of any group with the word managers in it and list that group or groups they belong to.
So for example
TSmith
Equipment managers
Managers night shift
Bkline
Equipment managers Day Shift
I have been trying to tweak the below script.
The issue is if the user is a member of any group with managers in the name it list everything about that user. All the groups the last log on time everything in AD.
Thanks so much for any help.
Import-Module ActiveDirectory
$users = Get-ADUser -searchbase "OU=East,DC=CHM,DC=com" -Filter * -Properties *
foreach ( $user in $users ) {
$user
$groups = $user | select -ExpandProperty memberof
if ($groups -match 'manager') {
$user.samaccountname
$groups
}
}
Try this:
Get-ADUser -SearchBase "OU=East,DC=CHM,DC=com" -Search -ResultSetSize $null -Filter * -Properties memberOf | Foreach-Object {
# extract grouop names and check if they contain the word 'manager'
$manager = ($_.memberof -replace '^CN=([^,]+),.+$','$1') -like "*manager*"
if($manager)
{
New-Object -TypeName PSObject -Property #{
UserName = $_.SamAccountName
ManagerGroups = $manager -join ';'
}
}
}