Yearly roll-up of student AD accounts - powershell

I have created an automated script on a made up server that will be run once a year the intention is students within a year level to transfer to the next year and add the new memberships whilst deleting the old year level.
This issue is that when I separate the script into 3 scripts it works without any issues. but, when I amalgamate them into the same PowerShell script the profiles don't move to the new OU all the memberships change.
import-module ActiveDirectory
$properties = #('Name', 'Enabled', 'HomeDirectory', 'DistinguishedName')
$dc = 'DC1.unisa.local' # EDIT LINE BETWEEN -> ''
$our = 'OU=test 1,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$ou1 = 'OU=test 2,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$ou2 = 'OU=test 3,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$ou3 = 'OU=test 4,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$ou4 = 'OU=test 5,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$ou5 = 'OU=test 6,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$ou6 = 'OU=test 7,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$oud = 'OU=del,OU=USR,DC=unisa,DC=local' # EDIT LINE BETWEEN -> ''
$adGroupNamer = 'Reception' # EDIT LINE BETWEEN -> ''
$adGroupName1 = 'Year1' # EDIT LINE BETWEEN -> ''
$adGroupName2 = 'Year2' # EDIT LINE BETWEEN -> ''
$adGroupName3 = 'Year3' # EDIT LINE BETWEEN -> ''
$adGroupName4 = 'Year4' # EDIT LINE BETWEEN -> ''
$adGroupName5 = 'Year5' # EDIT LINE BETWEEN -> ''
$adGroupName6 = 'Year6' # EDIT LINE BETWEEN -> ''
$adGroupNamed = 'Disabled Account' # EDIT LINE BETWEEN -> ''
$adGroupNames = 'Students' # EDIT LINE BETWEEN -> ''
$adGroupNameu = 'Users1' # EDIT LINE BETWEEN -> ''
$adGroupNamesu = 'Sophos User' # EDIT LINE BETWEEN -> ''
Start-Transcript -OutputDirectory "\\dc1\SYSVOL\unisa.local\scripts" # EDIT LINE BETWEEN -> ""
##DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE##
###############################################################################################################################################
$adUserIdsr = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($our) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIds1 = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou1) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIds2 = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou2) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIds3 = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou3) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIds4 = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou4) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIds5 = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou5) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIds6 = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($ou6) -Properties $properties | Select-object $properties | Sort-Object Name
$adUserIdsd = Get-ADUser -Filter {Enabled -eq "True"} -SearchBase ($oud) -Properties $properties | Select-object $properties | Sort-Object Name
foreach($adUsersd in $adUserIds6)
{
$adGroupMembershipd = Get-ADPrincipalGroupMembership -Identity $($adUsersd.DistinguishedName) -Server $dc
$radGroup6 = Get-ADGroup $adGroupName6
$radGroups = Get-ADGroup $adGroupNames
$radGroupu = Get-ADGroup $adGroupNameu
$radGroupsu = Get-ADGroup $adGroupNamesu
"Removing Active Directory user $($adUsersd.Name) from the following MemerOf $($radGroup6.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsersd.DistinguishedName) -MemberOf $($radGroup6.DistinguishedName) -Server $dc -ErrorAction Stop
"Removing Active Directory user $($adUsersd.Name) from the following MemerOf $($radGroups.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsersd.DistinguishedName) -MemberOf $($radGroups.DistinguishedName) -Server $dc -ErrorAction Stop
"Removing Active Directory user $($adUsersd.Name) from the following MemerOf $($radGroupu.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsersd.DistinguishedName) -MemberOf $($radGroupu.DistinguishedName) -Server $dc -ErrorAction Stop
"Removing Active Directory user $($adUsersd.Name) from the following MemerOf $($radGroupsu.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsersd.DistinguishedName) -MemberOf $($radGroupsu.DistinguishedName) -Server $dc -ErrorAction Stop
"Disabling Active Directory user account $($adUsersd.Name)"
Disable-ADAccount -Confirm:$false -Identity $($adUsersd.DistinguishedName) -Server $dc -ErrorAction Stop
"Moving Active Directory user: $($adUsersd.Name) to the retired group"
Move-ADObject -Identity $($adUsersd.DistinguishedName) -TargetPath $oud
}
foreach($adUsers6 in $adUserIds5)
{
$adGroupMembership6 = Get-ADPrincipalGroupMembership -Identity $($adUsers6.DistinguishedName) -Server $dc
$adGroup6 = Get-ADGroup $adGroupName6
$radGroup5 = Get-ADGroup $adGroupName5
"Removing Active Directory user $($adUsers6.Name) from the following MemerOf $($radGroup5.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers6.DistinguishedName) -MemberOf $($radGroup5.DistinguishedName) -Server $dc -ErrorAction Stop
if($adGroupMembership6 -like $($adGroup6.Name))
{
"$adUsers6.Name is alreay a member of group $($adGroup6.Name)"
}
else
{
"Adding Active Directory user $($adUsers6.Name) the the global security group $($adGroup6.Name)"
Add-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers6.DistinguishedName) -MemberOf $($adGroup6.DistinguishedName) -Server $dc -ErrorAction Stop
}
"Moving Active Directory user: $($adUsers6.Name) to next year level"
Move-ADObject -Identity $($adUsers6.DistinguishedName) -TargetPath $ou6
}
foreach($adUsers5 in $adUserIds4)
{
$adGroupMembership5 = Get-ADPrincipalGroupMembership -Identity $($adUsers5.DistinguishedName) -Server $dc
$adGroup5 = Get-ADGroup $adGroupName5
$radGroup4 = Get-ADGroup $adGroupName4
"Removing Active Directory user $($adUsers5.Name) from the following MemerOf $($radGroup4.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers5.DistinguishedName) -MemberOf $($radGroup4.DistinguishedName) -Server $dc -ErrorAction Stop
if($adGroupMembership5 -like $($adGroup5.Name))
{
"$adUsers5.Name is alreay a member of group $($adGroup5.Name)"
}
else
{
"Adding Active Directory user $($adUsers5.Name) the the global security group $($adGroup5.Name)"
Add-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers5.DistinguishedName) -MemberOf $($adGroup5.DistinguishedName) -Server $dc -ErrorAction Stop
}
"Moving Active Directory user: $($adUsers5.Name) to next year level"
Move-ADObject -Identity $($adUsers5.DistinguishedName) -TargetPath $ou5
}
foreach($adUsers4 in $adUserIds3)
{
$adGroupMembership4 = Get-ADPrincipalGroupMembership -Identity $($adUsers4.DistinguishedName) -Server $dc
$adGroup4 = Get-ADGroup $adGroupName4
$radGroup3 = Get-ADGroup $adGroupName3
"Removing Active Directory user $($adUsers4.Name) from the following MemerOf $($radGroup3.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers4.DistinguishedName) -MemberOf $($radGroup3.DistinguishedName) -Server $dc -ErrorAction Stop
if($adGroupMembership4 -like $($adGroup4.Name))
{
"$adUsers4.Name is alreay a member of group $($adGroup4.Name)"
}
else
{
"Adding Active Directory user $($adUsers4.Name) the the global security group $($adGroup4.Name)"
Add-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers4.DistinguishedName) -MemberOf $($adGroup4.DistinguishedName) -Server $dc -ErrorAction Stop
}
"Moving Active Directory user: $($adUsers4.Name) to next year level"
Move-ADObject -Identity $($adUsers4.DistinguishedName) -TargetPath $ou5
}
foreach($adUsers3 in $adUserIds2)
{
$adGroupMembership3 = Get-ADPrincipalGroupMembership -Identity $($adUsers3.DistinguishedName) -Server $dc
$adGroup3 = Get-ADGroup $adGroupName3
$radGroup2 = Get-ADGroup $adGroupName2
"Removing Active Directory user $($adUsers3.Name) from the following MemerOf $($radGroup2.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers3.DistinguishedName) -MemberOf $($radGroup2.DistinguishedName) -Server $dc -ErrorAction Stop
if($adGroupMembership3 -like $($adGroup3.Name))
{
"$adUsers3.Name is alreay a member of group $($adGroup3.Name)"
}
else
{
"Adding Active Directory user $($adUsers3.Name) the the global security group $($adGroup3.Name)"
Add-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers3.DistinguishedName) -MemberOf $($adGroup3.DistinguishedName) -Server $dc -ErrorAction Stop
}
"Moving Active Directory user: $($adUsers3.Name) to next year level"
Move-ADObject -Identity $($adUsers3.DistinguishedName) -TargetPath $ou3
}
foreach($adUsers2 in $adUserIds1)
{
$adGroupMembership2 = Get-ADPrincipalGroupMembership -Identity $($adUsers2.DistinguishedName) -Server $dc
$adGroup2 = Get-ADGroup $adGroupName2
$radGroup1 = Get-ADGroup $adGroupName1
"Removing Active Directory user $($adUsers2.Name) from the following MemerOf $($radGroup1.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers2.DistinguishedName) -MemberOf $($radGroup1.DistinguishedName) -Server $dc -ErrorAction Stop
if($adGroupMembership2 -like $($adGroup2.Name))
{
"$adUsers1.Name is alreay a member of group $($adGroup2.Name)"
}
else
{
"Adding Active Directory user $($adUsers2.Name) the the global security group $($adGroup2.Name)"
Add-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers2.DistinguishedName) -MemberOf $($adGroup2.DistinguishedName) -Server $dc -ErrorAction Stop
}
"Moving Active Directory user: $($adUsers2.Name) to next year level"
Move-ADObject -Identity $($adUsers2.DistinguishedName) -TargetPath $ou2
}
foreach($adUsers1 in $adUserIdsr)
{
$adGroupMembership1 = Get-ADPrincipalGroupMembership -Identity $($adUsers1.DistinguishedName) -Server $dc
$adGroup1 = Get-ADGroup $adGroupName1
$radGroupr = Get-ADGroup $adGroupNamer
"Removing Active Directory user $($adUsers1.Name) from the following MemerOf $($radGroupr.Name)"
Remove-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers1.DistinguishedName) -MemberOf $($radGroupr.DistinguishedName) -Server $dc -ErrorAction Stop
if($adGroupMembership1 -like $($adGroup1.Name))
{
"$adUsers1.Name is alreay a member of group $($adGroup1.Name)"
}
else
{
"Adding Active Directory user $($adUsers1.Name) the the global security group $($adGroup1.Name)"
Add-ADPrincipalGroupMembership -Confirm:$false -Identity $($adUsers1.DistinguishedName) -MemberOf $($adGroup1.DistinguishedName) -Server $dc -ErrorAction Stop
}
"Moving Active Directory user: $($adUsers1.Name) to next year level"
Move-ADObject -Identity $($adUsers1.DistinguishedName) -TargetPath $ou
}

