Trying to script adding users to a Group - powershell

I'm trying to create a simple script that will automate membership to a security group for my org.
I think my variables are coming back empty and are likely either defined wrong or I messed up the syntax somehow. Hoping someone here can help me see the error in my ways!
I am going to edit the code below to better explain my issue. The attribute I am calling can either have a value of M or it is null.
If I run the following command, I get back a list of users who have extensionattribute6 = M
get-aduser -filter {extensionattribute6 -like 'M*'}
If I attempt to add in the section that specifies OU, the results become null.
I guess all I'm asking is if there is a syntax mistake with the OUs or, if not, if anyone could hazard a guess as to what I am doing wrong. :)
$OU = "ou=ou1,ou=ou2,ou=ou3,dc=dc1,dc=dc2"
get-aduser -filter {extensionattribute6 -like 'M*'} -searchbase $OU

When you use the filter and like operator, you have to use the * on the right side of the statement.
$managers = Get-ADUser -SearchBase $OU -Filter "extensionattribute6 -like 'M*'"
This will add a list of AD Users that have a value that Starts with M in extensionattribute6. If you dont add the * to the right side, 'M', then it will look for all users with an extensionAttribute6 value that equals M.
If you are comparing them to be equal, then you can use -eq for equality (without stars * inside quote)
$managers = Get-ADUser -SearchBase $OU -Filter "extensionattribute6 -eq 'M'"
If you have multiple specific OUs you want to go over, might i suggest using a list of these OUs and iterating over them.
$OUs = #()
$OUs += "OU=OU1,DC=domain,dc=com"
$OUs += "OU=OU2,OU=someParent,dc=domain,dc=com"
...
$managers = #()
foreach($OU in $OUs) {
$managers += Get-ADUser -SearchBase $OU -Filter "extensionattribute6 -eq 'M'"
}

I arrived at a solution to this. I needed to call a new variable, borrowing heavily from what Jawad suggested.
The code I settled on is as follows.
$Managers = #()
$Managers += get-aduser -filter * -searchbase "ou=ou1,ou=ou2,ou=ou3,dc=dc1,dc=dc2" -properties extensionattribute6 | where-object{$_.extensionattribute6 -like 'M*'}
foreach ($Manager in $Managers) {add-adgroupmember -identity <groupname> -members $Manager}

Related

Get-AdUser Cannot convert to the type system.string

I am trying to run the get-aduser query below and I keep getting the error Get-AdUser Cannot convert to the type system.string. Any idea what might be the problem? TIA
$Base = (Get-ADOrganizationalUnit -Filter {(Name -like "Department")}).DistinguishedName
Get-ADUser -Filter * -SearchBase $Base -Properties Name
I tested this, and I can confirm that if your call to Get-ADOrganizationalUnit returns more than one OU, then the DistinguishedName property will be an array rather than a plain string. So you will need to change your call to Get-ADOrganizationalUnit so that it returns only one.
You can do that by either using the -ResultSetSize parameter to only use the first result:
$Base = (Get-ADOrganizationalUnit -Filter {(Name -like "Department")} -ResultSetSize 1).DistinguishedName
Or change the Filter so that it matches only one OU. I assume you're using -like because you're using a wildcard in your actual code, so you probably just have to be more specific.
Update: If you want users from all the matched OUs, then you can use ForEach-Object:
Get-ADOrganizationalUnit -Filter {(Name -like "Department")} |
ForEach {
Get-ADUser -Filter * -SearchBase $_.DistinguishedName -Properties Name
}

Target all users in two OU's and remove Distribution Lists

