Question

I currently use this script to obtain the SID of a user from AD. Not that each time I need an SID, I have to open the script and type the persons username in, which when I have 100's to do can be frustrating. The current script is as follows:

    $name = "username"
(New-Object System.Security.Principal.NTAccount($name)).Translate([System.Security.Principal.SecurityIdentifier]).Value
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Is there a way that I can use the same script but put the AD usernames in a textfile and pull them into powershell and have the output come out like so I get the username and the SID. Ideally into CSV format?

Cheers,

Was it helpful?

Solution

Assuming you have a list of usernames, each on its own row in userlist.txt, the process is not too complicated.

# Array for name&sid tuples
$users = @()

cat C:\temp\userlist.txt | % {
  # Syntax sugar
  $spSid = [Security.Principal.SecurityIdentifier]
  # Custom object for name, sid tuple
  $user = new-object psobject
  $user | Add-Member -MemberType noteproperty -name Name -value $null
  $user | Add-Member -MemberType noteproperty -name Sid -value $null
  $user.Name = $_
  $user.Sid = (New-Object Security.Principal.NTAccount($_)).Translate($spSid).Value
  # Add user data tuple to array
  $users += $user
}
# Export array contents into a CSV file
$users | Select-Object -Property Name,Sid | Export-Csv -NoTypeInformation C:\temp\sidlist.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top