Related

List of Active Directory groups not showing from PowerShell code

I input a list of groups for each user in CSV, and tried to create users using PowerShell code.
This is the PowerShell code:
- name: Change group for AD users
ansible.windows.win_powershell:
script: |
[CmdletBinding()]
param (
[array]
$datalist
)
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups
$users = Get-ADUser -Filter "SamAccountName -eq '$name'"
Get-ADUser -Filter "SamAccountName -eq '$name'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
Add-ADGroupMember -Identity $groups -Members $users
}
parameters:
datalist: "{{ hostvars.localhost.list }}"
I ended up getting this error:
"message": "Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter 'Identity'. Specified method is not supported."
Also tried '$groups':
"message": "Cannot find an object with identity: '$groups' under: 'DC=adexample,DC=local'.",
And "$groups":
"message": "Cannot find an object with identity: 'CN=GroupA,OU=Groups,DC=adexample,DC=local CN=Test Group,OU=Groups,DC=adexample,DC=local' under: 'DC=adexample,DC=local'.",
This is how I input my list of groups into the CSV file:
Groups
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
What is the right way to write $groups so that my list of groups can be output correctly?
Updated with CSV in plain text:
FirstName,SamAccountName,path,UserPrincipalName,Groups
Greg,gre.b87,"OU=Temporary Users,DC=adexample,DC=local",gre.b87#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
Zee,zeef.cd,"OU=Temporary Users,DC=adexample,DC=local",zeef.cd#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
I adapted bhuvanachand komara's to mine and it worked for me:
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups -split ";"
Get-ADUser -Filter "SamAccountName -eq '$samname'"
$users = Get-ADUser -Filter "SamAccountName -eq '$samname'"
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $user
}
Get-ADUser -Filter "SamAccountName -eq '$samname'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
}
The main thing is that I need to add $groups = $user.Groups -split ";" and another foreach loop for the groups.
$csvFile = 'path\to\csv\file.csv'
$users = Import-Csv -Path $csvFile
foreach ($user in $users) {
$samAccountName = $user.SamAccountName
$givenName = $user.GivenName
$surname = $user.Surname
$password = $user.Password
$email = $user.Email
$groups = $user.Groups -split ","
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-ADUser -SamAccountName $samAccountName -GivenName $givenName -Surname $surname -DisplayName "$givenName $surname" -EmailAddress $email -AccountPassword $securePassword -Enabled $true
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $samAccountName
}
}
Example CSV
SamAccountName,GivenName,Surname,Password,Email,Groups
user1,chand,komara,Password1,user1#example.com,group1,group2
user2,bhuvan,unnava,Password2,user2#example.com,group2,group3
For each user in the $users array, the code creates a new Active Directory user using the New-ADUser cmdlet with the specified SamAccountName,
GivenName, Surname, DisplayName, EmailAddress, and account password.
It then adds the user to the specified groups using the Add-ADGroupMember cmdlet.

