Issue With Powershell Loop Iteration - powershell

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

Related

get OU Permissions for specific domain

I found a script that give you OU permissions for the domain the script is run on.
I want to use the same script from a single domain but scan other domains I specify.
The problem I think is with $schemaIDGUID = #{}
When run It's always for the domain the script is running on which is different from the domain I want to run the script on.
Here's the script I modified it to pickup specific domain.
$schemaIDGUID = #{}
$domain = "My specific domain name"
$report = #()
$schemaIDGUID = #{}
$ErrorActionPreference = 'SilentlyContinue'
Get-ADObject -Server $domain -SearchBase (Get-ADRootDSE -Server $domain).schemaNamingContext -LDAPFilter '(schemaIDGUID=*)' -Properties name, schemaIDGUID |
ForEach-Object {$schemaIDGUID.add([System.GUID]$_.schemaIDGUID,$_.name)}
Get-ADObject -SearchBase "CN=Extended-Rights,$((Get-ADRootDSE -Server $domain).configurationNamingContext)" -LDAPFilter '(objectClass=controlAccessRight)' -Properties name, rightsGUID |
ForEach-Object {$schemaIDGUID.add([System.GUID]$_.rightsGUID,$_.name)}
$ErrorActionPreference = 'Continue'
$OUs = #(Get-ADDomain -Server $domain | Select-Object -ExpandProperty DistinguishedName)
$OUs += Get-ADOrganizationalUnit -Server $domain -Filter * | Select-Object -ExpandProperty DistinguishedName
$OUs += Get-ADObject -Server $domain -SearchBase (Get-ADDomain -Server $domain).DistinguishedName -SearchScope OneLevel -LDAPFilter '(objectClass=container)' | Select-Object -ExpandProperty DistinguishedName
ForEach ($OU in $OUs) {
$report += Get-Acl -Path "AD:\$OU" |
Select-Object -ExpandProperty Access |
Select-Object #{name='organizationalUnit';expression={$OU}}, `
#{name='objectTypeName';expression={if ($_.objectType.ToString() -eq '00000000-0000-0000-0000-000000000000') {'All'} Else {$schemaIDGUID.Item($_.objectType)}}}, `
#{name='inheritedObjectTypeName';expression={$schemaIDGUID.Item($_.inheritedObjectType)}}, `
*
}
$report | Export-Csv -Path ".\$domain.OU_Permissions.csv" -NoTypeInformation
#Start-Process ".\$domain.OU_Permissions.csv"
break
$report |
Where-Object {-not $_.IsInherited} |
Select-Object IdentityReference, OrganizationalUnit -Unique |
Sort-Object IdentityReference
$filter = Read-Host "Enter the user or group name to search in OU permissions"
$report |
Where-Object {$_.IdentityReference -like "*$filter*"} |
Select-Object IdentityReference, OrganizationalUnit, IsInherited -Unique |
Sort-Object IdentityReference
Your problem has nothing to do with the $schemaIDGUID variable.
The problem is this line:
$report += Get-Acl -Path "AD:\$OU"
The AD: drive is mapped to ADWS on a DC in your home domain, on module import, so you'll need to explicitly create another drive that maps to the target domain instead:
$domain = "other.domain.tld"
# discover naming context + find a DC to query
$defaultNC = (Get-ADRootDSE -Server $domain).defaultNamingContext
$DC = Get-ADDomainController -Server $domain
# map new ADTemp:\ drive
New-PSDrive -Name ADTemp -PSProvider ActiveDirectory -Root $defaultNC -Server $DC
For the rest of the script, the only thing you need to change is the previously mentioned line, to:
$report += Get-Acl -Path "ADTemp:\$OU"

Yearly roll-up of student AD accounts

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
}

Powershell Shadow Groups - Inconsistent Group Membership

