Finding a User on one of many domains - powershell

I am trying to get a script running but I keep running across the same issue, I have domains A, B, and C all in the same forest; but when I try to do simple commands such as
Disable-ADAccount -Identity $User
I am not able to get it to complete because it can't find the user in Domain B, which the user is in Domain A.
So the question, is there a way to get a script to check all domains (A, B, C) for "User1" and preform the disable action on them. (Other than setting the Switch)
-server

I ran into this issue recently, and ended up writing a function to get a user's ADUser object. You could use that object to disable the user easily enough.
Function Get-DomainUser{
Param([String]$Alias)
BEGIN{$GCs = Get-ADForest|select -expand GlobalCatalogs|?{($_ -match "^(.*?)\.(.+?)$")}|%{[pscustomobject]#{'Server' = $matches[1];'Region' = $matches[2];'FQDN' = $_}}|group region|%{$_.group|select -first 1}
}
PROCESS{
$DomUser = Get-ADUser -Filter {samAccountName -eq $Alias} -Prop DisplayName
If(([string]::IsNullOrEmpty($DomUser.Name))){
ForEach($GC in $GCs){
$DomUser = Get-ADUser -Filter {samAccountName -eq $Alias} -Server $GC.FQDN -Prop DisplayName
If(!([string]::IsNullOrEmpty($DomUser.Name))){Break}
}
}
$DomUser
}
}
This gets a list of global catalog servers, groups them by sites, then gets only 1 server per site. Then it tries to get the user, and if it fails for the current user then it tries each site until it finds the user.

Related

Using Powershell, how to get a list of Active Directory group members, including users and contacts, showing name, company, and email

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.

how to take users off ad groups user is part of

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

Need to validate user input (domain user,group) and fetch detail

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

How to extract a list of users with rights to create domain users in the Active Directory?

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

Searching AD Groups attached to specified Server

I'm looking to use powershell, specify a server hostname, and have it display all the AD Groups that have access to that server. From there I'll dig into the groups eventually getting the usernames and storing them in a csv file.
So far I have the code to get the DN of the server -
Get-adcomputer HOSTNAME | select DistinguishedName
Along with having the code to get the eventual usernames and store them in a csv -
$groups= GROUPS
$selectgroups=$groups |Get-Adgroup
$selectgroups |get-adgroupmember -Recursive | Select samaccountname |
Export-csv -path C:\Groups\Members.csv -NoTypeInformation
My problem is I can't figure out how to get powershell to query what groups are on the server I specify. Is this possible or will I have to look at another way of doing this?
Thanks.
Not sure you know exactly what you're looking for. There's no way to tell which AD groups have been granted access to a node via AD. The only thing you can do is look on the local node for AD groups, but there's a lot of places you could want/need to look as Frode F. mentioned already. A common theme would be which AD groups have been added to LOCAL groups on the node in question.
You could use WMI or the ADSI adapter for this information. An ADSI example to get all members of the 'Administrators' local group for server 'NODE123':
$server = "NODE123"
$arrGroupMembers=#()
$Group = "Administrators"
$ADSIComputer = [ADSI]("WinNT://" + $server + ",computer")
$ADSIGroup = $ADSIcomputer.psbase.children.find($Group)
$ADSIMembers= $ADSIGroup.psbase.invoke("Members")
foreach ($member in $ADSIMembers) {
$MemberClass = $member.GetType().InvokeMember("Class", 'GetProperty', $Null, $member, $Null)
if ($memberClass -eq "Group") {
$MemberName = $member.GetType().InvokeMember("Name", 'GetProperty', $Null, $member, $Null)
$arrGroupMembers+=$MemberName
}
}
With the array return above, you now have all groups that have access to NODE123 via being added to the local Administrators group. Maybe this example helps you.