Powershell, CSV-import - powershell

I'm not very experienced working with CSV files, and now I'm kinda stuck getting this small private project to work properly.
I've made a script that checks which user who is running the script, then gets the department number the user belongs to, from AD. Then I want to test that department number against a CSV file to get the correct Department name.
The CSV file look like this:
111;DepartmentBlue
222;DepartmentRed
333;DepartmentGreen
How can I make my script check if the Departmentnumber I got from AD, exists in this CSV file in column 1, and then return the Department Name (column 2)?
This is what I got:
Function outputData {
$outputUser.Text = ((Get-ADUser -Identity $env:username -Properties SamAccountName).SamAccountName)
$outputDep.Text = ((Get-ADUser -Identity $env:username -Properties Department).Department)
$dep = $outputDep.Text
$source = Import-Csv -Path "C:\temp\Script\departments.csv"
foreach($i in $source){
if($dep -eq $i){
#give me the department name
}
}
}

Modifying your current code, you could try the following:
Function outputData {
$ADUser = Get-ADUser -Identity $env:username -Properties Department
$dep = $ADUser.Department
$username = $ADUser.SamAccountName # Doesn't seem to be needed
$source = Import-Csv -Path "C:\temp\Script\departments.csv" -Delimiter ';'
foreach($i in $source){
if($dep -eq $i.departmentNumber){
$i.departmentName
}
}
}
outputData
All of this assumes that the first line of your CSV file is DepartmentNumber;DepartmentName. Alternatively, you could leave the CSV file without the headers and add the -Header parameter to your Import-Csv command like so:
Function outputData {
$ADUser = Get-ADUser -Identity $env:username -Properties Department
$dep = $ADUser.Department
$source = Import-Csv -Path "C:\temp\Script\departments.csv" -Delimiter ';' -Header "DepartmentNumber","DepartmentName"
foreach($i in $source){
if($dep -eq $i.departmentNumber){
$i.departmentName
}
}
}
outputData
This is all assuming the Department attribute in AD contains the department number value with the goal being looking up that same number in the CSV file and returning the corresponding department name on the same line. None of this code is efficient the way it is. We can accomplish this with less looping.
An alternative without looping and using the .where() function is the following:
Function outputData {
$ADUser = Get-ADUser -Identity $env:username -Properties Department
$dep = $ADUser.Department
$source = Import-Csv -Path "C:\temp\Script\departments.csv" -Delimiter ';' -Header "DepartmentNumber","DepartmentName"
$source.where({$_.departmentnumber -eq $dep},'First').departmentname
}
outputData
Another alternative is to use a string to hash table conversion like so:
Function outputData {
$ADUser = Get-ADUser -Identity $env:username -Properties Department
$dep = $ADUser.Department
$source = (gc c:\temp\test1\test2.csv -raw) -replace ';','=' | ConvertFrom-StringData
$source[$dep]
}
outputData

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

Populate Data into a Specific column in CSV Powershell

So I'm trying to add values to a CSV file. The code below works however it places the value in $department at the bottom of the file, but in the correct column. Does anyone have any advice on how I can get the value from $deparment to append to the top of the column in the CSV? My code is below:
$users = Import-Csv $file -Delimiter ","
$column_number = 6
foreach($user in $users){
$name = $user.Name
$department = Get-ADUser -Identity $name -Properties Department | Select-Object -ExpandProperty Department
Add-Content $file -Value "$(","*$column_number)$department"
}

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"
}

Exporting Membership groups for users from input file

I have this script that reads samaccountnames from a file and outputs the name of the user with its membership information. However, the output file only shows the last record. It seems that my code is overwriting the previous record. What am I missing? Thank you so much.
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name |
export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
}
Export-Csv has an -append parameter, so you could use that. ie it would append to the csv file with every iteration of the loop. You would need to make sure the file didn't exist before you start the loop or it would just get bigger and bigger each time you ran the code.
Another way it to add the items to an object and then export that at the end. ie $username += Get-ADUser......
You are reading a CSV file using Get-Content. This lets me think the file is simply a list of user SamAccountNames, each on a separate line. No headings.
Something like this perhaps:
jdoe
jsmith
If that is the case, read the input file like this:
$users = Get-Content -Path 'C:\MyScripts\UsersInput.csv'
To get an array of user SAMAccountnames.
If however it is a proper CSV file with headers, looking something like this:
"SamAccountName","Email","More","Stuff"
"jdoe","john.doe#yourdomain.com","blah","blah"
"jsmith","jane.smith#yourdomain.com","blah","blah"
Then you should use the Import-Csv cmdlet to get the entries as objects and obtain an array of SamAccountNames from that:
$users = Import-Csv -Path 'C:\MyScripts\UsersInput.csv' | Select-Object -ExpandProperty SamAccountName
Once you have that array, loop through it and get the group membership info for each user
Untested
$result = foreach ($accountName in $users) {
Get-ADUser –Identity $accountName -Properties DistinguishedName, DisplayName |
Select-Object #{Name = 'User'; Expression = {$_.DisplayName}},
#{Name = 'Groups'; Expression = { ( $_ | Get-ADPrincipalGroupMembership | Select-Object -ExpandProperty name) -join ', '}}
}
$result | Export-Csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
You are indeed overwriting the code ForEach user. You included Export-Csv in the ForEach. Instead export the whole array that ForEach creates:
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name
} | export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation

Finding users in AD

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
}