Skip to content

Instantly share code, notes, and snippets.

@pepoluan
Created June 25, 2013 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepoluan/5856121 to your computer and use it in GitHub Desktop.
Save pepoluan/5856121 to your computer and use it in GitHub Desktop.
I often had to get a User object from AD, and reuse it again and again and again. To complicate matters, some names are very commonly used among Indonesians. So, I whup up this PowerShell Function to: (1) Pull a User object from AD and put it in a $global: object, so I can use it everywhere, and (2) If there are more than one match, list all the…
Function GetU() {
param(
$usr,
$Order,
[switch]$Silent
)
$EssentialAttributes = @(
"EmployeeID"
"Email"
"MobilePhone"
"Manager"
)
# Specifying "-Order" overrides everything else
If ($Order -ne $null) {
$usr = $u[$Order]
}
Else {
# First, check if we actually specify *something* as parameter
If ($usr -eq $null) {
# Nothing specified; try recovering the last selected user
If ($u) { $usr = $u }
Else { Write-Error "`$u not yet defined!"; return }
}
Else {
# Something is specified. Let's check if it's a number
$Ord = 0
If ([System.Int32]::TryParse($usr,[ref]$Ord)) {
$usr = $u[$Ord]
}
# At this point, if $usr was a number, it has been converted into a member
# of the previously found array.
# If $usr is *not* a number, it's passed to the next line unscathed
}
}
# Why do we re-get the $usr if it comes from a previous $u?
# Good reason: Just in case there has been a change.
# Actual reason: I'm too lazy to put in additional checks. Besides, won't hurt to re-get the $usr
$global:u = Get-QADUser $usr -IncludeAllProperties
If (!$u) {
"$usr not found."
return
}
If ($u.Count -gt 1) {
"`r`n========== Multiple users found! ==========`r`n"
# Now we create a nice table containing the Ord(inal) of the found users
# to assist in selecting one from the list.
# (Previously, it was just a dump of the array, and I have to manually count for the order)
# (Not fun)
$c = 0
$arr = @()
foreach ($i in $u) {
$props = @{
Ord = $c++
Name = $i.Name
Username = $i.LogonName
CanonicalName = $i.CanonicalName
}
$arr += New-Object PSObject -Property $props
}
$arr | ft -autos
return
}
If ($u.Count -eq 1) {
If (!$Silent) {
$u | Select Name,LogonName,CanonicalName | ft -autos
foreach ($attr in $EssentialAttributes) { " {0} = {1}" -f $attr,$u.$attr }
Get-QADMemberOf $u | Select Name,CanonicalName | ft -autos
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment