Add all Security Groups to multiple computer objects - windows

I want to combine these below command to add all Security Groups to multiple computer or user objects. As like
Get-ADPrincipalGroupMembership
Add-ADPrincipalGroupMembership
So that what the Get-ADPrincipalGroupMembership will return from a computer or user object those will add to multiple computers or users object using Add-ADPrincipalGroupMembership. This pull a list of security groups as a Member Of any computer. I want to add those security groups to other few computers as Member Of.
$Host_name = Read-Host "Please enter the host name "
$Host_name = $Host_name.ToUpper()
Write-Host The computer $Host_name has Member Of below security groups. -ForegroundColor White -BackgroundColor DarkBlue
$allgroups = Get-ADComputer -Identity $Host_name -Properties * | Get-ADPrincipalGroupMembership | Select-Object name | Format-Table -HideTableHeaders #| Out-String | ForEach-Object { $_.Trim("`r","`n") }
$allgroups
$New_Hosts = Read-Host "Enter the new host name to be the Member Of same groups "
Get-ADComputer -Identity $New_Hosts
foreach ($nh in $allgroups)
{
#Add-ADPrincipalGroupMembership -Identity $New_Hosts -MemberOf $nh
#Add-ADPrincipalGroupMembership -MemberOf $nh
#Get-ADComputer -Identity $New_Hosts | Add-ADPrincipalGroupMembership -MemberOf $nh
}

Related

In Powershell how can I remove the first x number of characters from Get-ADUser results?

I have a list of results from Get-ADUser giving me all users in an OU. The format of the output username is '-prefix-username'. I need to remove the 7 character '-prefix-' and then conduct another Get-ADUser lookup against the remaining 'username' portions. The issue I'm finding is that if I run just the second Get-ADUser lookup where I set $User as just one specific '-prefix-username' it works fine but when I try to process a list I either get an error where there seems to be space after the trimmed username (txt format list - Get-ADUser : Cannot find an object with identity: 'user ' under:) or the username includes a " that I can't remove from the end of the username (csv format list - Get-ADUser : Cannot find an object with identity: 'user"').
So far I have:
get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 |
Select SAMAccountName |
Out-File C:\Temp\UserList.txt
$UserList = (Get-Content C:\Temp\UserList.txt)
$StandardUsers = ForEach($User in $UserList) {
Write-Host "Now checking $User"
Get-ADUser $User.Substring(7) -Properties * |
Select-object DisplayName, UserPrincipalName, Mail, Manager,EmployeeID
}
$StandardUsers | Out-File -FilePath C:\Temp\StandardUserList.txt
First thing to mention is that if you create the list using Select -ExpandProperty SAMAccountName, you would only get SamAccountnames in the file.
Having said that, why bother with an 'in-between' file at all and simply do:
# By default, Get-ADUser returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# Only ask for properties that are not already in this list.
Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 -Properties DisplayName, EmailAddress, Manager, EmployeeId |
Select-Object DisplayName, UserPrincipalName, EmailAddress, Manager,EmployeeID |
Set-Content -Path 'C:\Temp\StandardUserList.txt'
You are likely having issues with saving it to a file (where it gets formatted) and then reading it back in. The formatting could be adding " and reading a newline (which you think is a space) character. If you really need to save it then do the following (else just hook up the pipelines):
$userList = Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 |
Select-Object SAMAccountName
$userList |
Out-File C:\Temp\UserList.txt
$standardUsers = $userList |
Select-Object -ExpandProperty SAMAccountName -PipelineVariable user |
ForEach-Object {
Write-Host "Now checking $user"
$userWithoutPrefix = ($user -Replace '^-prefix-','') -Replace '(\w|\n)$','' # to use a more advanced version of the suggestion by #Avshalom
Get-ADUser $userWithoutPrefix -Properties * | Write-Output
} |
Select-Object DisplayName, UserPrincipalName, Mail, Manager, EmployeeID
$standardUsers | Out-File -FilePath C:\Temp\StandardUserList.txt

How do I remove all the groups from disabled Active Directory Users via Powershell?

I'm trying to gather all the disabled users in our Active Directory and trying to remove the disabled users from all their groups. Mostly for cleanup purposes. I'm a bit stuck on my script. I'm not sure what to put after Remove-ADPrincipalGroupMembership:
$disabled_users = Get-AdUser -SearchBase "Ou=Users, Ou=test, DC=testdomain, DC=io" -Filter
"enabled -eq 'false'"
foreach($person in $disabled_users) {
Get-ADPrincipalGroupMembership $person | Remove-ADPrincipalGroupMembership #stuckhere
}
Get-ADPrincipalGroupMembership returns only groups, leading Remove-ADPrincipalGroupMembership to auto-fill -Identity with the group name. You'll have to re-use the user object in -Identity.
Because of the first issue, Remove-ADPrincipalGroupMembership doesn't accept multiple groups from the pipeline. It should normally, but the [ADGroup] objects returned by Get-ADPrincipalGroupMembership seem to trip it up. To fix, use a ForEach loop, or use a two-step process:
# two steps:
$groups = Get-ADPrincipalGroupMembership $person
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $groups -WhatIf
# OR foreach loop:
Get-ADPrincipalGroupMembership $person |
Foreach {
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $_
}
Note that you can't remove an AD user's primary group (usually 'Domain Users'), so you may want to add a filter:
$groups = Get-ADPrincipalGroupMembership $person |
Where Name -notlike 'Domain Users'
Remove-ADPrincipalGroupMembership -Identity $person -MemberOf $groups
Adding another option using Remove-ADGroupMember instead:
Get-ADPrincipalGroupMembership $person | Remove-ADGroupMember -Members $person
Remove-ADGroupMember will take the distinguishedNames of the user's membership as pipeline value so you only need to specify the Member of the group you want to remove.

Copy Groups from one user to another in AD, except one specific group

Need help with adding a small comand to finish this pwoershell command.
I have this powershell command that copy groups from one user to another.
Now what i need is to add a command that will "Except" a specific group, like it will copy all the groups except one specific group.
Thanks for help.
Get-ADUser -Identity $Oldusername -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $Newusername
Get-ADUser -Identity $Oldusername -Properties memberof | Select-Object -ExpandProperty memberof | Where-Object { $_ -NotMatch $grouptoexclude } | Add-ADGroupMember -Members $Newusername
$grouptoexclude containing the name of the group you don't want the new user to be added into. It must be a distinguished name like CN=GroupName,OU=Groups,OU=Users & Workstations,DC=Fabrikam,DC=COM

Add-ADGroupMember Syntax

I don't understand what I do wrong:
Get-ADPrincipalGroupMembership UserName | select name | where {$_.name -like "nac*"} | Add-ADGroupMember -Identity **$_.name** -Members UserName
This is the error I get:
Add-ADGroupMember : Cannot validate argument on parameter 'Identity'.
The argument is null. Provide a valid value for the argument, and then
try running the command again.
What should I put in the $_.name?
If you have a value stored in $Username be sure to include the $ character so PowerShell will recognize it as a variable. You also might want to remove the *s from the last cmdlet. This may not work as a one-liner. Try this:
$Group = Get-ADPrincipalGroupMembership $UserName | select name | where {$_.name -eq "nac*"}
Add-ADGroupMember -Identity $Group.Name -Members $UserName
Try this:
$groups = get-adprincipalgroupmembership $sourceuser | ? Name -like "nac*"
#check content of $groups
$groups | select Name
add-adprincipalgroupmembership $targetuser -memberof $groups
I'm sure this will work. Otherwise please post your error message.
You need to take care of the -Identity parameter the cmdlets can handle:
The Identity parameter should be one of:
A distinguished name (DN)
A GUID,
A security identifier (SID) or
A Security Accounts Manager (SAM) account name
Both cmdlets also allow an object to be sent through the pipeline to the Identity parameter.
For Add-ADGroupMember this would be a group object.
For Get-ADPrincipalGroupMembership you can use a user, group, or computer object.
This part of the code returns the group objects $UserName is a member of.
(remember: $UserName is the distinguished name, GUID, security identifier, or SAM account name of the user.)
Get-ADPrincipalGroupMembership $UserName | Where-Object { $_.Name -like "nac*" }
Next you want to add a different user to the groups $UserName is a member of, right?
In that case, set up a variable to store the second user in, again use the distinguished name,
GUID, security identifier, or SAM account name and then use something like this:
Get-ADPrincipalGroupMembership $UserName | Where-Object { $_.Name -like "nac*" } | Add-ADGroupMember -Members $AnotherUserToAddToThisGroup

Check Win32_group membership with powershell

I want to know if a user whom username is delivered is member of a group whom groupname is delivered.
$u = Get-WmiObject -Class Win32_UserAccount -Filter "Name='$username'"
$g = Get-WmiObject -Class Win32_Group -Filter "Name='$groupname'"
So I get two object with the property SID.
How can I check that user $u is member of group $g?
You can do this with an Associators query (example). Which are notoriously slow but do work.
$u = Get-WmiObject -Class Win32_UserAccount -Filter "Name='user'"
$group = Get-WmiObject -Class Win32_Group -Filter "Name='group'" | Select-Object -ExpandProperty Caption
$u | foreach {
$query = “Associators Of {Win32_UserAccount.Domain='” `
+ $_.Domain + “',Name='” + $_.Name `
+ “'} WHERE AssocClass=Win32_GroupUser”
$memberOf = Get-WmiObject -Query $query |
select -ExpandProperty Caption
If($memberOf -contains $group){
Write-Host "$($_.Name) is a member of $group"
} Else {
Write-Host "$($_.Name) is not a member of $group"
}
}
Get the use you are looking for and group your are checking to see if the user is a member of. While u$ should be only one user it is still a collection with one member. Pipe it into a ForEach-Object and build the Associators query. Execute the query and return all the group captions ( domain\groupname). Since $memberof is an array we can use -contains to see if the group you are looking for is there.
Alternatively
You could use the AD cmdlets if you have access to them and run the following
(Get-ADUser $user -Properties memberof | Select-Object -ExpandProperty memberof) -contains (Get-ADGroup -Identity $group)
The above will return True or False. You can install Ad cmdlets by using import-module activedirectory
Continued Testing
OpenLDAP should support this from what I gather and it's much faster then the previous WMI.
$search = [adsisearcher]"(&(objectcategory=user)(Name=userFullName))"
$userLDAP = $search.FindOne().Path
$userMembers = ([ADSI]$userLDAP).memberof
$search = [adsisearcher]"(&(objectcategory=group)(Name=groupname))"
$group = ($search.FindOne().Path) -replace "LDAP://"
$userMembers -contains $group
Sorry as I do not have access to OpenLDAP for testing. Do a search for a user and get the MemberOf as $userMembers. Then get the group into $group. Needed to remove the LDAP prefix from the string. Then just do another -Contains again.

Resources