Script to Pull Base64String from Ad Objects

Script to Pull Base64String from Ad Objects

I am working on a powershell script together which will

  1. query an existing OU
  2. select the first and last name, samaccountname, and objectguid, of all users in the OU
  3. Take the objectguid of each user and convert it to a base64string (immutableid)
  4. output the results in a table format with users' first and last name, samaccountname, objectguid, and immutableid, sorted in alphabetical order by users' firstname.

The below script works just fine if I wanted to pull the base64string for one user at a time:

Import-module ActiveDirectory

$UserSamAccount = Read-Host "Provide SamAccountName of a user"
  
$User = Get-ADuser $UserSamAccount -Properties * | select ObjectGUID
  
$ImmutableID = [convert]::ToBase64String(([GUID]($User.ObjectGUID)).tobytearray())
  
Write-Host "ImmutableID for user $UserSamAccount is:" -ForegroundColor Cyan

$ImmutableID

Any help with this will be most appreciated. Thank you in advance!

1 Answer

If I understand correctly your need the following should do the trick. It uses [pscustomobject] to construct your desired output and a ForEach-Object to process each object from the pipeline:

Get-ADUser -Filter * -SearchBase "OU=myOU,DC=myDomain,DC=xyz" -SearchScope OneLevel |
    Sort-Object GivenName |
    ForEach-Object {
        [pscustomobject]@{
            GivenName      = $_.GivenName
            Surname        = $_.Surname
            SamAccountName = $_.SamAccountName
            ObjectGuid     = $_.ObjectGuid
            ImmutableId    = [convert]::ToBase64String($_.ObjectGuid.ToByteArray())
        }
    } # | Export-Csv path\to\myExport.Csv -NoTypeInformation <= Can pipe this to export later :)

You could also use Select-Object with a calculated property (might be simpler but harder to read):

Get-ADUser -Filter * -SearchBase "OU=myOU,DC=myDomain,DC=xyz" -SearchScope OneLevel |
    Sort-Object GivenName |
    Select-Object GivenName, Surname, SamAccountName, ObjectGuid, @{ N='ImmutableId'; E={ [convert]::ToBase64String($_.ObjectGuid.ToByteArray()) }}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.