Share via

Powershell Insert Blank Cell for Nonexistent Users in a csv

Charles Eaton 21 Reputation points
2020-11-16T19:27:24.157+00:00

Hello,

I am trying to find managers for each user listed in a csv, then export the results. Here is what I have so far:

$list = import-csv "C:\users.csv"

$managers = ForEach($User in $list){

Get-ADUser $User.name -Properties SAMAccountName,Manager | select Manager

}
$managers | Out-File C:\managers.csv

The problem is, some of the users in the list do not exist, and it causes the exported csv to "shrink" by one cell for each nonexistant user. but I still need to have the same amount of cells in the output and input to match it up properly in another system. Is there a way I can insert a blank cell for a nonexistent user?

Thanks in advance

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Rich Matheisen 48,116 Reputation points
2020-11-16T20:49:25.787+00:00

How about this instead?

Import-CSV C:\users.csv |
    ForEach-Object {
        Try{
            $u = Get-ADUser $_.name -Properties SAMAccountName,Manager -ErrorAction Stop
            [PSCustomObject]@{User = $_.name; SamAccountName = $u.SAMAccountName; Manager = $u.Manager}
        }
        Catch{
            [PSCustomObject]@{User = $_.name; SamAccountName = 'Not Found'; Manager = 'N/A'}
        }
    } | Export-CSV c:\managers.csv -NoTypeInformation

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.