hoping to get a little help here – I looked around the site but didn’t see anything quite like this (please direct me if there IS and I missed it).
I need to incorporate a new step in our user offboarding process, which would remove them from any AD Distribution Lists. I would like to set this up as a scheduled task to run once a night against two OU’s where the inactivated user accounts can be found.
I’d like to run this by pointing it at the USERS instead of the OU where the Distro Lists live, because I suspect that we’ll ultimately get the request to remove these users from OTHER types of group as well.
This snippet will remove AD Distro Lists from a single user, but leave all other types of AD groups alone:
# GroupCategory 0 = Distro List
# GroupCategory 1 = Security Group
# GroupScope 0 = DomainLocal
# GroupScope 1 = Global
# GroupScope 2 = Universal
$user = "userlogon"
Get-ADPrincipalGroupMembership -Identity $user|
Where {$_.GroupCategory -eq 0} |
ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
THIS snippet will look at an OU and return some info (just my example for using a variable with -searchbase):
$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$OU | ForEach {Get-ADGroup -Filter * -Properties ManagedBy -SearchBase $_ } |
Select Name, ManagedBy |
Sort -Property Name
Out-GridView
BUT – Does it hold together that in order to complete my objective, I would do something like this?! I'm a bit out of my depth here, any advice for a re-write is appreciated:
$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$user = "*"
$OUs | ForEach {
Get-ADPrincipalGroupMembership -Identity $user|
Where {$_.GroupCategory -eq 0} |
ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
}
There’s always a couple of ways to do stuff in PoSh, so I’m sure there’s a less-complicated way to do the same thing. If anyone has a different approach please feel free to suggest an alternative.
Thanks for taking a look!
So it sounds like you need three loops.
First, you will need to loop over the OU list to get the Users. We'll store the user objects in $Users
$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$Users = ForEach ($OU in $OUs) {
Get-ADUser -Filter * -SearchBase $OU
}
Next loop over the users to get the groups that you want to remove. Then loop over the groups to remove each one.
ForEach ($User in $Users) {
Get-ADPrincipalGroupMembership -Identity $user |
Where-Object {$_.GroupCategory -eq 0} |
ForEach-Object {
Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_
}
}
I think I'd take this a little differently, by getting the group membership of all users, then grouping by AD group, and processing each group that way. Seems like it would be a lot fewer calls to AD. So I'd start out getting all of the users, just like BenH, except I would include their MemberOf property. Then I'd build a list of potential groups and filter down to just the Distribution Lists. I'd make a Hashtable of those as the keys, and make the value an array of each user that is in that group. Then loop through that removing the value of each from the associated key.
$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$Users = ForEach ($OU in $OUs) {
Get-ADUser -Filter * -SearchBase $OU -Properties MemberOf
}
$UsersByGroup = #{}
ForEach($Group in ($Users.MemberOf | Select -Unique | Get-ADGroup | Where{ $_.GroupCategory -eq 0 })) {
$UsersByGroup.Add($Group.DistinguishedName,($Users | Where{ $Group.DistinguishedName -in $_.MemberOf}))
}
$UsersByGroup.Keys | ForEach{
Remove-ADGroupMember -Identity $_ -Members $UsersByGroup[$_] -Confirm:$false
}

Get-AdUsers in a for-each loop with appended characters in powershell

