When I supply a string and need to extract the domain user object (name, surname, manager name) I get the desired detail through following code.
$groupdetail : gc d:\domainobject.txt
$output = Get-ADUser $GroupDetail
$output | Select Name, GivenName,SurName, #{label="Manager";expression={(Get-ADUser $_.Manager -Properties DisplayName).Displayname}}
Next thing is validate of the input if it is a domain group then extract the group member names then get the user object information again as above. The problem is I am unable to validate if the string is a group.
$groupname = Get-content D:\domainobject.txt
foreach ($group in $groupname){
$groupname = get-adgroup $group
$groupmember = Get-ADGroupMember $groupname | Format-Table Name, SamAccountName -AutoSize
foreach ($groupdetail in $groupmember){
$groupdoutput = get-aduser $groupdetail
$groupoutput | Select-Object Name, GivenName,SurName, #{label="Manager";expression={(Get-ADUser $_.Manager -Properties DisplayName).Displayname}}
}
Write-Host $groupoutput
}
Both condition should run in one code so if the input string is a domain user get the information and exit. Incase string is a domain group it will loop in get the group member name then extract the domain user information. One way I thought is to run this condition $groupname.objectclass -eq "group" or $groupname.objectclass -eq "name" so that I need to convert the input string to PowerShell object.
I tried a few things but that did not work. Please suggest what are the possible way I can achieve this.
You could always use a try-catch block
try{$group = get-adgroup $groupname}
catch{$user = get-aduser $groupname}
if($group)
{write-host "It's a group!"}
else
{Write-host "It's a user!"}
That will tell you if it's a group or a user. Just replace the write-host with your logic.
Usually when doing this sort of thing, I want one of two things:
In the first case, if I want the groups that a user is a member of directly regardless of nesting, then I specify:
Get-AdUser -Identity 'Alice' -Properties MemberOf
This will return the MemberOf property with the user, which is a string array that in each element includes the distinguished name of a group the user is a direct member of. Depending on exactly what you're doing, it may make sense to fetch all groups from AD at once to get the group details en masse, and then do a lookup for each MemberOf.
In the second case, I only care about effective group membership of user accounts. I will want Get-AdGroupMember to resolve the nested groups into the resulting set of users. In other words, if I run Get-AdGroupMember -Identity 'Foo', and the members are user Alice and group Bar, and user Bob is a member of group Bar, then I want the cmdlet to return Alice and Bob. I don't care that Bar is the reason that Bob is in Foo. To do that, I run:
Get-AdGroupMember -Identity 'Foo' -Recurse
Related
I'm trying to export lists of AD group members with powershell. I was doing great with commands like this:
Get-ADGroupMember "MyGroupName" -Recursive | Get-ADUser -Properties Company,Surname,GivenName,EmailAddress | select Company,Surname,GivenName,EmailAddress | Sort-Object -Property Company,Surname | Export-CSV $home\Desktop\MyGroupName.csv
Then I realized that I was only getting users and not getting contacts, and I need both. I spent a pile of time Googling for how to include contacts as well as users, delving into Get-ADObject and filtering with ObjectClass "contact", but I can't seem to find a simple way to dump a list of group members that includes both users and contact and displays the info I want.
One suggestion online was to use
(Get-ADGroup "MyGroupName" -Properties members).members
That gives me the DistinguishedNames of the members, including both users and contacts, but I can't figure out how to get the properties I want. The property names between contacts and users don't really align - mail vs. EmailAddress, etc. Also, piping that output to Get-ADUser, unsurprisingly throws errors on the contacts.
If I pipe it to something like this:
Get-ADObject -Filter 'objectClass -eq "contact"' -Properties CN,mail,company | Format-Table CN,mail,company
I get the info I want on the contacts, but it throws errors on all of the users. Any advice/assistance would be appreciated. Thanks!
You'll need to process Users separately from Contacts, more or less. This isn't tested or complete, but should point the way for you:
(Get-ADGroup "MyGroup" -Properties Members).Members | Get-ADObject | ForEach-Object {
if ($_.ObjectClass -eq "contact") {
#emit what you want for a contact
} elseif ($_.ObjectClass -eq "user") {
#emit what you want for a user
} else { #it's probably a group, but ...
#process whatever isn't a user or a contact
}
}
What this does when you fill in the comments with your real code is
Gets the members from the group
Passes them to Get-ADObject, to get things like email, name, et cetera
Passes that result to ForEach-Object which then
Inspects the object to see what type it is (user, contact, something else), and
process the object based on the type, since the fields for each object type are apparently different.
I need a PowerShell script to count the members of an AD group that have the extensionAttribute4 property equal to o365_facstaff.
I’ve been using the following script to count all members of the group but I specifically need just the ones with the property:
$ADInfo = Get-AdGroup -Identity ‘<group name>’ -Properties Members
$ADInfo.Members.Count
We can get this information from AD with a single -Filter query on Get-ADUser:
# We'll need the group DN instead of the group name
# Here's an example
$groupDn = 'CN=test_group,CN=Users,DC=bender,DC=net'
# Get all ADUsers member of the target group with the specific
$groupMembers = Get-ADUser -Filter "(memberOf -RecursiveMatch '$groupDn') -and (extensionAttribute4 -eq 'o365_facstaff')"
# Check the Count property like you would with any array
$groupMembers.Count
Alternatively, as also mentioned in the comments, you can get the group members off of the ADGroup and further filter, though this results in additional unnecessary local processing. This can become problematic with very large groups, especially if your ADDS infrastructure runs closer to the minimum system requirements:
# Using $ADInfo from your code sample
$membersWithfacstaff = $ADInfo.Members | Where-Object {
( Get-ADUser $_ -Properties extensionAttribute4 ).extensionAttribute4 -eq 'o365_facstaff'
}
# Use the Count property
$facstaff.Count
As also mentioned in the comments, Measure-Command will give you the count too but is a bit redundant here, considering you'd have to reference the Count property anyways if you want to use it programmatically.
See this answer of mine for more information on effectively using the -Filter parameter on the RSAT AD cmdlets.
We are trying to take user off all ad groups when user is termed in HR Database. I have the termination of user account figured out but how can we take that specific user our of all assigned group using powershell.
You will want to retrieve the ADUser object before deleting it from ActiveDirectory, examine its .MemberOf property, and then run through those groups with the Remove-ADGroupMember cmdlet.
To get you started you need to get the user's memberOf and the user's distinguishedName
In the following example I am getting the user by their logon name (samaccountname) You can use whatever attribute you want as long as it returns the correct user:
$testUser = "Test User"
$user = Get-ADUser -filter {Samaccountname -eq $testUser} -Properties memberof, distinguishedName
$Groups = $user.MemberOf
$DN = $user.DistinguishedName
Then in order to remove the user from their current membership, you can just put it in a foreach:
foreach($group in $groups)
{
Remove-ADGroupMember -Members $DN -Identity $group -Confirm:$false
}
The -Confirm:$false is to suppress the warning about removal. You might want to remove that part during testing
Many will tell you to look at the user's memberOf attribute. That will work just fine in most cases.
However, memberOf only shows groups with a scope of 'Universal' on any domain in the forest, or 'Global' groups on the same domain. It will not show groups with a 'Domain Local' scope (regardless of domain), or 'Global' groups on other domains.
To guarantee you find all groups the user is a member of, you need to search every domain in your forest for groups that the user is a member of:
Import-Module ActiveDirectory
$user = Get-ADUser "theuser"
$domains = (Get-ADForest).Domains
$groups = New-Object System.Collections.ArrayList
foreach ($domain in $domains) {
$groups.AddRange(#(Get-ADGroup -filter {member -eq $user.DistinguishedName} -Server $domain))
}
Then $groups has the list of groups, and you can use Remove-ADGroupMember to remove the user from those groups.
Again, this is only relevant to you if you either:
Have more than one domain in your forest, and/or
Use 'Domain Local' groups
I was tasked with creating Powershell scripts that we will use to review the Active Directory of our clients. I like to add that my knowledge of Powershell is very basic, but I've found A LOT online (including many Stack Overflow topics!) to help me with this task. My script is pretty much in place, but there is one functionality that I would like to add to my script. I do not know if (and how) this even possible. I've looked at many sites to help me with this issue, but I did not find any solutions. So I decided to ask it to the community itself. Here is a description of my issue.
What I want is to have a list of users that have the rights to create Domain Users and have the rights to install Updates / Hot-Fixes on Domain Controllers. In order to be able to create a Domain User, the user must have a membership (or equivalent) to Domain Administrators (Found here https://technet.microsoft.com/en-us/library/dd894463(v=ws.10).aspx. It's easy to get the Domain Administrators and Enterprise Administrators (the latter having also the ability to create Domain Users obviously). I have a script that retrieves all the Domain Users and the groups that they have membership to, so that is covered.
What I want to achieve is to get Domain Users that are not a member of the Domain Administrators (or equivalent) groups that have rights to create Domain Users (or within certain OU's like explained in this topic https://serverfault.com/questions/83686/how-to-create-a-limited-domain-admin-that-does-not-have-access-to-domain-contr).
There is not an attribute that defines what I am looking for. I had some ideas of using de 'admincount' property like this: Get-ADUser -Server $ADServer -Filter {admincount -gt 0}. This returns to me all the ADUsers that are within the Default Protected Groups within the Active Directory. But what I want is to be able to get Users that are not contained in these groups.
Is there a way to get this information?
Sorry I began fully coding this but without seeing your script and not having a full test AD env in front of me at the moment, I will give you the psudo-code as it seems like you've done enough that you can probably take this code and run with it and pretty easily have a fully working script since most the primary commands/filters needed I have included below:
Get a list of all OUs
$OUs = #(Get-ADDomain | Select-Object -ExpandProperty DistinguishedName)
$OUs += Get-ADOrganizationalUnit -Filter * | Select-Object -ExpandProperty DistinguishedName
$OUs += Get-ADObject -SearchBase (Get-ADDomain).DistinguishedName -SearchScope OneLevel -LDAPFilter '(objectClass=container)' | Select-Object -ExpandProperty DistinguishedName
Get a filtered list of all non-admin users using:
Get-ADUser -Server $ADServer -Filter { admincount -eq 0 }
Loop through each of the OUs and retrieve their permissions
foreach ($OU in $OUs)
(Get-Acl $OU).access | where { accesscontroltype -eq 'Allow' })
Inner loop your filtered non-admin user array with each access permission needed to perform the pseudo-admin duties using:
foreach ($objUser in $(Get-ADUser -Server $ADServer -Filter { admincount -eq 0 }))
(Get-Acl $OU).access | where { identityreference -eq <TRIMMED INNER LOOP USER OBJECT NAME FROM $objUser> }
If matched, add to new array, otherwise do nothing
Dump array to report
I want to know if this is possible to compare two object's properties with the LDAPfilter ?
Something like (This is not working - return nothing every time): -LDAPfilter {sAMAccountName=userPrincipalName}
I tried to find a clue in this Microsoft's documentation about the LDAPfilter, but I found nothing.
Some explanations about my goal :
I want to get every user with the User logon name different than the User logon name (Pre Windows 2000).
I am using the command "Get-ADUser"
The two properties I want to compare are : "User logon name" (userPrincipalName) and "User logon name (Pre Windows 2000)" (sAMAccountName)
I don't know if this is possible with the LDAP filter, if not, is there an other way to do it ?
No, it's not possible with an LDAP filter. You can only compare an attribute with a value, not two attributes with each other. You need something like this for the latter:
Get-ADUser -Filter * -Properties * |
? { $_.SamAccountName -eq $_.UserPrincipalName }
Note that these two properties are practically guaranteed to be different, because the UPN normally includes the FQDN of the domain whereas the sAMAccountName does not. Your comparison will effectively look somewhat like this:
'user' -eq 'user#domain.example.com'
so you may want to do something like this instead:
Get-ADUser -Filter * -Properties * |
? { "$($_.SamAccountName)#$env:USERDNSDOMAIN" -eq $_.UserPrincipalName }