Friday, October 14, 2022

Powershell function to look up an Active Directory user with SamAccountName

This is a short function to create a function called "Show-User".

#
# Show a single user
#
function Show-User
{
    param (
        [Parameter(Mandatory)] $Username
        )

    try{
        $test = Get-ADUser -Identity $Username -Prop CN,description,LastLogon,whenCreated,LastLogontimestamp,LastLogonDate,SamAccountName, userPrincipalName,SmartcardLogonRequired,PasswordNeverExpires, targetAddress, EmailAddress,homeDirectory, CanonicalName, adminDescription, msDS-cloudExtensionAttribute1 -ErrorAction Stop | 
            Select CN, SamAccountName, description, userPrincipalName, SmartcardLogonRequired, PasswordNeverExpires, whenCreated, adminDescription, LastLogonDate, Employee-ID, @{n="lastLogontimestamp";e={[datetime]::FromFileTime($_.lastLogontimestamp)}},  @{n="lastLogon";e={[datetime]::FromFileTime($_.LastLogon)}},AccountExpirationDate, targetAddress, EmailAddress,homeDirectory, CanonicalName
        if($test) {
            Write-Output $test
        }
    } catch {
        Write-Output "User object $Username does not exist in AD"
    }
}

Execute the powershell script to create the command, then you should be able to use it in powershell like this:

C:\windows\system32> Show-User -Username john.doe

Hope you find that useful.

No comments:

Post a Comment