- 1 year ago
Writing User ObjectID to variable #Powershell
In PowerShell, you can access the ObjectID
of the current user by using the Get-ADUser
cmdlet from the ActiveDirectory
module. Here's how you can assign the ObjectID
of the current user to a variable:
powershell# Import the Active Directory module (if not already imported)
Import-Module ActiveDirectory
# Get the current user's ObjectID
$currentUser = $env:USERNAME
$userObjectID = (Get-ADUser -Filter {SamAccountName -eq $currentUser}).ObjectGUID
# Convert the ObjectID to a string representation
$userObjectIDString = $userObjectID.ToString()
# Display the ObjectID
Write-Host "User ObjectID: $userObjectIDString"
In the above code, we first import the ActiveDirectory
module (if not already imported) using the Import-Module
cmdlet. Then, we get the current user's username from the environment variable $env:USERNAME
.
Next, we use the Get-ADUser
cmdlet to retrieve the user object from Active Directory based on the username. We use the ObjectGUID
property of the user object to get the ObjectID
.
Finally, we convert the ObjectID
to a string representation and store it in the $userObjectIDString
variable. You can use this variable to work with the ObjectID
in your PowerShell script as needed.
Note: To use the Get-ADUser
cmdlet, you need to have the Active Directory module installed on your system. If you don't have it, you can install it by adding the "Active Directory Domain Services" feature from the "Add Roles and Features" wizard in the Windows Server Manager.