简体   繁体   中英

Disable/Enable AD user account from CSV

How can I enable or disable an AD user account from a csv based on an entry. If the status for both say Active, only one account gets enabled instead of both. Same for the disabled status CSV file:

Samaccountname,Status
john.doe,Active
jane.doe,Disabled

What I have so far:

Import-CSV -Path c:\folder\adaccounts.csv

ForEach ($User in $Users)
{
    IF ($User.Status -contains "Disabled")
    {
        Get-ADUser -Identity $user.samaccountname | Disable-ADAccount
    }
    elseif ($User.Status -contains "Active")
    {
        Get-ADUser -Identity $user.samaccountname | Enable-ADAccount
    }
    

At the top of your script you are importing the CSV but it doesn't look like you have assigned it to a variable for your foreach loop if you assign it to the $Users variable like below, the rest of the script should then go through your CSV as expected.

$Users = Import-Csv -Path c:\folder\adaccounts.csv

-Contains is an operator to test if something can be found in an array of things, not for testing if a string is equal or not to another string.

I would revise your code like this:

Import-CSV -Path 'c:\folder\adaccounts.csv' | ForEach-Object {
    # test if a user with that SamAccountName can be found
    $user = Get-ADUser -Filter "SamAccountName -eq '$($_.Samaccountname)'" -ErrorAction SilentlyContinue
    if ($user) {
        # set Enabled if Status is not 'Disabled'
        $user | Set-ADUser -Enabled ($_.Status -ne 'Disabled')
    }
    else {
        Write-Warning "User $($_.Samaccountname) does not exist" 
    }
}

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