I am using Powershell to maintain several shadow groups (a group that mirrors all the users in a specific OU.)
I have three OUs, Staff, Faculty, and Administration. Each has a group associated with it, with the Staff group encompassing all three groups.
Here is the code:
$server="win-ad1.example.com"
#Staff
$AdministrationOU="OU=Administration,OU=Accounts,DC=example,DC=com"
$FacultyOU="OU=Faculty,OU=Accounts,DC=example,DC=com"
$StaffOU="OU=Staff,OU=Accounts,DC=example,DC=com"
$ShadowGroup="CN=Staff,OU=User Groups,OU=Accounts,DC=example,DC=com"
Get-ADGroupMember -Server $server –Identity $ShadowGroup `
| Where-Object {($_.distinguishedName –NotMatch $AdministrationOU) `
-OR ($_.distinguishedName –NotMatch $FacultyOU) `
-OR ($_.distinguishedName –NotMatch $StaffOU)} `
| ForEach-Object {Remove-ADPrincipalGroupMembership -Server $server –Identity $_ –MemberOf $ShadowGroup –Confirm:$false}
Sleep -Seconds 2
Get-ADUser -Server $server –SearchBase $AdministrationOU –SearchScope OneLevel –LDAPFilter "(!(memberOf=$ShadowGroup))" `
| ForEach-Object {Add-ADPrincipalGroupMembership -Server $server –Identity $_ –MemberOf $ShadowGroup}
Get-ADUser -Server $server –SearchBase $FacultyOU –SearchScope OneLevel –LDAPFilter "(!(memberOf=$ShadowGroup))" `
| ForEach-Object {Add-ADPrincipalGroupMembership -Server $server –Identity $_ –MemberOf $ShadowGroup}
Get-ADUser -Server $server –SearchBase $StaffOU –SearchScope OneLevel –LDAPFilter "(!(memberOf=$ShadowGroup))" `
| ForEach-Object {Add-ADPrincipalGroupMembership -Server $server –Identity $_ –MemberOf $ShadowGroup}
#Administration
$ShadowGroup="CN=Administration,OU=User Groups,OU=Accounts,DC=example,DC=com"
Get-ADGroupMember -Server $server –Identity $ShadowGroup `
| Where-Object {$_.distinguishedName –NotMatch $AdministrationOU} `
| ForEach-Object {Remove-ADPrincipalGroupMembership -Server $server –Identity $_ –MemberOf $ShadowGroup –Confirm:$false}
Sleep -Seconds 2
Get-ADUser -Server $server –SearchBase $AdministrationOU –SearchScope OneLevel –LDAPFilter "(!(memberOf=$ShadowGroup))" `
| ForEach-Object {Add-ADPrincipalGroupMembership -Server $server –Identity $_ –MemberOf $ShadowGroup}
Get-ADGroupMember -Server $server –Identity $ShadowGroup `
| Enable-ADAccount -Server $server
....
#same code for Faculty
This is (I think) pretty standard code, but I admit to writing very little powershell. The code should remove all the users in the group that aren't in the OU, then add all the users (not already in the group) that are in the OU to the group.
In theory, this works great, however in practice adding/removing users to the Staff group can go massively wrong. In one run of the script, it will suddenly remove swathes of (random) users from the group, despite them obviously being in one of the OUs. A run of the script again may add them back or take out other users. Many time the script runs perfectly.
I had initially chalked it up to the script talking to different domain controllers, so I added the -Server argument to each Active Directory call, so that it would hit the same (primary) domain controller each time. The problem still occurs, and in all of my searching I can't find anyone with the same issue (probably because I'm not really sure how to phrase what is happening.)
Any help would be appreciated.
Note, for scale here are the size of the OUs:
Staff: 199
Faculty: 194
Administration: 32

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"
}

How can I update AD users using PowerShell and CSV import?

I'm trying to use this powershell script to update AD users. Ideally I'll be updating a bunch of attributes, but for now I'm just trying to get it to update the department just so I get tell if it's working.
Import-Module ActiveDirectory
$dataSource=import-csv "c:\ADupdate.csv"
foreach($dataRecord in $datasource) {
$employeeID=$dataRecord.employeeID
# List of attributes to update
$department=$dataRecord.department
Get-ADUser -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" -Identity $employeeID -Properties department | Set-ADUser -Replace #{department=$department}
}
Figured out my own problem. Here is what I ended up using if anyone else is interested... though I'm using a lot of attributes.
Import-Module ActiveDirectory
$users = Import-Csv -Path c:\update.csv
foreach ($user in $users) {
Get-ADUser -Filter "employeeID -eq '$($user.employeeID)'" -Properties * -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" |
Set-ADUser -employeeNumber $($user.employeeNumber) -department $($user.department) -title $($user.title) -office $($user.office) -streetAddress $($user.streetAddress) -City $($user.City) -state $($user.state) -postalCode $($user.postalCode) -OfficePhone $($user.OfficePhone) -mobile $($user.mobile) -Fax $($user.Fax) -replace #{"extensionAttribute1"=$user.extensionAttribute1; "extensionAttribute2"=$user.extensionAttribute2; "extensionAttribute3"=$user.extensionAttribute3}
}