简体   繁体   中英

How can I compare CSV to AD users and disable users not in CSV?

As a process to disable users, I have a CSV where users are identified by employeeID and not username. I need to loop through and compare the CSV to AD users, and any AD user not in the CSV needs to be disabled. This is what I have so far, but it's not working. I'll admit I'm still fairly new to powershell scripting, so any help would be much appreciated.

Import-Module ActiveDirectory  

Import-Csv -Path c:\ADTerm.csv | foreach {Get-ADUser -filter * -SearchBase "ou=Test,ou=Logins,dc=domain,dc=com" -Identity $_.employeeID} | Where {$_ -ne $null} | Disable-ADAccount -Identity $_.employeeID

I cant really fit this all in a comment without it looking horrible so lets start with this.

You are combining -Filter and -Identity which most likely wont net the results you are looking for. Use Identity to get one specific user or filter to get one to many. Looking at TechNet for Get-AdUser you will see Identity only matches values to:

  • DistinguishedName
  • objectGUID
  • objectSid
  • sAMAccountName

In that regard I see you have a column for EmployeeID . I'm guessing that those are not SamAccountName which is one of the values that -Identity supports. I feel that you could do with the following changes.

$IDs = Import-Csv -Path c:\ADTerm.csv | Select-object -ExpandProperty EmployeeID
Get-ADUser -filter * -SearchBase "ou=Test,ou=Logins,dc=domain,dc=com" -Properties EmployeeID | 
        Where-Object{$_.EmployeeID -and ($IDs -notcontains $_.EmployeeID)} | Disable-ADAccount

Update the get-aduser to get all users in that OU. Get-Aduser does not return the EmployeeID by default so we use -Properties to specify it. Filter all those users that have employeeID but not one in the list. Disable-ADAccount will take the output of Get-AdUser nicely so there is not need to specify the account again.

Depending you might be storing this value as EmployeeNumber in AD. This is also dependent on your having a csv file with a column for EmployeeNumber

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM