Adding newly imported users to several groups - powershell

I am new to Powershell... I have also done a lot of "looking", to see if I could find a resolution, before posting this question. While I have found several "close" answers (a good example is: Adding newly created users to pre-existing groups), I have not found one which meets our needs. The issue is wanting to add the new user to several groups at once, and I cannot get the syntax right. I have tried:
Add-ADGroupMember -Identity $_.Group -Members $_.SamAccountName
This works, but only adds one group. I have tried:
Add-ADGroupMember -Identity 'Group1','Group2','Group3' $_.SamAccountName
And
Add-ADGroupMember -Identity "Group1","Group2","Group3" -Members $_.SamAccountName
None of which worked. I have tried $(group1,group2,group3)... I just need help getting the right wording. The script in the picture works just fine, but only gives me 1 group. Please help me figure out how to add multiple groups. (I tried to copy/paste the actual script into this question, and it formats very oddly.
An image of the code which works fine

I'm not terribly familiar with that command, but have you tried either creating a text document with each group name separated by either a , or each new group has its own line?
That way at the start of the script you can say:
$groups = get-content path.txt
and run a foreach loop, like:
foreach ($group in $groups){
Add-ADGroupMember -Identity $group -Members $.SamAccountName}
or if you'd like to input the groups manually, instead of get-content, you can add this at the start of your sctipt:
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,HelpMessage='Enter a list of group names seperated by a
comma, no spaces')]
[string]$List
)

So, your code (the one provided on the screenshot) is fine. It works because you're providing only one group to the -Identity parameter.
Taken from MS Docs:
-Identity
Specifies an Active Directory group object by providing one of the following values.
The identifier in parentheses is the Lightweight Directory Access Protocol (LDAP) display name for the attribute.
The acceptable values for this parameter are:
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A Security Account Manager account name (sAMAccountName)
If you were to add the newly created AD User to multiple groups, you can loop through the Groups and add the user to each one of them.
# In this example you will need to capture $_.sAMAccountName in a variable
$usersAMAccountName = $_.sAMAccountName
"Group1,Group2,Group3".split(',')|foreach{
Add-ADGroupMember -Identity $_ -Members $usersAMAccountName
}
# This is another option
foreach($group in "Group1","Group2","Group3")
{
Add-ADGroupMember -Identity $group -Members $_.samAccountName
}
I would recommend Splatting for New AD User creation, which is something used on the answer provided on the SO link Adding newly created users to pre-existing groups
Specifically this is perfect in my opinion:
try
{
$newADUser = New-ADUser #newUserProperties -PassThru
Add-ADGroupMember -Identity $_.Group -Members $newADUser.SamAccountName
}
catch
{
Write-Warning "Could not create $($newUserProperties.samaccountname)"
}

Related

Remove user from all AD Group Except domain users

Get-Aduser -identity $User -Properties Memberof -filter {Memberof Name -Notlike "Domain Users" | ForEach-Object { $_.Memberof | Remove-ADGroupMember -Members $User -Confirm:$false}}
Hey Yall,
Im trying to remove folks from their AD Groups except for the Domain Users Group in AD (Our company is holding on to AD accounts, idk why, but they want to remove their general accesses.
When I use the above code to remove them it says: "Get-ADUser : Parameter set cannot be resolved using the specified named parameters."
Im not sure what way is a better way to do this.

GET not printing when there is another GET after it?

I've gt this script to automate removal of users for our workplace and I can't figure out why this Get doesn't print anything if there is another get after it. Is this a delay issue? or there a problem with my syntax"
#Requests user input username
$_Name=Read-Host "Enter account name you wish to disable"
#Lists the users AD groups and removes them
Get-ADPrincipalGroupMembership $_Name | select name
Get-ADUser -Identity $_Name -Properties MemberOf -Credential $_Creds| ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Credential $_Creds -Confirm:$false
}
write-host "User has been removed from the listed groups..."
It just returns a blank space where the list should be.
To extrapolate what was mentioned in the comments:
You are currently running two separate Get commands. The first one, Get-ADPrincipalGroupMembership will generate output. It's a list of groups a principal is member of. The second Get command you're running (Get-ADUser) has it's output used in a loop and you're not printing that output. You'd need to do something like Write-Output $_.MemberOf to see it.
You're using $_.MemberOf as another input to the command Remove-ADGroupMember. For that command the documentation states:
Outputs
None or Microsoft.ActiveDirectory.Management.ADGroup
Returns the modified group object when the PassThru parameter is specified. By default, this cmdlet does not generate any output.
So unless you supply the parameter -PassThru it will consume the "output" of $_.MemberOf and not display anything.

Copygroup membership from one group to another powershell

