PowerShell: Get-AdUser based on SamAccountName


My first project uploated on this blog will be about how to find and export Active Directory users by their SAMaccountName. In my case a had text file with SamAccountNames and I wanted output in nice CSV file with SamAccountName, DisplayName and Office.

Script in high level:
1. load content from file with SamAccountNames
2. get ADuser object from Active Directory by SamAccountName
3. create psobject and set properties
4. export array to CSV file

1. Load content from file

This part of code is so simply. Content is stored in file with name "DC_users.txt."

1
2
    $users_file = (Get-Item -Path ".\" -Verbose).FullName + "\DC_users.txt"
    $users = Get-Content $users_file

2. Get ADuser object from Active Directory

SamAccountNames are stored in variable $users. So script works in loop, trought array $users.


1
$user = (Get-ADUser -f {SamAccountname -like $i} -Properties * | select SamAccountname,Displayname,Office )


3. Create PSObject

Very good explanation how to create own PSObejct is here here.

1
2
3
4
5
$user_object = @{'SamAccountName'=$user.SamAccountname;
                 'DisplayName'=$user.Displayname;
                 'Office'=$user.Office;
}
$output = New-Object -TypeName psobject -Property $user_object


4. Export data to CSV file

Our PSObjects are stored in array $output2. Save data to .csv file is simple with build in powershell command "Export-Csv"


1
$output2 | Export-Csv $output_file -Encoding Default

Final Powershell code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function Get-ADUser_by_SAMaccountName {
    $users_file = (Get-Item -Path ".\" -Verbose).FullName + "\DC_users.txt"
    $users = Get-Content $users_file
    $output_file = (Get-Item -Path ".\" -Verbose).FullName + "\DC_users-output.csv"
    $output = $null
    $output2 = @()
    $percentage_per_one_step = (100 / ($users.Count) -as [double])
    $current_complete = 0
  
    foreach($i in $users) {
        Write-Progress -Activity "user $($i) of $($users.Count)" -PercentComplete $current_complete
        $user = (Get-ADUser -f {SamAccountname -like $i} -Properties * | select SamAccountname,Displayname,Office )
        $user_object = @{'SamAccountName'=$user.SamAccountname;
                    'DisplayName'=$user.Displayname;
                    'Office'=$user.Office;
                }
        $output = New-Object -TypeName psobject -Property $user_object
        $output2 +=$output
        $current_complete += $percentage_per_one_step
    }
    $output2 | Export-Csv $output_file -Encoding Default 
}
#call function
Get-ADUser_by_SAMaccountName

#Add-Content $output_file $output

Comments

Popular Posts