Finding users in AD - powershell

I am trying to use a text file of users e-mail address to find the samaccountname names of the corresponding users.
Clear-Host
Import-Module ActiveDirectory
$File = "C:\T2\Users.csv"
$Users = Get-Content $File
ForEach ($User in $Users)
{ Get-ADUser -Filter * | Where { $_.EmailAddress -eq $User } | Select SamAccountName -ExpandProperty SamAccountName }
I am trying to understand what I am doing wrong

If your file is actually a .csv (comma-separated values), what you're doing is getting raw string content with Get-Content. There is a cmdlet, Import-Csv, that will take your CSV and turn it into a powershell object so you can iterate over it and access the headers as properties like you're trying to do in your code:
$users = Import-Csv -Path '/path/to/file.csv'
Then in your loop, you can clean up and speed up your code by not querying the entire AD tree for each user:
foreach ($user in $users)
{
Get-ADUser -Filter "EmailAddress -eq '$($user.EmailAddress)'" |
Select-Object -ExpandProperty SamAccountName
}
Super simplified version:
#requires -Module ActiveDirectory
foreach ($user in Import-Csv -Path '/path/to/file.csv')
{
(Get-ADUser -Filter "EmailAddress -eq '$($user.EmailAddress)'").SamAccountName
}

Related

Powershell for get-aduser for multiple users from a csv file with foreach

I am trying to get info of some users. I have a CSV file with their name test1.csv to get the required details I am using:
$name = import-csv test1.csv | select -expand name
foreach ($user in $name) {get-aduser -filter 'name -eq $user'}
But there is no output.
Thanks in advance
The comments are correct that all you need to do is specify -filter "name -eq '$user'".
However, often you can use this method to get all the users at once, which often works much faster:
$LDAPFilter = Import-Csv -Path test1.csv | ForEach-Object -Begin { '(|' } -Process { "(name=$($_.Name))" } -End { ')' }
$LDAPFilter = -join $LDAPFilter
Get-ADUser -LDAPFilter $LDAPFilter

use samaccountnames to export user properties(mainly just first name and lastname) to csv file

I have a CSV file containing the samaccount name of some users.
From this list, I want to export the properties of these users to a CSV file.
Kindly share the simplest possible way to do so in Windows Powershell ISE.
I have tried this :
Import-ModuleActiveDirectory
Import-CSV C:\scripts\list.csv | ForEach{Get-ADUser -Identity $samaccountname-Filter*-Properties*|export-csv c:\ADusers.csv
}
Thank you!
You didn't show us the first couple of lines of the CSV file.
A proper CSV file has multiple fields and a header line like this:
"AccountName","EmailAddress"
"doe","john.doe#example.com"
"kent","clark.kent#example.com"
If this is the case, do:
Import-ModuleActiveDirectory
$userProperties = 'GivenName', 'SurName', 'Initials'
Import-Csv -Path "C:\Scripts\List.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$($_.AccountName)'" -Properties $userProperties -ErrorAction SilentlyContinue
if ($user) {
$user | Select-Object -Property $userProperties
}
} | Export-Csv "C:\ADUsers.csv"
If the file you load only has SamAccountNames each listed on a new line, then this is not a CSV file and you should use:
Import-ModuleActiveDirectory
$userProperties = 'GivenName', 'SurName', 'Initials'
Get-Content -Path "C:\Scripts\List.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$_'" -Properties $userProperties -ErrorAction SilentlyContinue
if ($user) {
$user | Select-Object -Property $userProperties
}
} | Export-Csv "C:\ADUsers.csv"
As you can see, I'm not using the -Identity parameter here, because in case a user with that SamAccountName is not found, an exception is thrown.
This way, output is only generated when the user actually exists.
Also, it is a bad idea to use -Properties * when you only want some of the properties returned.
Hope that helps
if you wanna do this in the ISE, you probably dont need/want to use oneliner for that.
I would suggest to import the CSV first, and then run foreach.
$list = Import-CSV -path $filePath
$result = New-Object System.Collections.ArrayList
foreach ($name in $list){
$adUser=Get-ADUser -Identity $name
$result += $adUser
}
From here, you can start thinking of error handling etc.
This will help you:
Import-ModuleActiveDirectory
Import-CSV -Path "C:\Scripts\List.csv" | Foreach {
Get-ADUser -Identity $_ -Filter * -Properties *
} | Export-CSV "C:\ADUsers.csv"
Your code was not working because $samaccountname was empty and blank not containing the username. So I replaced it with the automatic variable $_
Put each SamAccountName on its own line in the list file.
Example:
user1
user2
user3
Change list.csv to a text file (list.txt) and try this:
$username = Get-Content "C:\scripts\list.txt"
ForEach($user in $username){
Get-ADUser -Identity $user | Select GivenName,Surname,Initials | Export-CSV -Path "C:\ADUsers.csv"
}

Compare list of computer from text file with AD-User property