I was hoping someone can point me in the right direction please.
Im trying to do something that should be pretty straight forward i think, but i can;t get it to work or can i find any similar examples. basically, i want to be able to do the following:
Look at an existing Security Group 'Member of' groups and then add those member of groups to another/new group. So for example, group 1 is member of 'A, B, C' groups. Group 2 is memebr of none. I want to copy the membership of Group 1 to Group 2, but NOT users (although if that was a must they could then be removed easily enough.
What i dont need to worry about is any users, or copying groups that users are members of etc.
Thanks
Thanks for that... so if i look at something like:
Add-ADGroupMember -Identity 'TARGETGROUP' -Members (Get-ADGroupMember -Identity 'SOURCEGROUP' -Recursive -Server Server1) -Server Server1
This adds users from Sourcegroup to Targetgroup, but im not worried about users, its the sourcegroups 'Member of' details i want addding to the targetgroup if that makes sense?
I can extract the info from the targetgroup using something like
$Groups = Get-ADGroup -Identity 'SourceGroup' -Properties memberof -Server Server1 | select MemberOf | Format-Table -AutoSize -Wrap
But then cant seem to do much with importing that info into the new group. Hope that makes sense? :)
Thanks for the info: That looks to be trying to add the groups from Source into the Members of section as oppose to the member of section for the groups, if that makes sense? it states 'Add-ADGroupMember : A universal group cannot have a local group as a member' which would suggest its tring to add the groups a s amember of the new group, not into the 'member of' of the new group..
Just wanted to share the following (in crude form) as this doen what i was after:
Get-ADGroup -Identity %SOURCE% -Properties memberof -Server SERVER1 |
Select-Object -ExpandProperty memberof |
Add-ADGroupMember -Members %TARGET% -Server SERVER1
Thanks for your help chaps.

Powershell - Add users to groups without ansi

I am looking for a solution to add users to groups in active directory after I have created their users accounts. Currently my powershell script has a few things lacking but I am going to tackle them one at a time.
In this cycle I trying to learn the best way to add groups to newly created user accounts. Is it best to copy from a template account (which I am having problems doing as I keep getting a blank account... Or should I manage all new user information directly in the script. Which is best practice?
In my research I see how this can be done with adsi.
I was hoping not to use this method unless I have to. what I was hoping for was something like this. with Get-ADUser, Set-ADUser, Set-ADObject, Get-ADObject, or similar commands.
$user=get-aduser 'abc user'
$userModify=Set-aduser $user
$groups=get-aduser $tmplateUser | select -ExpandProperty memberof
# or groups could come from an array, I have not decided which is best.
foreach ($Group In $groups)
{
$usermodify.memberof.add -identity $Group -member $user
}
Does anyone have any suggestions or examples?
if you can use the 'ActiveDirectory' module then you can try:
Import-Module ActiveDirectory
This will show you the cmdlets available for managing groupmembership.
Get-Command -Verb add -Noun *group*
This will show you examples of the cmdlet.
Help cmdletname -examples
There are many ways to create users, most use information stored in a csv file as input to say a cmdlet like New-ADUser.
The foreach construct will depend upon which cmdlet you choose to use.
$groups = Get-ADUser $tmplateUser -Properties memberof |
Select-Object -ExpandProperty memberof
foreach ($group in $groups)
{
Add-ADGroupMember -Identity $group -Members $newuser
}

Powershell Script to search specific OU in AD and find disabled users that is member of a group

I'm trying to write a script to find disabled users that is member of one or more groups in a specific OU in AD. It will then remove all the groups for all the disabled users. I found this script which removes all groups from users in a csv file, but as i'm looking to run this as a scheduled task I prefer not to process users that already had their groups removed without having to move them to a different OU.
Import-Csv $csvFile | ForEach-Object {
# Disable the account
Disable-ADAccount -Identity $_.samAccountName
# Retrieve the user object and MemberOf property
$user = Get-ADUser -Identity $_.samAccountName -Properties MemberOf
# Remove all group memberships (will leave Domain Users as this is NOT in the MemberOf property returned by Get-ADUser)
foreach ($group in ($user | Select-Object -ExpandProperty MemberOf))
{
Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false
}
}
Any idea on how to filter out the users with more then one group?
I'm using this script to export disabled users that has not logged on for 60 days:
Get-QADUser -searchRoot $OuDomain -searchScope OneLevel -InactiveFor 61 -NotLoggedOnFor 61 -disabled -sizelimit 0
Thx
You seem to have filter by ou part down which is good. You have some thoughts in the beginning of you post but the only actual question is how to filter out the users with more then one group. Not sure if that is a typo or not but I read that as checking the count of groups a user has. A more realistic interpretation of that is filter users that could have at least one of a list of groups. I'm going to cover both.
The Count
I'm sure this is not what you want but just want to cover the base. The following would also work in a Where-Object clause
If((get-aduser $user -Properties MemberOf).MemberOf.Count -gt 0){Process...}
Multiple Groups
I'm sure this was your intention. Locate users that could contain one of serveral groups. This is best handled with regex.
$groupsFilter = "citrix_GateKeeper","barracuda_spam_alerts"
$groupsFilter = "($($groupsFilter -join '|'))"
# $groupsFilter in this example is: (citrix_GateKeeper|barracuda_spam_alerts)
If(((Get-ADUser $user -Properties MemberOf).MemberOf) -match $groupsFilter){Process....}
Create a regex match string based on a string array of multiple groups. If $user is a member of either of those groups then true would be returned.
If nothing here is of any use to you then I would suggest making your question clearer. Hopefully this helps.