Get-ADUser for not exact username - powershell

The script below lists some user details, it works only in case I've entered the EXACT user name. Is there a method I could use to get results if I type a partial username?
I mean if for example I enter "elibukin" or "eli.buk" instaed of "eli.bukin" witch is the correct username.
do {
Write-Host "Who r we looking for ? (type EXIT when u done)"
$User = Read-Host
Get-ADUser $User -Properties * |
fl empl*,title, sam*, disp*, mail*, manager*, depa*, giv*, l, last*,
logon*, when*
} until ($user -eq "exit")

I would use -LDAPFilter with ambiguous name resolution (ANR).
Get-ADUser -LDAPFilter "(anr=smith)"
See https://support.microsoft.com/en-us/kb/243299 for more information about ANR.

I have actually worked on a script much like this. I used the -like operator to accommodate partial matches. However, this might give you more than one result.
Get-ADUser -Filter ("SamAccountName -like '*$user*'")
Or use something of this format to narrow down your result:
Get-ADUser -Filter ("SamAccountName -like '*$user*' -and Name -like '*$FirstName*' -and Surname -like '*$Lastname*'")
Use -or instead of -and for a broader result.

If you want fuzzy matching use the parameter -Filter with the -like operator:
do {
$user = Read-Host -Prompt 'Who are we looking for (type EXIT when done)'
if ($user -ne 'exit') {
Get-ADUser -Filter "SamAccountName -like '*$User*'" -Properties * |
Format-List empl*,title, sam*, disp*, mail*, manager*, depa*, giv*, l,
last*, logon*, when*
}
} until ($user -eq "exit")

Related

Issues with looping - Need help "refining" my code

I've this ps script that I have written myself. It searches for available Active Directory groups with a keyword, and if no keyword is found, it outputs that it cannot find any AD groups, and asks if I'd like to search again. However, the issue I'm facing, is that it outputs that it cannot find any AD groups, even if it does find groups with my keyword...
This be my code:
$group = Read-Host "Which groups would you like to search for?"
$group = $group + "_*"
$groups = Get-ADGroup -Filter {name -like $group} -Properties * | select SAMAccountName, Description
while ($groups -eq $null) {
if ($groups -eq $null) {
Write-Verbose "Did not find any matching groups. Try again" -Verbose
$group = Read-Host "Which groups would you like to search for?"
$group = $group + "_*"
Get-ADGroup -Filter {name -like $group} -Properties * | select SAMAccountName, Description
} else {
if ($groups -ne $null) {
Get-ADGroup -Filter {name -like $group} -Properties * | select SAMAccountName, Description
}
}
}
Now, I know this is probably not that cleanly done, and the formatting could be better... maybe. But I'm having a hard time understanding why it outputs the "try again" message even if results shows up
Thanks!
As commented, the while ($groups -eq $null) already tests for 'nothing found', so you need not test that again inside the loop.
I would suggest a slightly different approach using an endless while loop you break out of if the Get-ADGroup cmdlet returned any results
while ($true) {
$group = Read-Host "Which groups would you like to search for?"
# if the user did not enter an empty of whitespace-only string
if (![string]::IsNullOrWhiteSpace($group)) {
# Get-ADGroup by default already returns these properties:
# DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
# so in this case, only ask for the extra Description property
$groups = Get-ADGroup -Filter "Name -like '$($group)_*'" -Properties Description
if ($groups) {
# output the two properties
$groups | Select-Object SamAccountName, Description
# and exit the while loop
break
}
}
# once here, you didn't find any groups on the input keyword, so let the user try again
Write-Verbose "Did not find any matching groups. Try again" -Verbose
}
Note:
-Filter should be a string rather than a scriptblock
using -Properties * to ask for all is very wasteful if all you eventually care about is two properties.
comparing to $null can be done better with if($groups) as opposed to if ($groups -ne $null) and if(!$groups) as opposed to if ($groups -eq $null). If you must compare to $null, then better change the order like if ($null -eq $groups)
I used the sub expression operator $() in "Name -like '$($group)_*'", because otherwise, PowerShell will try and expand an undefined variable $groups_. An alternative to this is to use "Name -like '${group}_*'"

Can I not use a variable in with Get-ADUser

I have a variable I pull from a form that I need to tie in with a matching display name to retrieve an existing samAccountName.
If (Get-ADUser -Filter { (displayName -eq $user) -AND ($Returner -eq "Yes")} ) {
$Check = Get-ADUser -Filter{displayName -eq $user} -Properties SamAccountName
$sam = $check.SamAccountName
$sam
}
As soon as I have the -AND ($Returner.....) part in there the check fails to execute.
I need that check in there as that is what is passed from the Cherwell form to flag that a user is a returner and then I am going to pull in the current samAccountName for that person.
Can someone assist on how I should be using a check of a parameter in with the Get-ADUser command.
Many thanks
S.
I don't see why you would perform the same Get-ADUser command twice..
You can do this like below:
$adUser = Get-ADUser -Filter "DisplayName -eq '$user'" -Properties DisplayName, SamAccountName
$sam = if (($adUser) -and $Returner -eq "Yes" ) { $adUser.SamAccountName }
$sam
Hope that helps
You are using $Returner inside of the -filter of get-aduser. If I understand correctly, this is a variable created by a form.
You should check for $Returner inside of the if statement:
If ( (Get-ADUser -Filter { displayName -eq $user}) -AND ($Returner -eq "Yes")) {
$Check = Get-ADUser -Filter{displayName -eq $user} -Properties SamAccountName
$sam = $check.SamAccountName
$sam
}

Get-ADUser -filter parsing

I am running a script which takes a person's first and last name from an SAP extract, and reads AD to get their UPN. For most people, this works; however there are a bunch of users whose first name is an issue. For instance "Philip Davies" (names changed to protect the innocent) in SAP is "Phil Davies" in AD. So: I have used the following command and it works:
Code:
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -eq "Phil" -and Surname -eq "Davies"}
I then realised I can check for the first three characters which will NORMALLY be the same in the contracted name... so I did this which also works:
Code:
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -like "Phi*" -and Surname -eq "Davies"}
Next step: variables; so I try this and it works:
Code:
$fna="Phil"
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -eq $fna -and Surname -eq "Davies"}
But if I try this:
Code:
$fna="Philip"
$fna=$fna.Substring(0,3)
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -like $fna* -and Surname -eq "Davies"}
I get no result. It doesn't matter if I use brackets, double-quotes, single-quotes, anything. As soon as I try to parse a variable AND use a wildcard, it either produces an error message or no result.
Can anyone please help me with this either by using the "-ldapfilter" method or telling me how to parse AND wildcard?
Thanks
You should not use the wildcard with a variable since you wish to check it with a name which is a string. So what you can do is directly wrap the string with the wildcard and store the final thing in a variable like:
$fna="Philip"
$fna="$($fna.Substring(0,3))*"
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -like $fna -and Surname -eq "Davies"}
or you can use the LDAP Filter directly like :
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -LDAPFilter "(&(GivenName=$fna)(Sn=Davies))"
Hope it helps.

Filter displayname for parentheses error

My script won't send any information to my .txt file except the headers. I want to find any display names that may contain (), /, _ and so forth. Am I not able to use * symbol to mean that I want any display name filtered that contains a "(" anywhere in the name?
#Grab some AD attributes for the specific user ID
$userid = Get-ADUser -filter {displayname -like '*(' -or displayname -like '*_' -or displayname -like '*/'} -SearchBase "OU=Corporate,DC=we,DC=dirsrv,DC=com" -Properties name, displayname, description, manager
Trying to make it show up in my txt file but still new to powershell
#Grab some AD attributes for the specific user ID
$userids = Get-ADUser -Properties name, displayname, description, manager -filter {displayname -like '*(*' -or displayname -like '*_*' -or displayname -like '*/*'}
#THIS IS THE FOREACH I'M TRYING TO MAKE WORK
foreach ($userid in $userids)
{
$ID = Get-AdUser ($userid.displayname) -Properties displayname
$userid = $ID.displayname
}
foreach ($userid in $userids)
{
#manager missing
if ($userid.Manager -eq $null) {
$owner = "MISSING"
$ownerid = "MISSING"
$ownername = "MISSING"
} else {
#grab the manager's name, surname, and department
$owner = Get-ADUser ($userid.Manager) -Properties GivenName, Surname
$ownerid = $owner.Name
$ownername = $owner.Surname + "." + $owner.GivenName
}
}
What I'm making so far. Not having good luck tho lol
When you use the -like operator like you are, you are looking for strings that end in (,_, etc. Instead you need to surround the character you are looking for with wildcards:
{displayname -like '*(*' -or displayname -like '*_(*' -or displayname -like '*/*'}
Alternatively, for a more succinct query, you could use a regular expression:
{displayname -match '[\(\)\\_]'}
Note that since (,), and \ are special regular expression characters, you have to escape them with \.
WOW so if I input the code
Get-AdUser -Properties displayname -filter {displayname -like '*(*'} | Select displayname
Then it will give me all the listings I need of the displayname..... note to self!
Now to connect it with my code :P

Powershell variables in Get-AdUser

I'm trying to write a simple powershell script.
Get-ADuser -Filter {GivenName -eq $GivenName $hateList} -SearchBase $Container -Properties displayName,telephoneNumber,department|ForEach-Object {"FullName`t: $($_.displayName)`r`nPhone`t`t: $($_.telephoneNumber)`r`nDepartment`t: $($_.department)`r`n"}
The error what I got:
Get-ADUser : Error parsing query: 'GivenName -eq $GivenName $hateList' Error Message: 'syntax error' at position: '26'.
So the problem is that the variables aren't substituted with their values. What do I do wrong?
You Filter parameter is not right. If you want to have GivenName be equal to $GivenName you should do it like this:
{GivenName -eq $GivenName}
If you want it to be equal to $GivenName or $hateList, whatever it is, you should try something like:
{(GivenName -eq $GivenName) -or (GivenName -eq $hateList)}
Check this link for more filter:
http://technet.microsoft.com/en-us/library/ee617241.aspx
You can first get list of users with filter like this:
{GivenName -eq $GivenName}
And the do some post processing:
$users | Where-Object { $hateList -notcontains $_.cn }
If variable expansion doesn't work when passing the variable, try to pass it enclosed in quotes:
{GivenName -eq "$GivenName"}