Issue With Powershell Loop Iteration

When attempting to run the below code it appears that it's running through my initial foreach loop twice. What am I not seeing? I appreciate any help.
$DC = Get-ADDomainController
$OUs = Get-ADOrganizationalUnit -Filter 'Name -eq "test"'
$TimeStamp = get-date -format D
$description = "Disabled on " + $TimeStamp
$canNotDisableUser = Get-ADGroupMember -Identity DoNotDisableUsers -Recursive | Select -ExpandProperty Name
$accounts = $null
# Search for User Accounts inactive for XX Days and Disable if not in DoNotDisable Security Group
$accounts = Search-ADAccount -SearchBase $OU -AccountInactive -TimeSpan ([timespan]90d) -UsersOnly
foreach($account in $accounts){
If ($canNotDisableUser -notmatch $account.Name){
Disable-ADAccount -Identity $account.DistinguishedName -Verbose
}
# Disable Protected from Accidental Deletion from OU
Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $OU.DistinguishedName -Server $DC | Set-ADObject -ProtectedFromAccidentalDeletion:$false -Verbose -WhatIf
# Move Disabled Users to Disabled Users OU & Add Timestamp to Description
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $OU.DistinguishedName | Foreach-object {
Set-ADUser $_ -Description $description -Verbose -WhatIf
Move-ADObject $_ –TargetPath “OU=Disabled Users, DC=xxx,DC=net” -Verbose -WhatIf
}
# Enable Protected from Accidental Deletion from OU
Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $OU.DistinguishedName -Server $DC | Set-ADObject -ProtectedFromAccidentalDeletion:$true -Verbose -WhatIf
}
One of the things that will save you LOTS of time in troubleshooting these kinds of issues is "indentation". Make it a habbit of always making sure they are indented correctly.
# Search for User Accounts inactive for XX Days and Disable if not in DoNotDisable Security Group
$accounts = Search-ADAccount -SearchBase $OU -AccountInactive -TimeSpan ([timespan]90d) -UsersOnly
foreach($account in $accounts){
If ($canNotDisableUser -notmatch $account.Name){
Disable-ADAccount -Identity $account.DistinguishedName -Verbose
}
### YOU probably intend to close the foreach loop here. If so, Move the LAST brace to this place.
# Disable Protected from Accidental Deletion from OU
Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $OU.DistinguishedName -Server $DC | Set-ADObject -ProtectedFromAccidentalDeletion:$false -Verbose -WhatIf
# Move Disabled Users to Disabled Users OU & Add Timestamp to Description
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $OU.DistinguishedName | Foreach-object {
Set-ADUser $_ -Description $description -Verbose -WhatIf
Move-ADObject $_ –TargetPath “OU=Disabled Users, DC=xxx,DC=net” -Verbose -WhatIf
}
# Enable Protected from Accidental Deletion from OU
Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $OU.DistinguishedName -Server $DC | Set-ADObject -ProtectedFromAccidentalDeletion:$true -Verbose -WhatIf
}
Corrected
# Search for User Accounts inactive for XX Days and Disable if not in DoNotDisable Security Group
$accounts = Search-ADAccount -SearchBase $OU -AccountInactive -TimeSpan ([timespan]90d) -UsersOnly
foreach($account in $accounts){
If ($canNotDisableUser -notmatch $account.Name){
Disable-ADAccount -Identity $account.DistinguishedName -Verbose
}
}
# Disable Protected from Accidental Deletion from OU
Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $OU.DistinguishedName -Server $DC | Set-ADObject -ProtectedFromAccidentalDeletion:$false -Verbose -WhatIf
# Move Disabled Users to Disabled Users OU & Add Timestamp to Description
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $OU.DistinguishedName | Foreach-object {
Set-ADUser $_ -Description $description -Verbose -WhatIf
Move-ADObject $_ –TargetPath “OU=Disabled Users, DC=xxx,DC=net” -Verbose -WhatIf
}
# Enable Protected from Accidental Deletion from OU
Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $OU.DistinguishedName -Server $DC | Set-ADObject -ProtectedFromAccidentalDeletion:$true -Verbose -WhatIf