I'm trying to get a (one line) answer to get a list of users (based on a filter of get-aduser) then use that list to do a search matching on an extended version of their name - e.g. I have:
UserA
UserB
UserAAdmin
UserBAdmin
and want to find (when user A is disabled) the UserAAdmin. This seemed like it would be simple, but I can't seem to use the SAMACCOUNTNAME with a like or equals statement no matter what I try- i.e.
Get-ADUser -Filter {Enabled -eq $false} -Properties sAMAccountName |
ForEach {Get-AdUser -Filter {samaccountname -like ($_.samaccountname + "Admin")}}
(as for the why, well, because the client I'm working with has a structure such that all their user accounts have ADMIN added to the end of their admin accounts and we want to find any disabled USER accounts and find (and then disable) the associated admin account).
Thanks
The answer of Avshalom is correct, but it is not efficient and useless to queries your AD twice ...
Once you have all your disabled users then you can just filter
$Users = Get-ADUser -Filter {Enabled -eq $false}
Foreach ($User in $Users)
{
$Match = "ADM-"+$User.SamAccountName
$Users|?{$_.samaccountname -like $match}
}
If i understand you right, you can try this...
$DisabledUsers = Get-ADUser -Filter {Enabled -eq $false}
Foreach ($User in $DisabledUsers)
{
$Match = $User.SamAccountName + '*'
$MatchedUsers = Get-AdUser -Filter {samaccountname -like $match}
foreach ($MatchUser in $MatchedUsers)
{
"You Can do here what you want"
}
}

Powershell Combine Get-ADUser Results

I have a script used to manage group memberships, but am running into a challenge when it comes to searching multiple OU's.
Currently, within the script, I have the following code used to query AD:
$Users = Get-ADUser -LDAPFilter $LDAPString -SearchBase $SearchOU
(...)
Foreach ($User in $Users)
{
If ($User.distinguishedName -notin $Members.distinguishedName)
{
Add-ADGroupMember -Identity $GroupDN -Members $User.distinguishedName -Server $DomainController
}
}
So far, I have tried the following, where $OU is an array of OU's, but I end up with just the first result.
Foreach ($OU in $SearchOUs)
{
$Users += Get-ADUser -LDAPFilter $LDAPString -SearchBase $OU
}
Is there an easy way to combine the resulting hash tables or is it best to simply create a new hash table and add results to that?
Your second attempt is close. Try adding $Users = #() before the Foreach. The += operator is overloaded, so it can pick the wrong operation. Initializing the variable to an empty array makes it clear what you want:
$Users = #()
Foreach ($OU in $SearchOUs)
{
$Users += Get-ADUser -LDAPFilter $LDAPString -SearchBase $OU
}
Also, it's an array, not a hashtable. Those are distinct.

Get organization Job title in AD using powershell

I have been searching everywhere, and have tried many different combinations, but I can't seem to figure out how to get the "Job title" from the organization part of AD.
Here are a few things that I have tried
get-aduser -Filter * -SearchBase "Bob.Barker" -Properties sAMAccountName,Title
Get-ADUser -identity "Bob.Barker" -Filter * -Properties title | group title -NoElement
Also, as a bonus question how would you set the job title.
Thank you all for your assistance.
In your example, if the user's username is Bob.Barker then use this:
get-aduser -Filter {samAccountName -eq "Bob.Barker"} -Properties sAMAccountName,Title
or if surname is Barker
get-aduser -Filter {sn -eq "Barker"} -Properties sAMAccountName,Title
(old thread I'm aware, I'm just happy I know the answer to some of these questions - hopefully help out the next guy/gal that needs this reference quickly)
These chunks of powershell are correct:
get-aduser -Filter {samAccountName -eq "Bob.Barker"} -Properties sAMAccountName,Title
(looking up by SamAccountname, a little more accurate)
get-aduser -Filter {sn -eq "Barker"} -Properties sAMAccountName,Title
(Looking up by surname/lastname, if you have a big AD you'll have a lot of results to go through)
The other question above was
Also, as a bonus question how would you set the job title.
Here it is below:
Get-aduser -identity bob.barker | set-aduser -replace #{title="New Job Title"} -whatif
I like using the -whatif, just in case something goes terribly wrong and I make the CEO the janitor or something.
And here you commit it: Notice, you find the user first with get-aduser, then in the pipe |, you set-aduser with the new value between the #{} braces
Get-aduser -identity bob.barker | set-aduser -replace #{title="New Job Title"}
And here's a bonus answer. If you want to export a whole bunch of users with the same title who need a new title, export your search results into a CSV:
Get-Aduser -filter 'Title -like "Old Job Title"' -Properties * | select samaccountname | Export-csv "C:\some_path\change_these_titles_samaccountnames.csv"
The exported CSV will only have the SamAccountnames that match that job title you're looking for (in this case "Old Job Title").
Now, create a few $variables to store the new job title, the CSV to import, and the samaccountname, and a for-loop to look at the CSV File.
$Set_Title=Import-CSV "C:\some_path\change_these_titles_samaccountnames.csv"
$New_Title="New Title for everyone in CSV file"
foreach ($User in $Set_Title) {
$User.sAMAccountName
Set-ADUser -Identity $User.sAMAccountName -Title $New_Title
}
you could even put a count variable outside the for-loop to show how many users were updated:
$total = ($Set_Title).count
$total
Write-Host "AD User Titles have been updated..."
Hope this helps the next person out!
Use this to get all the information you need, like title related or organizational info
Get-ADUser -Filter {samAccountName -like "*bla*"} -Properties *