在AD中创建用户

时间:2020-06-20 08:33:56

标签: powershell

我有一个Employee Details的CSV文件,并希望根据Employee Status执行创建,修改和禁用操作。遵循CSV。

EmployeeCode,EmployeeID,EmployeName,Firstname,Lastname,Email,Designation,Department,State,ReportingManagerCode,Status
XA0001,1256,Srihari T,Srihari,T,srihari.t@contosso.com,Executive,Finance,Kerala,1258,New
XA0002,1257,Adam Varghese,Adam,Varghese,adam.varghese@contosso.com,TL,CC,Tamil Nadu,1210,Disabled
XA0003,1258,Shakti Velu,Shakti,Velu,shakti.velu@contosso.com,Manager,Finance,Kerala,1205,Existing

遵循OU结构。

contosso.com
    Finance(OU=Finance,DC=contosso,DC=com)
    CC(OU=CC,DC=contosso,DC=com)
    Left(OU=Left,DC=contosso,DC=com)

期望的解决方案:如果用户状态为“新建”,则将在其部门OU中创建用户以及其他属性。状态“已禁用”用户被禁用并移至“左OU”。状态“现有”用户会更新其属性。

对于每个操作,我都有单独的PowerShell脚本运行,但是无法通过检查“状态字段”将它们合并为一个脚本。

  1. 能够创建用户,但无法将状态查找为“新建”来创建它。
Import-Module activedirectory
$ADUsers = Import-csv 'C:\IT\EmployeeDetails.csv'

foreach ($User in $ADUsers)
{       
    $Username   = ($User.Firstname + '.' + $User.Lastname).ToLower()
    $Firstname  = $User.Firstname
    $Lastname   = $User.Lastname
    $OU         = 'OU=Finance,DC=contosso,DC=com'
    $Email      = $User.Email
    $EmployeeID = $User.EmployeeID
    $State      = $User.State
    $Designation   = $User.Designation
    $Department = $User.Department
    $Password = (Get-RandomCharacters -characters AbcDeFgHiJkLmNoPqRsTuVwXyZ!@#*123456789 -length 8)

    #Check to see if the user already exists in AD
    if (Get-ADUser -F {SamAccountName -eq $Username})
    {
         Write-Warning "A user account with username $Username already exist in Active Directory."
    }
    else
    {
        New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username@contosso.com" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Firstname $Lastname" `
            -Path $OU `
            -EmployeeID $EmployeeID `
            -State $State `
            -EmailAddress $Email `
            -Title $Designation `
            -Department $Department `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True

    }
}
  1. 禁用用户,但无法在状态上查找为“已禁用”以禁用并移至“左OU”。
Import-Module activedirectory

$ADUsers = Import-csv C:\IT\EmployeeDetails.csv

foreach ($User in $ADUsers)
{
    Get-ADUser -Filter "EmployeeID -eq '$($User.EmployeeID)'" | 
    Move-ADObject -TargetPath "OU=Left,DC=contosso,DC=com" -PassThru | 
    Disable-ADAccount
}
  1. 修改详细信息,但无法将“状态”查找为“现有”来进行修改。
Import-Module activedirectory

$ADUsers = Import-Csv C:\IT\EmployeeDetails.csv

foreach ($User in $ADUsers)
{
Get-ADUser -Filter "EmployeeID -eq '$($User.EmployeeID)'" | 
Set-ADUser -EmailAddress $User.Email -Title $User.Designation -Department $User.Department -State $User.State
}

1 个答案:

答案 0 :(得分:0)

要从这些部分中创建一个脚本,我建议为以下内容创建三个函数

  1. 创建一个新用户
  2. 移动并禁用现有用户,并且
  3. 更新现有用户

并根据CSV中Status的值在主循环中调用其中任何一个。

如下所示:

Import-Module ActiveDirectory

function New-User ($record) {
    $AccountName = ($record.Firstname + '.' + $record.Lastname).ToLower()

    #Check to see if the user already exists in AD
    if (Get-ADUser -Filter "SamAccountName -eq '$AccountName'" -ErrorAction SilentlyContinue) {
         $msg = "New-User: a user account with username $AccountName already exist in Active Directory."
         Write-Warning $msg
    }
    else {
        $FullName = ('{0} {1}' -f $record.Firstname, $record.Lastname).Trim()
        $OU       = 'OU={0},DC=contosso,DC=com' -f $record.Department
        $Password = (Get-RandomCharacters -characters AbcDeFgHiJkLmNoPqRsTuVwXyZ!@#*123456789 -length 8)

        $userParams = @{
            SamAccountName        = $AccountName
            UserPrincipalName     = "$AccountName@contosso.com"
            Name                  = $FullName
            GivenName             = $record.Firstname
            Surname               = $record.Lastname
            Enabled               = $true
            DisplayName           = $FullName
            Path                  = $OU
            EmployeeID            = $record.EmployeeID
            State                 = $record.State
            EmailAddress          = $record.Email
            Title                 = $record.Designation
            Department            = $record.Department
            AccountPassword       = (ConvertTo-SecureString $Password -AsPlainText -Force)
            ChangePasswordAtLogon = $true
        }
        # create the user and report back
        New-ADUser @userParams

        # don't forget to output the initial password, the user needs this for the first-time login.
        $msg = "New-User: created user $AccountName. Initial password: $Password"
    }
    # report back
    $msg
}

function Move-User ($record) {
    # check if the user object exists
    $user = Get-ADUser -Filter "EmployeeID -eq '$($record.EmployeeID)'" -ErrorAction SilentlyContinue
    if (!$user) {
        $msg = "Move-User: a user account with EmployeeID $($record.EmployeeID) does not exist."
        Write-Warning $msg
    }
    else {
        $OU = "OU=Left,DC=contosso,DC=com"
        $user | Set-ADUser -Enabled $false
        $user | Move-ADObject -TargetPath "OU=Left,DC=contosso,DC=com"

        $msg = "Move-User: user $($user.SamAccountName) disabled and moved to $OU"
    }
    # report back
    $msg
}

function Update-User ($record) {
    # check if the user object exists
    $props = 'EmailAddress', 'Title', 'Department', 'State'
    $user = Get-ADUser -Filter "EmployeeID -eq '$($record.EmployeeID)'" -Properties $props -ErrorAction SilentlyContinue
    if (!$user) {
        $msg = "Update-User: a user account with EmployeeID $($record.EmployeeID) does not exist."
        Write-Warning $msg
    }
    else {
        $userParams = @{
            EmailAddress = $record.Email
            Title        = $record.Designation
            Department   = $record.Department
            State        = $record.State
        }
        $user | Set-ADUser @userParams

        $msg = "Update-User: user $($user.SamAccountName) updated"
    }
    # report back
    $msg
}

$result = Import-Csv 'C:\IT\EmployeeDetails.csv' | ForEach-Object {
    # perform the actions New, Move or Update
    switch ($_.Status) {
        'New'      { New-User $_ ; break}
        'Disabled' { Move-User $_ ; break}
        'Existing' { Update-User $_ ; break}
        default    { "ERROR: Unknown Status in CSV: $_" }
    }
}

# output the messages on screen
$result

# or write to file
$result | Set-Content -Path 'C:\IT\EmployeeResults.txt'

请注意,我无法检查您的功能Get-RandomCharacters的作用,但是我假设它执行的很好。

在此代码中并不重要,但是CSV标头之一中有错字:EmployeName应该为EmployeeName

相关问题