Automate Add AD Users from CSV, archive CSV and delete CSV after Sucessful User Add using Powershell

Viewed 32

I am trying to add users to active directory form CSV files dropped in a particular folder by using PowerShell script. This script will check AD if the users have been created and archive the CSV files before deleting them in readiness for another drops of CSV files. The power shell script will scheduled to process the CSV files dropped into the folder. I also want to user a separate but similar script to delete user from a CSV files using PowerShell.

Below are CSV file content and my script. When running the file, there is no error or failure but I couldn't get any user created from the CSV file and no log file is created with the output redirect option 2>&1 and the CSV files are not being archived too.

CSV File content:

"givenName","displayName","sAMAccountName","EmailAddress","OU",password
"DummyUser","DummyUser","dummy.user.customer1.com","dummy.user@customer1.com","OU=customer1,OU=Customers,DC=customerservice,DC=customerdomain,DC=com","**********"

Powershell Script:

<# This script is used to add  Customers users in bulk to  active directory using CSV file
 This script will be scheduled to run every hour or everyday to add new  customer users to the AD  Customers OU
 A new AD User based attributes CSV file with .csv extension and  name format LDAP_Users***####.csv  must be placed in a shared folder called LDAPExport. The folder...
..LDAPExport is located in thg C: drive of the server.  Access to the folder from permitted servers is through the FTP server service running on this server where the script is running#>


try {
    set-location = c:\ldapexport  <# I just added this line after posting the question #>
    $CustomerAddADUserCSV = Get-ChildItem -Path C:\ldapexport\ -Name *adduser*.csv
    $CustomerAddADUserLogFolder = "c:\ldapexport\CustomerADUsersLogs"
    $LdapExportLog = "c:\ldapexport\LdapExportLog"

  

<#the next lines check if AddUser csv file exists and then processed the file to add the Customer user/s account to Active Directory #>    
        if($CustomerAddADUserCSV){
               foreach ($CustomerCSVfile in $CustomeraddADUserCSV){
             
                 $NewADUsers = Import-Csv -Path $CustomerCSVfile ;
                 foreach ($User in $NewADUsers) 
                    {            
                    
                        $Displayname = $User.displayName            
                        $UserFirstname = $User.Firstname            
                        $UserLastname = $User.Lastname            
                        $OU = $User.OU            
                        $SAM = $User.sAMAccountName            
                        $Password = $User.Password
                        $EmailAddress = $User.EmailAddress
                                   
                        New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false > "$LdapExportLog\csvdeAdUsers_$(get-date -f ddMMyyyy_HHmmss).log" 2>&1  -ErrorAction stop;
                        Get-ADUser -Identity $SAM -ErrorAction Stop > "$LdapExportLog\csvdeAdUsersAdded_$(get-date -f ddMMyyyy_HHmmss).log" 2>&1
                        } ;
            
          

<#the next lines archive the  AddUser csv files into a zipped files and store them the "Archive" located in the "ldapexport" directory.#>    
         
        
                $CustomerAddADUserCSVFileArchive = Compress-Archive -Path "C:\ldapexport\$CustomerCSVfile"  -DestinationPath C:\ldapexport\Archives\$CustomerCSVfile.$(get-date -f ddMMyyyy_HHmmss).zip -force;
               

                Compress-Archive -Path $CustomerAddADUserLogFolder  -DestinationPath C:\ldapexport\Archives\CustomerADUsersLogs_$(get-date -f ddMMyyyy_HHmmss).zip -force > $LdapExportLog\csvdeArchive_$(get-date -f ddMMyyyy_HHmmss).log 2>&1;


             }

         else{
                Write-Host "No new AddUser csv file exists. Quiting..." >  $LdapExportLog\csvdeAdUsers_$(get-date -f ddMMyyyy_HHmmss).log 2>&1;
                exit
             } 
            
       

    }
}


catch {
    write-host "Please, check the script of the referenced .csv file for any error logs"
    }
1 Answers

Here's a rewrite of your code. I have changed some of the variable names because I found yours quite confusing sometimes.

Below code uses splatting on the New-ADUser cmdlet and collects the newly added user objects in a variable $addedUsers. This collection is only outpout at the very end of the code instead of writing and compressing in each iteration.

$ArchivePath = 'C:\ldapexport\Archives'
$ErrorLog    = 'c:\ldapexport\LdapExportLog\csvdeAdUsers_{0:ddMMyyyy_HHmmss}.log' -f (Get-Date)
$NewUsersCsv = 'c:\ldapexport\LdapExportLog\csvdeAdUsersAdded_{0:ddMMyyyy_HHmmss}.csv' -f (Get-Date)

$addedUsers = foreach ($csvFile in (Get-ChildItem -Path 'C:\ldapexport' -Filter '*adduser*.csv')) {
    $NewADUsers = Import-Csv -Path $csvFile.FullName
    foreach ($User in $NewADUsers) {
        $userParams = @{
            Name                  = $User.displayName
            SamAccountName        = $User.sAMAccountName
            DisplayName           = $User.displayName
            GivenName             = $User.Firstname
            Surname               = $User.Lastname
            EmailAddress          = $User.EmailAddress
            Path                  = $User.OU
            AccountPassword       = ConvertTo-SecureString $User.Password -AsPlainText -Force
            Enabled               = $true
            ChangePasswordAtLogon = $false
            ErrorAction           = 'Stop'
            PassThru              = $true
        }
        # try to create the new user and output the properties to be collected in variable $addedUsers
        try {
            New-ADUser @userParams
        }
        catch {
            $msg = "Error creating user $($User.sAMAccountName): $($_.Exception.Message)"
            # write to the error log
            $msg | Add-Content -Path $ErrorLog
            Write-Warning $msg
        }
    }

    # create the full path for the archive file and compress this current imported csv file
    $archiveFile = Join-Path -Path $ArchivePath -ChildPath ('{0}.{1:ddMMyyyy_HHmmss}.zip' -f $csvFile.BaseName, (Get-Date))
    Compress-Archive -Path $csvFile.FullName -DestinationPath $archiveFile
    # remove the current csv file
    $csvFile | Remove-Item
}

# here, you save the newly added users collected in variable $addedUsers
$addedUsers | Export-Csv -Path $NewUsersCsv -NoTypeInformation
# if you want, compress this file and archive
# create the full path for the archive file and compress
$archiveFile = Join-Path -Path $ArchivePath -ChildPath ('{0}.zip' -f [System.IO.Path]::GetFileNameWithoutExtension($NewUsersCsv))
Compress-Archive -Path $NewUsersCsv -DestinationPath $archiveFile
# remove the newusers csv file?
$NewUsersCsv | Remove-Item
Related