I new in Powershell world and trying to write a script which perform following:
Get List of Computers from a text file
Get list of Users from a text file
Control if the computer name is added in LogonWorkstations field in each user account
Here is the script I have written as of yet.
$Computers = Get-Content Computers.txt
$Users = Get-Content -Path Users.txt | Sort-Object -Unique
$ADUsers = Get-ADUser -Filter * -Properties LogonWorkstations -SearchScope Subtree -SearchBase "OU=ck,OU=users-com,DC=domain,DC=com" |
Where-Object {$Users -contains $_.Name} | Format-List Name,LogonWorkstations
As the script shows I read and retrieve property for Users and have list of computers in text file.
There are 50+ computers and users my question is how can I compare this line wise example check if computer from line 1 of Computers.txt exist in LogonWorkstations property of user from line 1 of Users.txt?
If each line of both files are corresponding, you can use a simple for loop to iterate through both lists simultaneously. $ADUsers will contain the output of ADUser objects matching the conditions.
$ADUsers = for ($i = 0; $i -lt $Users.Count; $i++) {
Get-ADUser -Filter "Name -eq '$($Users[$i])'" -Properties LogonWorkstations |
Where-Object { ($_.LogonWorkstations -split ',') -contains $Computers[$i] }
}
Since LogonWorkstations contains a comma-separated string, you will have to do some string manipulation. Using the -split operator on the , character will result in an array of strings. The -contains operator works nicely when comparing an item or collection of items to a single item.
If you want to compare the LogonWorkstations value of a user to any computer in the list, you can do something like the following:
$ADUsers = foreach ($User in $Users) {
Get-ADUser -Filter "Name -eq '$User'" -Properties LogonWorkstations | Where-Object {
Compare-Object -Ref ($_.LogonWorkstations -split ',') -Dif $Computers -IncludeEqual -ExcludeDifferent
}
}
Compare-Object here will only return a value if there is an exact match.
Note: I believe the LogonWorkstations attribute has been replaced with UserWorkstations attribute. Both may work now but may not be guaranteed in the future.
I haven't tried the below code but hopefully, you will be able to work out any little issues:
$computers = Get-Content -Path #PATHTOCOMPUTERS.TXT
$users = Get-Content -Path #PATHTOUSERS.TXT | Sort-Object -Unique
#Set a counter to zero
$counter = 0
foreach ($user in $users){
try{
#Get the current user from AD
$adUser = Get-ADUser -Filter { Name -eq $user} -Properties LogonWorkStations -ErrorAction Stop
#Uses the current index using $counter to get the correct computer from computers.txt and
#checks if the user has it setup as a LogonWorkStation
if ($adUser.LogonWorkstations -eq $computers[$counter]){
Write-Host "$user has $computer as a logon workstation"
}else{
Write-Host "$user doesn't have $computer as a logon workstation"
}
}catch{
Write-Host "Failed to get the AD user"
}
#Increment the $counter
$counter++
}

Cannot get information from Get-ADUser to output to CSV

I have a SUPER simple query of Get-ADUser select mail that I need to output to CSV. The query fetches the information that I am looking for and prints to screen but when I attempt to use the Export-Csv OR Out-File cmdlets it creates a blank document.
$Users = Import-Csv C:\users\bob\Desktop\Administrator.csv
foreach ($User in $Users) {
$User = $User.UserName
Get-ADUser $User -Properties * |
Select mail |
Export-Csv -Path C:\Users\miker99a\Desktop\DiscoveryED.csv
}
Im a chucklehead. The answer is -append, I was overwriting the entries as the script ran
$Users = Import-Csv C:\users\bob\Desktop\Administrator.csv
foreach ($User in $Users) {
$User = $User.UserName
Get-ADUser $User -Properties * | Select mail | Export-Csv -Path C:\Users\miker99a\Desktop\DiscoveryED.csv -Append
}

Getting user name through AD using powershell

I've been banging my head against this for a while and can't figure out why this isn't working.
Import-Module ActiveDirectory
$Users = Get-ADGroupMember -identity “Accounting” -recursive | select name | export-csv -path "D:\group.csv"
$csv = Import-Csv "D:\group.csv"
foreach ($user in $csv) {Get-ADUser -filter "'Name -eq ""$user""'"}
You have a couple of issues here I think.
You export the data just to import it again. Do you even need a second copy of the data?
Import-Csv will return an object array not just the names. There is more than one way to address this but this should be more what you are looking for
Import-Module ActiveDirectory
$Users = Get-ADGroupMember -identity “Accounting” -recursive | select name
foreach ($user in $Users) {Get-ADUser -filter {Name -eq $user.Name}}
Even that is more than it needs to be. Its redundant since Get-ADGroupMember already returns similar objects you need. What do you need to do with this data? If you really need Get-AdUser then just pipe the output to it.
Get-ADGroupMember -identity “Accounting” -recursive | Get-Aduser
$user is a row in the CSV file. You need to address the Name field of that row (you also have way too many single- and double-quotes).
foreach ($user in $csv) {Get-ADUser -filter "Name -eq '$($user.name)'"}
Or you could make the CSV file just a vanilla listing of names, and not read it as CSV:
Get-ADGroupMember -identity “Accounting” -recursive | select -expandproperty name | out-file "c:\group.txt"
$csv = get-content -path "c:\group.txt"
foreach ($user in $csv) {Get-ADUser -filter "Name -eq '$user'"}
But if you're only using the file as a conduit between the group search and the user lookup, you can skip that entirely by piping the output of Get-ADGroupMember directly to Get-ADUser.
Get-ADGroupMember -identity “Accounting” -recursive | Get-ADUser;