get-sam-from-email.ps1 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <#
  2. .SYNOPSIS
  3. This script takes a list of email addresses from the clipboard, retrieves their corresponding SAM account names from Active Directory,
  4. and copies the results as a table to the clipboard.
  5. .ENVIRONMENT
  6. - The Active Directory module must be installed and imported:
  7. 1. Open PowerShell as Administrator.
  8. 2. Run the following command to install the RSAT (Remote Server Administration Tools):
  9. Get-WindowsCapability -Name RSAT.ActiveDirectory* -Online | Add-WindowsCapability -Online
  10. 3. Import the Active Directory module into your PowerShell session with:
  11. Import-Module ActiveDirectory
  12. #>
  13. # Get the list of email addresses from the clipboard
  14. $emailAddresses = (Get-Clipboard -Raw).Split("`n")
  15. # Initialize an array to hold the results
  16. $results = @()
  17. # Loop through each email address
  18. foreach ($email in $emailAddresses) {
  19. # Get the user object from Active Directory
  20. $user = Get-ADUser -Filter {Mail -eq $email} -Properties SamAccountName
  21. # Check if the user was found
  22. if ($user) {
  23. # Add the email and SAM account name to the results array
  24. $results += [PSCustomObject]@{
  25. Email = $email
  26. SamAccountName = $user.SamAccountName
  27. }
  28. } else {
  29. # If the user was not found, add a placeholder
  30. $results += [PSCustomObject]@{
  31. Email = $email
  32. SamAccountName = "Not Found"
  33. }
  34. }
  35. }
  36. # Convert the results to a table and copy to clipboard
  37. $results | Format-Table | Out-String | Set-Clipboard
  38. Write-Host "Script completed. The results have been copied to the clipboard."
  39. $results | Format-Table | Out-String