I have a CSV file that looks like this:
name
fname1lname1#companyemail.com
fname2lname2#companyemail.com
...
I would like to loop through each email address and query AD for that address to grab the user objects ID. I have been able to do this using a script, but I would like to be able to do it using just one line.
This is what I've done so far:
import-csv -path .\csv_file.csv | foreach-object { get-aduser -filter { proxyaddresses -like "*$_.name*} | select name } | out-file .\results.csv
This obviously doesn't work and I know it has something to do with how I am handling my $_ object in the foreach loop.
I'm hoping for the output to look something like:
fname1lname1#companyemail.com,userID1
fname2lname2#companyemail.com,userID2
...
You are filtering on the property proxyaddresses however that is not part of the default property set that Get-AdUser returns. Also your code had a errant " which might have been a copy paste error.
Import-CSV -Path .\csv_file.csv | ForEach-Object {
Get-ADUser -Filter "ProxyAddresses -like '*$($_.name)*'" -Properties ProxyAddresses,EmailAddress | select EmailAddress,SamAccountName
} | Export-CSV .\results.csv -NoTypeInformation
-Filter can be tricky sometimes as it is looking for string input. Wrap the whole thing in quotes and use a sub expression to ensure that the variable $_.Name is expanded properly and has is asterisks surrounding it.
Since you are also looking for emailaddress we add that to the properties list as well. I will assume the second column is for samaccountname.
We also use Export-CSV since that will make for nice CSV output.
If you're using Exchange this can be much simpler and faster if you use the Exchange cmdlets:
Import-CSV -Path .\csv_file.csv | ForEach-Object {
Get-Recipient $_ |
Select PrimarySMTPAddress,SamAccountName
} | Export-CSV .\results.csv -NoTypeInformation
Exchange requires all email address to be unique, and maintains it's own internal database that uses email address as a primary index so it can return the DN and SamAccountName that goes with that email address almost immediately.
AD doesn't require them to be unique, so it doesn't index on that attribute and it has to search every user object looking for the one that has that email address in it's proxy address collection.
Related
I got user information from the user group in AD. every column has no problem except the user name.
On csv, User name is normal but there is a format when I get content from csv for using powershell like as below;
#{Name=abc}
for compare-object with two CSV, I need to use -expand.
Is there anyway to avoid this result?
I want to get a same content on CSV and powershell.
get-adgroup $path -server server.com | get-adgroupmember -recursive | select-object -unique | get-aduser -properties mail | name, mail | export-csv c:\result.csv
Use import-csv cmdlet to import the csv and not get-content. Also the provided code sample won't work - e.g. you missed select-object here:
| name, mail |
You do not need to query the group, as you already know the name ($path), you can directly query the groupmemberships, e.g.:
get-adgroupmember -identity $path -recursive
But in the end you could achieve the same in a much more efficient way, e.g.:
get-aduser -LDAPFilter "(memberOf:1.2.840.113556.1.4.1941:=[groupDistinguishedName])" -property mail | select-object -property mail,name | export-csv [path]
replace [groupDistinguishedName] with the distinnguishedName of the group. This will give you all users back which are member (transitive) of the defined group.
see: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/4e638665-f466-4597-93c4-12f2ebfabab5
I have a CSV list of usernames from all over my domain, and I'm trying to compare the list against a specific OU and send the matches to another file. I'm brand new to powershell, so after a good amount of research and comparing with other scripts I came up with this:
$users = Import-csv C:\Users\me\Desktop\'RSA.csv'
$(ForEach ($user in $users)
{
Get-AdUser -identity $user -SearchBase "ou=Sub,ou=Root,dc=My,dc=Domain,dc=Name" -Filter *
}) |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
When I run this I get the error "Get-ADUser : Cannot validate argument on parameter 'Identity'. The Identity property on the argument
is null or empty." If I run without the -identity $user it just pulls everything. Any suggestions on how to make this work?
When you are calling Get-ADUser rather than giving it a string with just the user name you are passing in an object with a property called username. You could use Select-Object -ExpandProperty Username or reference the just property.
Import-Csv 'C:\Users\me\Desktop\RSA.csv' |
Where-Object {(!([string]::IsNullorWhiteSpace($_.UserName)))} |
ForEach-Object {
Get-ADUser -Identity $_.UserName
} |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
Notes: Changed to a ForEach-Object loop for readability since it looked like you where trying to mostly use the pipeline. Also added a test to skip blank lines or usernames that are whitespace/empty string. Removed the SearchBase and Filter since you are looking up based on identity can't use those in the command. As there isn't a parameter set that allows you to use all of them. Get-Help Get-ADUser shows the available parameter sets.
I'm new and don't know enough about powershell.
I've got a .csv that is nothing but "EMAILS" for the header and some 6000 emails under it. (email1#company, email2#company, etc.)
I need to find the state of a particular, custom property for each one.
Individually, I know that I can run
Get-ADUser -Filter {mail -eq 'email#company'} -properties customproperty
in order to find one particular user's state.
I have been hitting my head against a wall trying to make it work with import-csv and export-csv, but I keep getting red all over my console.
Can someone point me an to example where import-csv and export-csv are used properly, with a command run against the contents?
Here's what I would do.
First, fetch all users that have email addresses in AD, and save them into a hashtable. This will make lookups absurdly faster and place less overall load on your domain controller. If you've got 100,000 user accounts it may not be the best option, but I expect that it will be in general.
$ADUsers = #{};
Get-ADUser -Filter "mail -like '*'" -Properties mail, customproperty | ForEach-Object {
$ADUsers.Add($_.mail, $_.customproperty);
}
Now you import the CSV and do lookup using a calculated property with Select-Object, and export it back out.
Import-Csv -Path $InputFile | Select-Object -Property emails, #{n='customproperty';e={$ADUsers[$_.emails]}} | Export-Csv -Path $OutputFile -NoTypeInformation;
So without seeing the code of what you posted, where I think you will run problems is with how interaction of two things.
The first will be that when you use the Import-CSV cmdlet. You will receive an array of objects with a property for each column and not an array of strings.
This is ties into the second part of the issue which is the sensitivity of the AD module filter. But the short answer is don't use {} inside the filter because it will break if you use {mail -eq $ImportedCSV.EMAILS}.
mklement0 has a wonderful answer that goes into the details. But a simple rule of thumb is "double quote outer, single quote" inner.
So you could expand the EMAILS property either with Select-Object -ExpandProperty EMAILS to have an array which works inside {} or you could use "mail -eq '$ImportedCSV.EMAILS'".
Here is an example with both the expansion and using the "property -eq '$variable'" style filter:
Import-CSV C:\Example\Path.csv |
Select-Object -ExpandProperty EMAILS |
ForEach-Object {
Get-ADUser -Filter "mail -eq '$_'" -Properties customproperty
} |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
Please use below code
$csvInput = Import-CSV C:\Example\test.csv
Foreach ($line in $csvinput) {
Get-ADUser -Filter {mail -eq $line.mail} -Properties mail, customproperty |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
}
I am trying to pipe a list of email addresses into a get-user command in powershell
$email = get-content -path "c:\temp\file.csv" get-user -indentity $email | select-object userprincipalname,department,phone,name | format-table | out-file c:\temp\file.txt
Welcome to SO.
Lets see... where to start
Email Address is not one of the value recognized for Identity
It is spelled -identity
Don't use Format-table for object output.
Department is not one of the default values returned.
There is no AD attribute just called phone
It's Get-Aduser not get-user
Don't know if it was just a copy paste accident but you have multiple lines as one.
-Identity expects one value. Not an array of names.
Knowing that lets see if we can take a stab at what you were trying to do. Assuming that your file "c:\temp\file.csv" only contained addresses with no header (since that is how you were treating it.)
Get-Content c:\temp\file.csv | ForEach-Object{
Get-ADUser -Filter "emailaddress -eq '$_'" -Properties department,OfficePhone
} | Select-Object UserPrincipalName,Department,OfficePhone,Name | Export-CSV C:\temp\outputfile.csv -NoTypeInformation
There is no error correction here so you might need to look into an -ErrorAction try/catch combination. I encourage you to look that up on your own.
Im writing a custom script from start to finish to search for users ,so i can disable and move them. (script is done and working)
What im trying to do now is to create a easy readable log which also has to be used as an easy rollback.
I.ex.:
Get-Aduser -Identity test -properties SamAccountName,MemberOf,GivenName,Surname
This will return something in line of:
DistinguishedName : CN=test,OU=OUy,OU=Lab Accounts,DC=domain,DC=org
Enabled : True
GivenName : test
Name : test
SamAccountName : test
Surname : test
Memberof : {CN=OU,OU=Norway,OU=Lab Accounts,DC=Domain,DC=org, CN=Domain Admins,CN=Users,DC=Domain,DC=org}
If i use:
$test2 = Get-ADUser -Identity test |
Select-Object -Property SamAccountName,GivenName,Surname,Memberof
which gives me:
SamAccountName GivenName Surname Memberof
-------------- --------- ------- --------
test test test {}
What my issue now is how to log this to either a csv/text file which can be easily imported back for rollback.
Im currently using clixml which preserves the export ive done with a hashtable within a hashtable.
like:
$user=#{
#{
Username=$user.samaccountname
Memberof=$user.memberOf
}
}
This allows me to more or less use dot notation to access the information stored for easy rollback, but viewing the file is not that easy readable
Which method do you propose me to use to log the info i need when alot of the info is some kind of collection of items?
I've tried to explore with PSobject but i havent gotten the hang of that yet.
Are there any logging method which will output to a easy to read log and easy use for rollback?
If anyone is able to supply an example and also point me to a page to further explore this i will appreciate it very much.
By readerfriendly im thinking of something like this:
Username,Givenname,Surname,Memberof
Test,test2,test3,Admins;somegroup;somegroup
or
Username,Givenname,Surname,Memberof
Test,test2,test3,Admins somegroup somegroup
EDIT 1
Here is the code that gets the info:
Get-ADUser -Identity test -Properties SamAccountName,GivenName,Surname,Memberof |
Select-Object -Property SamAccountName,GivenName,Surname,Memberof | export-csv C:\test.txt
This is what is in the file as output:
#TYPE Selected.Microsoft.ActiveDirectory.Management.ADUser
"SamAccountName","GivenName","Surname","Memberof"
"test","Mari","Hopkins","Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"
You already have this information primed for a CSV. Why not just use Export-CSV and the opposite Import-CSV
$test2 | Export-CSV -Path c:\temp\backup.csv -Append
Append will add the item to the file and not overwrite the current contents. Then, if you need to, you can import it back with Import-CSV. Likely with multiple objects
$deprecatedAccounts = Import-CSV -Path c:\temp\backup.csv
To create the output you could collect the users with an array.
$users = #()
$users += $test2
$users | Export-CSV -Path c:\temp\backup.csv -Append
Edit from comments
Sorry, I didnt understand the issue at first. What you need to do is expand MemberOf from an array to a string.
Get-ADUser test -Properties SamAccountName,GivenName,Surname,Memberof |
Select-Object SamAccountName,GivenName,Surname,#{Label="MemberOf";Expression = {$_.Memberof -join ";"}} |
Export-Csv -Path c:\temp\backup.csv -Append -NoTypeInformation
Create a calculated property in the select-object that expands the memberof into a semicolon delimeted string. -NoTypeInformation removes the #TYPE Selected.Microsoft.ActiveDirectory.Management.ADUser line if you do not like that.
If you ever needed to process this back into an array you could do so with a simple split
Import-CSV c:\temp\backup.csv | ForEach-Object{$_.MemberOf -split ";"}
Depends on what you mean by easy to read, but how about using Export-Clixml to store the object and Import-Clixml to import it?