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

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,579 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,537 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 46,796 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
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

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