Getting samaccountname from list of names

As a sysadmin we have all been in the situation where you’ve been handed a list of names where you are asked “please add these users to group this or that”. Next time you get a list with email addresses. It might be in a .csv or a .xlsx or .txt. The format might vary a lot! You can try to solve this with providing non-IT personal with templates, but we all know that they will not find the right one when needed.

Updating your existing functions is time consuming and I’m not even going to mention the fact how much time it would take to do this manually which might be the case if you’re not fluid enough in PowerShell to make changes in a script. Ten users might be ok to do manually, but it’s a totally different thing when you’re handed a list with several hundred usernames.

Instead of handing out templates to the Organization admins (HR, economic admins etc.) I keep track of my own. In this case a simple .csv with a header ‘Name’.

I’m starting by adding the parameters that I need

  • Infile
  • Outfile
  • Server (if you’re running the script cross-domain)
function Get-SamfromName {
    param (
        [Parameter(Mandatory = $true)]
        [String]$infile,
        [Parameter(Mandatory = $true)]
        [String]$outfile,
        [Parameter(Mandatory = $true)]
        [String]$Server
    )
    
}

A user list is rarely 100% correct. There’s always typos and other errors to be expected and I want to catch these so I can manually check them later. So, I create a list variable that will contain these errors

$notfound = @()

I start by importing a list of names from a .csv specified in $infile and then for each name query active directory for a user that matches that name. If there’s no match, then I store the name in the notfound list. If there’s a match I send it along the pipeline to export-csv specified in $outfile. At the end I print the list of users that wasn’t found in active directory.

function Get-SamFromName {
    param (
        [Parameter(Mandatory = $true)]
        [String]$infile,
        [Parameter(Mandatory = $true)]
        [String]$outfile,
        [Parameter(Mandatory = $true)]
        [String]$Server
    )

    $notfound = @()
    Import-csv -path $infile | 
     
     
    ForEach-Object {
        $filter = $_.Name
        $user = Get-ADUser -filter { Name -like  $filter }  -Server $server  | Select-Object name, samaccountname
        if ($null -eq $user) {
            $notfound += $filter 
        }
        else {
            Write-Output $user
        }
    } | Export-Csv -Path $outfile -Delimiter ';' -NoTypeInformation -Encoding UTF8
    Write-host "Users not found" 
    Write-Output $notfound 
      
}