ps/Modules/Alkami.DevOps.SystemEngineering/Public/Get-ActiveDirectoryAccount.ps1

72 lines
2.1 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Get-ActiveDirectoryAccount {
<#
.SYNOPSIS
Returns the Active Directory account for a user or service account.
.DESCRIPTION
Returns the Active Directory account for a user or service account. Caller must have domain admin rights
.PARAMETER Identity
[string] The identity of the Active Directory account to retrieve.
.EXAMPLE
Get-ActiveDirectoryAccount -Identity "testUser"
#>
[CmdletBinding()]
[OutputType([PSObject[]])]
param(
[Parameter(Mandatory)]
[Alias("Account", "AccountName")]
[ValidateNotNullOrEmpty()]
[string]$Identity
)
$logLead = (Get-LogLeadName)
$trimIdentity = $Identity.Trim()
# Make sure the caller passed in more than just whitespace
if ([String]::IsNullOrEmpty($trimIdentity)) {
Write-Warning "$logLead : Identity [$Identity] must contain at least one non-whitespace character."
return $null
}
# Look for a normal user
try {
Write-Verbose "$logLead : Attempting to find account using Get-ADUser."
$result = Get-ADUser -Identity $trimIdentity -Properties *
} catch {
Write-Verbose "$logLead : Account named [$Identity] not found using Get-ADUser: $($_.Exception.Message)"
}
# No normal user account? Check for a gMSA/MSA
if ($null -eq $result) {
try {
Write-Verbose "$logLead : Attempting to find account using Get-ADServiceAccount."
$result = Get-ADServiceAccount -Identity $trimIdentity -Properties *
} catch {
Write-Verbose "$logLead : Account named [$Identity] not found using Get-ADServiceAccount: $($_.Exception.Message)"
}
}
# Still nothing? Tough luck kid. Write a warning.
if ($null -eq $result) {
Write-Warning "$logLead : No account could be located with the supplied account name."
if (-NOT (Test-IsUserDomainAdmin)) {
Write-Warning "$logLead : This command is being run without domain administrative privileges. In some cases, elevated permissions may be required to locate accounts."
}
}
return $result
}