Get SamAccountName from list of various names - powershell

I have a list of names taken from Oracle that Im trying to find the SamAccountName for. The file is a CSV and some names are "last, first" or "last, first middle initial" and some have three or four names like "alpha bravo charlie delta". The names in the list are likely not the same as listed in AD. Trying to figure out how to sort through this to find AD accounts. The code I currently have is not producing any results.
Import-Module ActiveDirectory
Import-Csv "\\server\users\folder\Oracle_HR.csv"
ForEach-Object{
Get-ADUser -Filter { Name -like "'$($_.name)'"} -Properties Name |
Select-Object Name,SamAccountName |
Export-CSV "\\server\users\folder\Oracle_ADs.csv" -NoTypeInformation
}

The answers by Gabriel Luci and Mathias R. Jessen give good advice on "fuzzy" filtering of AD users.[1]
However, your primary problem is that your ForEach-Object call is not receiving pipeline input, because you haven't connected it to output from the Import-Csv call.
Simply join the two commands with |:
Import-Csv "\\server\users\folder\Oracle_HR.csv" | ForEach-Object { # ...
Secondarily, your -Filter argument { Name -like "'$($_.name)'"} mistakenly applies two layers of quoting and is missing wildcard characters, given that -like compares against the entire field, yet you want substring matching.
Since it's better to avoid the use of script blocks ({ ... }) as -Filter arguments, use a string:
"Name -like `"*$($_.name)*`"" # Note the enclosing '*' to match substrings
Note that I've used embedded " quoting (escaped as `") rather than ' quoting, so as not to break the filter with names that contain ', such as O'Malley.
That said, if, as your question suggests, the names in your CSV data aren't direct substrings of the AD users' .Name property values, the above filter will not be enough, and even the ANR (Ambiguous Name Resolution) technique shown in the linked answers may not be enough.
Thirdly, your Export-Csv call is misplaced: because it is inside the ForEach-Object script block, the same output file gets overwritten in every iteration.
Restructure your command as follows:
Import-Csv ... | ForEach-Object { ... } | Export-Csv ...
Optional reading: ForEach-Object behavior when not providing pipeline input:
The associated script block is executed once.
$_, the automatic variable that contains the current input object, is $null.
[1] Note that the search term in the LDAP filter may need escaping ; per this article, the characters * ( ) \ NUL require escaping and must be escaped as \<hh>, where <hh> is the two-digit hex representation of the char's ASCII code (e.g., * must be escaped as \2A):
$escapedName = -join $(foreach ($c in [char[]] $_.name) { if ('*', '\', '(', ')', "`0" -contains $c) { '\' + ([int] $c).ToString('X2') } else { $c } })
Get-ADUser -LDAPFilter "(anr=$escapedName)"
With $_.name containing string "James* (Jimmy) Smith\Smyth`0", $escapedName would evaluate to literal James\2A \28Jimmy\29 Smith\5CSmyth\00

Keep in mind that the property names in PowerShell are not named the same as the attributes in AD. The Name property corresponds to both the name and cn attributes in AD (both attributes are always the same).
There is also DisplayName (displayName in AD), GivenName (givenName), and Surname (sn). You could try matching against the DisplayName:
Get-ADUser -Filter "DisplayName -eq '$($_.name)'"
If none of those properties match your data exactly, you will have some trouble. No one thing you do will probably work for every account. Hopefully this is just a one-time job and you can work through them in pieces (try one thing, take out the ones that work, and try something different on the rest).
One thing you can try is using AD's Ambiguous Name Resolution (ANR), which will match a search string against several different attributes and even match a first and last name against givenName and sn. That might work with some in your list. You would use it like this:
Get-ADUser -LDAPFilter "(anr=$($_.name))"
If none of that works, you'll have to split the names (for example, by spaces: $_.name.Split(" ")) and try to match pieces of it to different attributes. You'll have to look at your data and see what works.

One approach is to use the Ambiguous Name Resolution feature in Active Directory.
It'll do fuzzy matching against multiple attributes, like the displayName, Name and mail attributes (among others), so it's pretty good for this exact kind of scenario where you don't necessarily know the order or the names or the full name up front:
Get-ADUser -LDAPFilter "(&(anr=$($_.name)))"

I recommend using LDAPFilter and Ambiguous Name Resolution (anr) with Get-ADUser. The algorithm looks up several name fields in different orders to find matches:
Get-ADUser -LDAPFilter "(anr=John Doe)"
Or modifying your code:
Get-ADUser -LDAPFilter "(anr=$($_.name))"

You could try something like the following:
Import-Module ActiveDirectory
$allUsers = Get-Content "\\server\users\folder\Oracle_HR.csv"
$users = #()
ForEach($obj in $allUsers){
$user = Get-ADUser -Filter { GivenName -like $obj} -Properties Name, samAccountName
if(!$user){
$user = Get-ADUser -Filter { SurName -like $obj} -Properties Name, samAccountName
}
if(!$user){
$user = Get-ADUser -Filter { Name -like $obj} -Properties Name, samAccountName
}
if(!$user){
Write-Host "User $obj could not be found" -ForegroundColor Red
}else{
$users += $user
}
}
$users | Select-Object Name,SamAccountName | Export-CSV "\\server\users\folder\Oracle_ADs.csv" -NoTypeInformation
You might need to split the values also like:
Import-Module ActiveDirectory
$allUsers = Get-Content "\\server\users\folder\Oracle_HR.csv"
$users = #()
ForEach($obj in $allUsers){
$objSplit = $obj.Split(",")
foreach($split in $objSplit){
$user = Get-ADUser -Filter { GivenName -like $split} -Properties Name, samAccountName
if(!$user){
$user = Get-ADUser -Filter { SurName -like $split} -Properties Name, samAccountName
}
if(!$user){
$user = Get-ADUser -Filter { Name -like $split} -Properties Name, samAccountName
}
if(!$user){
Write-Host "User $split could not be found" -ForegroundColor Red
}else{
if($users.samAccountName -notcontains $user.SamAccountName){
$users += $user
}
}
}
}
$users | Select-Object Name,SamAccountName | Export-CSV "\\server\users\folder\Oracle_ADs.csv" -NoTypeInformation

Related

Powershell AD: filter description -like $variable => contains $variable

My task include to filter all users names in group and subgroup in AD. Continue to filter the computers and show just those, which contains filtered names.The problem is, that description includes also other characters like space or "NEW".
My code:
foreach ($file in Get-ADGroupMember -Identity GroupName -Recursive) {Get-ADComputer -Filter 'Description -like $file.name' -Property Name,Description | Select -Property Name,Description}
It would be great to just add * or change -like to -include :D But...
My begginers question is: How to write the code to see all results, not just the ones which match exactly the $file.name?
Thank you for ur time!
Your initial problem was in the Filter you used. With the correct quoting and using the sub-expression operator $() that fixed it.
However, as promised in my comment, here's what I mean on how you can create a report of group members (both users, computers and if you like also subgroups).
Since all objects returned from the Get-ADGroupMember cmdlet have an .objectClass property, you can use that to determine what next Get-AD* cmdlet you can use.
Here, I'm capturing the collected objects output in the foreach() loop in a variable that you can show on screen, or save as Csv file you can open in Excel for instance.
$groupName = 'GroupName'
$result = foreach($adObject in (Get-ADGroupMember -Identity $groupName -Recursive)) {
# use the proper Get-AD* cmdlet depending on the type of object you have
switch ($adObject.objectClass) {
'user' {
$adObject | Get-ADUser -Properties Description | Select-Object Name, Description, #{Name = 'Type'; Expression = {'User'}}
}
'computer' {
$computer = $adObject | Get-ADComputer -Properties Description
# you want to output only the computers where the Description property holds the computer name
if ($computer.Description -like '*$($computer.Name)*') {
$computer | Select-Object Name, Description, #{Name = 'Type'; Expression = {'Computer'}}
}
}
# perhaps you don't want subgroups in your report, in that case just remove or comment out the next part
'group' {
$adObject | Get-ADGroup -Properties Description | Select-Object Name, Description, #{Name = 'Type'; Expression = {'Group'}}
}
}
}
# show the result on screen
$result | Format-Table -AutoSize
# save the result as Csv file
$outFile = Join-Path -Path 'X:\Somewhere' -ChildPath ('{0}_members.csv' -f $groupName)
$result | Export-Csv -Path $outFile -NoTypeInformation -UseCulture
The -UseCulture switch makes sure the Csv file uses the delimiter character your local Excel expects. Without that, a comma is used
Interesting reads:
about_Operators
Adam the Automator
Learn Powershell | Achieve More
and of course StackOverflow

PowerShell filter by OU

Import-Module ActiveDirectory
Get-ADComputer -Filter {enabled -eq $true} -properties *|select Name,
| Out-File -FilePath c:\Powershell.txt
I am trying to export a list to txt file and have it display a list of all the computers on my domain by name and the OU or group it is assigned to. i am able to retrieve the name with this, but would like to ad a OU Colum.
Since the DistinguishedName value contains the OU RDN, we can extract it with a bit of string splitting magic:
Get-ADUser -Filter * |Select Name,#{Name='OU';Expression={$_.DistinguishedName -split '(?<!\\),' |Select -Index 1}}
This will give us only the RDN (ie. OU=Company Users), if you want the full DN of the OU, do:
Get-ADUser -Filter * |Select Name,#{Name='OU';Expression={$_.DistinguishedName -split '(?<!\\),',2 |Select -Skip 1}}
The pattern (?<!\\), will match any , in the DN only if not preceded by \ - this is to avoid splitting on escaped ,'s, like in CN=LastName\, FirstName,OU=Users,...
Honestly, I would derive the OU from the DistinguishedName value. It will be quicker than running additional ActiveDirectory module PowerShell commands. You can then output the OU value using Select-Object's calculated properties. I would also recommend outputting to CSV (using Export-Csv) since that format is easily readable by PowerShell and other file editing tools.
Get-ADComputer -Filter 'Enabled -eq $true' |
Select-Object Name,#{n='OU';e={$_.DistinguishedName -creplace '^.*?,(?=[A-Z]{2}=.*)'}} |
Export-Csv -Path c:\Computers.csv
Note that the CSV export will have a header row and values will be delimited by comma. If you prefer a different delimiter, you can use the -Delimiter parameter or your PowerShell session's default list separator with the -UseCulture switch.
-creplace is a case-sensitive version of -replace operator.
^.*?,(?=[A-Z]{2}=.*) is regex syntax for matching the text to replace. ^ denotes the start of the string. .*?, matches a few characters as possible until a , is matched. But since a CN value can contain , characters, we only want to stop matching when it precedes OU= or DC=. This is why we have positive lookahead (?=[A-Z]{2}=.*). [A-Z]{2} matches exactly two capital letters followed by =.
This what I do, it is a bit slower than the other examples provided but it will prevent any timeout on the Get-ADcomputer cmdlet. I'm also using CanonicalName to have an absolute path of the OU because OUs can have the same name and Canonical is easier to read than Distinguished.
$OUs = Get-ADOrganizationalUnit -Filter * -Properties CanonicalName
$Result = foreach($OU in $OUs)
{
$hash = #{
Filter = 'Enabled -eq $true'
SearchScope = 'OneLevel'
SearchBase = $OU.DistinguishedName
}
foreach($computer in Get-ADComputer #hash)
{
[pscustomobject]#{
ComputerName = $computer.Name
OU = $OU.CanonicalName
}
}
}

Export user from multiple groups

Good Morning Guys,
I write this script to export multiple users in multiple groups in a CSV file.
In addition to not exporting anything, I cannot insert a column in the CSV where the user's appatenency group is specified. Just the one with the name "vpn-*", like vpn-users
Powershell Version 4.0
$Data = $UserData = #()
$GroupName = Get-ADGroup -Filter {name -like "VPN-*"} -Properties Name | Select-Object Name
Foreach ($group in $GroupName)
{
$UserData = Get-ADGroupMember -Identity {$group}
Where objectClass -eq 'user' |
Get-ADUser -Properties Name, UserPrincipalName, description, Enabled |
Select-Object Name, UserPrincipalName, description, Enabled
}
$UserData | export-csv "c:\members2.csv"
I see a number of issues with the posted code. Some are mere preferences, but others look like they would affect the outcome.
-Properties Name isn't needed in the initial Get-ADGroup command. The Name property is returned by default.
Respectful to #Theo's comment re: -ExpandProperty, however, I prefer not to use that unnecessarily. You don't even need the first Select-Object command, just reference the property and it will unroll and return a string array. Property unrolling is supported as of PowerShell Version 3.
Your argument to the -Filter parameter should be a string. I myself have a hard time breaking the habit of wrapping those queries in script blocks {...}, however, there are some specifics of the AD cmdlets, and using a string is a best practice. Basically, the argument takes a string type, if you give it a script block it will convert it to a string and that process may not always work as desired.
It's better to store your AD properties in an array you can cite multiple times. Normally you would've only needed to add 'Description' but considering you were also using it in a later Select-Object command it makes more sense to add all the desired properties to an array.
Personally, I prefer not to use simplified syntax. I don't know what the community's opinion is on that but I rewrote using my preference.
You were also missing |' before the Where-Object command.
And, yes you would have to move the Export-Csv inside the loop to output data per loop iteration. Using the -Append parameter to avoid overwriting it on every iteration.
Untested Example:
$ADProps = 'Name', 'UserPrincipalName', 'description', 'Enabled'
$GroupName = (Get-ADGroup -Filter "name -like 'VPN-*'" ).Name
Foreach ( $Group in $GroupName )
{
$UserData =
Get-ADGroupMember -Identity $Group |
Where-Object{ $_.objectclass -eq 'user' } |
Get-ADUser -Properties $ADProps |
Select-Object ($ADProps += #{Name = 'Group'; Expression = { $Group }})
$UserData | export-csv "c:\members2.csv" -NoTypeInformation -Append
}

get-aduser using emailaddress

when i want to get some information from an user i use this:
Get-ADUser -Filter {EmailAddress -eq 'jperez#dominio.com'}
but when i wanna check the information from a bulk of users i try this:
$batch| foreach {Get-ADUser -Filter {emailaddress -eq $_.email}}
email is the name of the variable in the CSV file
but i am getting this error:
"Get-ADUser : Property: 'email' not found in object of type: 'System.Management.Automation.PSCustomObject'"
i can not use the identity because te emailaddess is not supported for this one
It doesn't look like you are setting up properties for the search result to return. Ie:
Import-csv -Path \\tsclient\c\temp\test.csv -delimiter ";" | ForEach {
Get-ADUser -Filter "EmailAddress -eq '$($_.email)'" -Properties EmailAddress
}
What kind of format are you getting this information in?
Personally, I like to make a temporary file then query using a variable in the for loop. For instance, if I had a file that was a list of email addresses at C:\Users\MyUser\Documents\emailList.txt I would do the following:
$my_list = Get-Content C:\Users\MyUser\Documents\emailList.txt
foreach ($x in $my_list){
$x = $x replace '\s',''
Get-ADUser -Filter {EmailAddress -eq $x}
}
This will pull a Get-ADuser for the entire list by email address. It will also remove white space, which has caused me issues in this situation in the past. Let me know if you have further questions or if you have trouble getting the above commands to work.
Or you can do it per invoke-expression.
$content = Get-Content c:\folder\file.txt
foreach ($emails in $content)
{
$command = "get-aduser -Filter {emailaddress -eq ""$emails""} | select -ExpandProperty SamAccountName"
Invoke-Expression $command
}
Works too :)
Another quick solution is to only pass the property that you want to filter on to the filter expression (this works well when working with CSV imports). Using your example it would change to:
$batch.email| foreach {Get-ADUser -Filter {emailaddress -eq $_}}

Escape apostrophes from variable in powershell

I have the following script set up, and it works as intended....except for users with apostrophes in their email.
$users = get-content C:\Filename.csv
$results = Foreach ($user in $users)
{
get-aduser -filter "EmailAddress -like '$user'" -properties CanonicalName,LastLogon,Name |
select Name,#{N="Thing";E={$_.DistinguishedName.Split(',')[-4]}},#{N="Place";E={$_.DistinguishedName.Split(',')[-5]}},#{N="Last Logon";E `
={[DateTime]::FromFileTime($_.Lastlogon)}}
}
$results | Export-Csv C:Filename.csv -NoTypeInformation
Does anyone know how to escape the apostrophe in an email like example_o'connor#example.com? Whenever I run the above script it always errors out on email addresses like the one above.
Edit: My csv file is a single column of email addresses with no header.
Edit 2: Sorry to waste everyone's time. Turns out the script was working fine, along with some of the suggestions in this thread such as adding "" "" around my variable, but it was that I was testing against a list where not all the values were correct so that is my fault. Thank you everyone for your time.
Try this...
Since you are using a CSV, I imagine you've piped them from another AD cmdlet.
Get-Member is a great tool here.
$users | Get-Member will output TypeName: CSV:Selected.Microsoft.ActiveDirectory.Management.ADUser
However, this is not a String type which the Filter parameter in ADUser needs.
So to convert this...
$selection | Get-Member will output TypeName: System.String.
The other portion is to make sure that the -Filter parameter in Get-ADUser is expanding the strings properly one-by-one, since Get-ADUser's -Filter parameter cannot deal with String Arrays.
$users = Import-Csv C:\filename.csv
$selection = ($users.emailaddress)
foreach ($user in $selection)
{
get-aduser -filter {EmailAddress -eq $user} -properties CanonicalName,LastLogon,Name |`
select Name,#{N="Thing";E={$_.DistinguishedName.Split(',')[-4]}},`
#{N="Place";E={$_.DistinguishedName.Split(',')[-5]}},`
#{N="Last Logon";E={[DateTime]::FromFileTime($_.Lastlogon)}}
}