Skip to content

Instantly share code, notes, and snippets.

@trondhindenes
Last active May 17, 2017 14:54
Show Gist options
  • Save trondhindenes/d99180d886a4e570b890 to your computer and use it in GitHub Desktop.
Save trondhindenes/d99180d886a4e570b890 to your computer and use it in GitHub Desktop.
Function for verifying local and domain users
Function UserSearch
{
Param ([string]$AccountName)
#Check if there's a realm specified
if ($AccountName.Split("\").count -gt 1)
{
if ($AccountName.Split("\")[0] -eq $env:COMPUTERNAME)
{
$IsLocalAccount = $true
}
Else
{
$IsDomainAccount = $true
$IsUpn = $false
}
}
Elseif ($AccountName -contains "@")
{
$IsDomainAccount = $true
$IsUpn = $true
}
Else
{
#Default to local user account
$accountname = $env:COMPUTERNAME + "\" + $AccountName
$IsLocalAccount = $true
}
if ($IsLocalAccount -eq $true)
{
$localaccount = get-wmiobject -class "Win32_UserAccount" -namespace "root\CIMV2" -filter "(LocalAccount = True)" | where {$_.Caption -eq $AccountName}
if ($localaccount)
{
return $localaccount.Caption
}
$LocalGroup = get-wmiobject -class "Win32_Group" -namespace "root\CIMV2" -filter "LocalAccount = True"| where {$_.Caption -eq $AccountName}
if ($LocalGroup)
{
return $LocalGroup.Caption
}
}
ElseIf (($IsDomainAccount -eq $true) -and ($IsUpn -eq $false))
{
#Search by samaccountname
$Searcher = [adsisearcher]""
$Searcher.Filter = "sAMAccountName=$($accountname.split("\")[1])"
$result = $Searcher.FindOne()
if ($result)
{
return $accountname
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment