Output on Powershell script not displaying properly

Viewed 37

I have a Powershell script that audits an imported CSV and spits out a completed version of the CSV adding columns that state if the users in the CSV are in AD and if so are they active or not.

#CSV file to have header of "Employee" with First and Last name in each row
Echo "CSV file to import must be in c:\temp folder location with header of "Employee""
$csvlocate = (Read-Host -Prompt "CSV File to import (enter in like filename.csv and make sure file is in c:\temp folder)")
$csvEmployees = Import-Csv -path C:\temp\$csvlocate.csv
$adUsers = Get-AdUser -Filter *

foreach ($Employee in $csvEmployees) {
    $Found = $adUsers | Where-Object { ($_.GivenName -eq $Employee.givenName) -and ($_.Surname -eq $Employee.surName) }
    if ($Found) {
        "In AD $($Employee.givenName) $($Employee.surName)."
        $Employee | Add-Member -Name InAD -Value $true -MemberType NoteProperty
        $Employee | Add-Member -Name Enabled -Value $Found.Enabled -MemberType NoteProperty
    } else {
        "Not in AD $($Employee.givenName) $($Employee.surName)."
        $Employee | Add-Member -Name InAD -Value $false -MemberType NoteProperty
        $Employee | Add-Member -Name Enabled -Value $false -MemberType NoteProperty
    }
}



$csvEmployeesNotInAd = $csvEmployees.foreach{
    $employee = @{
        'CSVName' = $_.Name
        'InAD' = $false
    }
    if ($_.Name -in $adUsers.Name) {
        $employee.InAD = $true
    }
    [pscustomobject]$employee
}



$csvEmployees | Export-Csv -Path C:\temp\$csvlocate.completed.csv -NoTypeInformation -Force

When the CSV spits out all I see in the Enabled column is System.Object[]. Any ideas why?

1 Answers

By the looks of it, your code could be reduced to the following:

Import-Csv $sourceCsv | ForEach-Object {
    $filter = "(&(givenName={0})(Surname={1}))" -f $_.givenName, $_.Surname
    $user   = Get-AdUser -LDAPFilter $filter
    $_.PSObject.Add([psnoteproperty]::new('InAd', [bool] $user))
    $_.PSObject.Add([psnoteproperty]::new('Enabled', [bool] $user.Enabled))
    $_
} | Export-Csv $destinationCsv -NoTypeInformation

The if / else conditions are not needed at all, you also don't need to query all AD Users for this comparison, this is quite inefficient, or will be in a Domain with a high amount of user objects.

[bool] $user and [bool] $user.Enabled works because if the user couldn't be found, in other words, $user is $null, by casting [bool] we would be getting $false.

Also, having a CSV with the user's GivenName and Surname is a terrible idea. You should be using one of these:

  • DistinguishedName
  • objectGUID
  • objectSid
  • sAMAccountName
Related