Search code examples
powershellactive-directory

How do I add a new line into my array with new data grabbed from Active Directory?


I am new to Powershell, and I am trying to create a .csv file output from this script that I can quickly use to upload into a database.

It all works well and outputs exactly how I want it to, but I can only do one user at a time.

I have a loop set up that runs back through the script, but I'm missing the part where I need the array to output on a new line.

Any suggestions?

Import-Module ActiveDirectory

[string]$script:iviisID = Read-Host "Enter iViis ID number"

$AddUser = {

    $script:name = Read-Host "Enter username (first.last)"
    
    $script:number = Read-Host "Enter users Phone Number"

    $script:gender = Read-Host "Enter 1 for Male, 2 for Female"

    if ($gender -eq 1)
    {
        $script:gender = "Male"
    } else
    {
        $script:gender = "Female"
    }

    $script:role = Read-Host "Enter 1 for Foreman, 2 for Contract Manager"

    if ($role -eq 1)
    {
        $script:role = "Foreman@er"
    } else
    {
        $script:role = "ContractManager@er"
    }

    $user = Get-ADUser -identity $name -Properties *

    $firstName = $user | foreach {$_.givenName}
    $lastName = $user | foreach {$_.sn}
    $employeeID = $user | foreach {$_.employeeID}
    $email = $user | foreach {$_.mail}

    $array =@(
        [PSCustomObject] @{
        FirstName = $firstName
        Surname = $lastName
        FirstNames = $firstName
        LastName = $lastName
        EMPLOYEEID = $script:iviisID
        PGID = $employeeID
        EmployeeCode = $script:iviisID
        UserID = [string]$script:iviisID + "@er"
        ENABLEDFLAG = "1"
        EmailAddress = $email
        PersonalPhoneNumber = $number
        Role = $role
        Password = "plant.box.dog"
        Gender = $gender
        PreferredName = $firstName
        Category = "Employee"
        }
    )

    $newUser = Read-Host "Would you like to add another user? (y/n)"

    if($newUser -eq "y")
    {
        [int]($script:iviisID) = $iviisID
        $script:iviisID++



        &$AddUser
    }
    else
    {
        $array | Export-CSV -NoTypeInformation -Path C:\Test\Employees.csv
    }
}

&$AddUser

This is the example of my code, if I run through this it ends up giving me a .csv with only the latest run through of the loop that I have run, but I have no way to retain the information I have already added.

Apologies if the way I have created this is a bit odd, as I am just learning Powershell and experimenting, but if anybody could direct me in the right direction or suggest anything then please let me know :)

Edit: Added missing code


Solution

  • The issue with your code, the reason why your Csv only gets the last user created is because each recursive call to the $AddUser scriptblock is overwriting the previous Csv file, your code could be solved by adding -Append:

    $array | Export-CSV -NoTypeInformation -Path C:\Test\Employees.csv -Append
    

    However, instead of using a recursive call I recommend you to use a while loop, much easier this way and there is no need to use $script: scoped variables. In this case the while loop is wrapped in an outer invoked scriptblock to enable directly piping the output from the loop to Export-Csv.

    Import-Module ActiveDirectory
    
    & {
        [int] $iviisID = Read-Host 'Enter iViis ID number'
    
        while ($true) {
            $name = Read-Host 'Enter username (first.last)'
            $number = Read-Host 'Enter users Phone Number'
            $gender = Read-Host 'Enter 1 for Male, 2 for Female'
            if ($gender -eq 1) {
                $gender = 'Male'
            }
            else {
                $gender = 'Female'
            }
    
            $role = Read-Host 'Enter 1 for Foreman, 2 for Contract Manager'
            if ($role -eq 1) {
                $role = 'Foreman@er'
            }
            else {
                $role = 'ContractManager@er'
            }
    
            $user = Get-ADUser -Identity $name -Properties givenName, sn, employeeId, mail
    
            [PSCustomObject] @{
                FirstName           = $user.givenName
                Surname             = $user.sn
                FirstNames          = $firstName
                LastName            = $lastName
                EMPLOYEEID          = $iviisID
                PGID                = $user.employeeID
                EmployeeCode        = $iviisID
                UserID              = [string] $iviisID + '@er'
                ENABLEDFLAG         = '1'
                EmailAddress        = $user.mail
                PersonalPhoneNumber = $number
                Role                = $role
                Password            = 'plant.box.dog'
                Gender              = $gender
                PreferredName       = $firstName
                Category            = 'Employee'
            }
    
            $newUser = Read-Host 'Would you like to add another user? (y/n)'
    
            if ($newUser -eq 'y') {
                $iviisID++
                continue
            }
    
            # if `$newUser` not equal to 'Y' breaks the while loop here
            break
        }
    } | Export-Csv -NoTypeInformation -Path C:\Test\Employees.csv