How to fix cannot convert system.object[] error

I am receiving the following error when running this script:
Get-ADGroupMember : Cannot convert 'System.Object[]' to the type
'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter
'Identity'. Specified method is not supported.
Also, the users move from the Win7 group to the Win10 group, but depending on if they are members of the other groups in the if statements, none of the groups in the if statements are moving for any of the users. Please help.
Just for reference the userlist file contains Active Directory usernames in a text file like this:
jsmith
ksmith
etc.
The grouplist text file contains Active Directory groups like this:
Nitro7
Project7
Visio7
Zoom7
SnagIt7
OneNote7
Code:
Import-Module ActiveDirectory
$users = Get-Content -Path .\userlist.txt
$group = Get-Content -Path .\grouplist.txt
$members = Get-ADGroupMember -Identity $group -Recursive
foreach ($user in $users){
Remove-ADGroupMember -Identity "Win7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Win10" -Members $user -Confirm:$false -Verbose
If ($members.SamAccountName -contains $user) {
Remove-ADGroupMember -Identity "Nitro7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Nitro10" -Members $user -Confirm:$false -Verbose
}
If ($members.SamAccountName -contains $user) {
Remove-ADGroupMember -Identity "Project7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Project10" -Members $user -Confirm:$false -Verbose
}
If ($members.SamAccountName -contains $user) {
Remove-ADGroupMember -Identity "OneNote7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "OneNote10" -Members $user -Confirm:$false -Verbose
}
If ($members.SamAccountName -contains $user) {
Remove-ADGroupMember -Identity "Zoom7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Zoom10" -Members $user -Confirm:$false -Verbose
}
If ($members.SamAccountName -contains $user) {
Remove-ADGroupMember -Identity "SnagIt7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "SnagIt10" -Members $user -Confirm:$false -Verbose
}
If ($members.SamAccountName -contains $user) {
Remove-ADGroupMember -Identity "Visio7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Visio10" -Members $user -Confirm:$false -Verbose
}
}
The -Identity property of Get-ADGroupMember is a singleton, not an array.
However, the -Identity property does accept the pipeline for input. So, you may be able to do something like this:
$members = $group | Get-ADGroupMember -Recursive
Although, IMX, some of the AD commands are a bit wonky due to their age. I expect you may need to do something like this:
$members = foreach ($g in $group) { Get-ADGroupMember -Identity $g -Recursive }
The rest of your script has kind of a confused logic, however, so I can't really tell what you're intending to do.
{snip}
Based on your comments, here's what I'd do.
First, I'd change your groups file. Instead of a plain text list of the groups, I'd make it a CSV file with two columns: The old group and the new group.
So, grouplist.csv looks like this:
"OldGroupName","NewGroupName"
"Nitro7","Nitro10"
"OneNote7","OneNote10"
"Project7","Project10"
"SnagIt7","SnagIt10"
"Visio7","Visio10"
"Win7","Win10"
"Zoom7","Zoom10"
Now you have a map for each old group and the group you want to migrate your users to.
Now, we do it like this:
$users = Get-Content .\userlist.txt
$groups = Import-Csv .\grouplist.csv
foreach ($group in $groups) {
$UsersToModify = Get-ADGroupMember $group.OldGroupName -Recursive | Where-Object SamAccountName -in $users
Remove-ADGroupMember -Identity $group.OldGroupName -Members $UsersToModify -Confirm:$false -Verbose -WhatIf
Add-ADGroupMember -Identity $group.NewGroupName -Members $UsersToModify -Confirm:$false -Verbose -WhatIf
}
[Note: Remove the -WhatIf to actually perform the actions.]
For each group, we get a list of the groups members, filter it to the usernames in $users and save that to $UsersToModify. Then, we pass that list of users to the Remove and Add commands. We only need to call it once per each group.
I know you had a special exception for Win7 to Win10, but I don't see where the logic of the script really needs to change to accommodate that. If you want to always add all users in $users to Win10, you could add that manually:
$UsersToAddtoWin10 = $users | Get-ADUser
Add-ADGroupMember -Identity Win10 -Members $UsersToAddtoWin10 -Confirm:$false -Verbose -WhatIf
Import-Module ActiveDirectory
$users = Get-Content -Path .\userlist.txt
foreach ($user in $users){
Remove-ADGroupMember -Identity "View_Win7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "View_Win10" -Members $user -Confirm:$false -Verbose
[array]$grps=Get-ADUser $user -Property memberOf | Select -ExpandProperty memberOf | Get-ADGroup | Select Name
foreach($grp in $grps){
if($grp.Name -match "Nitro7") {
Remove-ADGroupMember -Identity "Nitro7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Nitro10" -Members $user -Confirm:$false -Verbose
}
If ($grp.Name -match "Project7") {
Remove-ADGroupMember -Identity "Project7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Project10" -Members $user -Confirm:$false -Verbose
}
If ($grp.Name -match "OneNote7") {
Remove-ADGroupMember -Identity "OneNote7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "OneNote10" -Members $user -Confirm:$false -Verbose
}
If ($grp.Name -match "Zoom7") {
Remove-ADGroupMember -Identity "Zoom7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Zoom10" -Members $user -Confirm:$false -Verbose
}
If ($grp.Name -match "SnagIt7") {
Remove-ADGroupMember -Identity "SnagIt7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "SnagIt10" -Members $user -Confirm:$false -Verbose
}
If ($grp.Name -match "Visio7") {
Remove-ADGroupMember -Identity "Visio7" -Members $user -Confirm:$false -Verbose
Add-ADGroupMember -Identity "Visio10" -Members $user -Confirm:$false -Verbose
}
}
}
Let's see if this will work for you, considering your $user and $group lists are exactly as you show...
#get your users...
$users = Get-Content -Path .\userlist.txt
#get your groups...
$groups = Get-Content -Path .\grouplist.txt
#for each user...
foreach ($user in $users) {
#get their group memberships, expand the property...
$memberOf = Get-ADUser -Identity $user -Properties MemberOf | Select -ExpandProperty memberof
#for each membership found in $groups that also ends in '7'...
foreach ($membership in ($memberOf | Where-Object {($_ -match ($groups -join "|")) -and ($_ -like '*7')})) {
#remove the user from the matched group...
Remove-ADGroupMember -Identity $membership -Members $user -Confirm:$false
#add the user to a group with the same name, replacing 7 with 10...
Add-ADGroupMember -Identity $membership.Replace("7","10") -Members $user -Confirm:$false
}
}
IMPORTANT
Please note that this -match operator will return any other groups that are contained in $groups that also end in 7. If you have additional group names that match that criteria stored in $groups, you will want more filtering on $memberOf for the $membership iteration.
This script will also replace every instance of the character '7' in $membership (a matched group's DistinguishedName), with '10', in order to add $user to the new group. So, make sure that isn't a problem.

powershell delete aduser groupmemberchip of other childdomain

script should delete a ADUser of all of his Groupmemberchips (including memberships in forestdomain and other childdomains), deactivate it and move it into another OU.
environment:
forest-domain: forest.com
child-domains: child1.forest.com
child2.forest.com
child3.forest.com
script is running in child1.forest.com
this is the script so far:
$username="testuser"
$groups=Get-ADPrincipalGroupMembership -Identity $username | where {$_.name -notlike "Domain Users"}
$getuser=Get-ADUser -Identity $username | select DistinguishedName
$userpath=$getuser.DistinguishedName
foreach ($group in $groups) {
Remove-ADGroupMember -Identity $group -member $username -Confirm:$false
}
Disable-ADAccount -Identity $username
Move-ADObject "$userpath" -TargetPath "OU=Deaktivierte Benutzer,DC=child1,DC=forest,DC=com"
actually it successfull deletes all group-memberchips of child1.forest.com but not of forest.com or child2.forest.com
This code is working properly:
$User=Get-ADUser "testuser" -server "child1.forest.com"
$Group=Get-ADGroup "SomeGroup" -server "forest.com"
Remove-ADGroupMember $Group -Members $user -server "forest.com" -Confirm:$false
I tried to combine these script-snippets but not yet successful.
I have an idea... to read the domain of the OU and pass it into the loop, but I dont get it working to read the OU in a way that I can use it.
Can someone help please?
found a solution, I query if the group exist in server:
$found=0
$servers=#("forest.com","child1.forest.com","child2.forest.com","child3.forest.com")
$username="testuser"
$user=Get-ADUser -Identity $username
$groups=Get-ADPrincipalGroupMembership -Identity $user | where {$_.name -notlike "Domain Users"}
foreach ($group in $groups) {
foreach ($server in $servers) {
$groupname=$group.name
$groupserver=Get-ADGroup $groupname -server $server
if($groupserver)
{
$group=Get-ADGroup $groupname -server $server
Remove-ADGroupMember $Group -Members $user -Confirm:$false -ErrorAction SilentlyContinue
$found=1
}
if ($found -eq 1){break}
}
}

If And statement with a foreach for AD Users in Powershell

$names = Import-CSV C:\PowerShell\TerminatedEmployees.csv
$Date = Get-Date
foreach ($name in $names)
{
Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" | select Name | Out-File "C:\Powershell\ADUserMemberships\$($name.TextBox37)Memberships.txt"
$ADgroups = Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" | where {$_.Name -ne "Domain Users"}
Remove-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" -MemberOf $ADgroups -Confirm:$false
Disable-ADAccount -Identity "$($name.TextBox37)"
Get-ADUser -Identity "$($name.TextBox37)" | Move-ADObject -TargetPath "OU=DisabledAccounts,OU=XXX,DC=XXX,DC=XXXX,DC=XXX"
Set-ADUser -Identity "$($name.TextBox37)" -Description "Disabled $Date"
}
This is an already working script I have. However, I realized I need to check 2 properties on the AD user to determine if they need to need to go through my foreach statement. Both properties need to be met. If they are then there's no reason for the AD users to be processed.
The AD user is already disabled.
The AD user already resides in the Disabled OU.
I'm thinking this needs to be done in an If -And statement. But does this need to be done before the foreach or inside the foreach?
Start out by retrieving the user account with Get-ADUser and then inspect the Disabled property + compare the Disabled OU to the DistinguishedName of the user:
$names = Import-CSV C:\PowerShell\TerminatedEmployees.csv
$Date = Get-Date
$DisabledOU = "OU=DisabledAccounts,OU=XXX,DC=XXX,DC=XXXX,DC=XXX"
foreach ($name in $names)
{
$ADUser = Get-ADUser -Identity "$($name.TextBox37)"
if(-not($ADUser.Enabled) -and $ADUser.DistinguishedName -like "*,$DisabledOU")
{
# no need to proceed, skip to next name in foreach loop
continue
}
$ADGroups = Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)"
$ADGroups |Select-Object Name |Out-File "C:\Powershell\ADUserMemberships\$($name.TextBox37)Memberships.txt"
# no need to call Get-ADPrincipalGroupMembership again
$ADgroups = $ADGroups | where {$_.Name -ne "Domain Users"}
Remove-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" -MemberOf $ADgroups -Confirm:$false
Disable-ADAccount -Identity "$($name.TextBox37)"
$ADUser | Move-ADObject -TargetPath $DisabledOU
Set-ADUser -Identity "$($name.TextBox37)" -Description "Disabled $Date"
}