Populate Data into a Specific column in CSV Powershell - 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"
}

Related

CSV var as expression is empty, shown as {}

I got a small issue. I have a CSV with some names. I needed to get the email addresses of those users, so I created a small script that will find users with that firstname and lastname in AD.
After that, I wanted to export it to a new CSV file, but keep the phone-numbers from the first CSV file so its also available in the new CSV export.
That last part don't seem to work. In the output that expression is shown as {}.
Can someone help me?
$csv = import-csv -path C:\users\da6\desktop\UsersZonderEmail.csv
$output = #()
foreach ($i in $csv) {
$givenname = $i.Voornaam
$lastname = $i.Achternaam
$number = $i.IpPhone
$output += try {Get-ADUser -Filter {givenname -eq $givenname -and surname -eq $lastname} | select Name, UserPrincipalName, #{ name="ipphone"; expression=$number}} catch {}
}
Basically what is wrong with your code is that you forgot the opening bracket { in the expression oart of the calculated property.
Also note that -Filter should be a string, not a scriptblock.
Lastly, adding to an array with += is a bad habit, as the entire array needs to be rebuilt in memory on every addition.
Better let PowerShell collect the values from the loop:
$csv = Import-Csv -Path 'C:\users\da6\desktop\UsersZonderEmail.csv'
$output = foreach ($item in $csv) {
Get-ADUser -Filter "GivenName -eq '$($item.Voornaam)' -and Surname -eq '$($item.Achternaam)'" -Properties EmailAddress |
Select-Object Name, UserPrincipalName, #{ Name="ipphone"; Expression = {$item.IpPhone}}, EmailAddress
}
# output to new CSV file
$output | Export-Csv -Path 'C:\users\da6\desktop\UsersMetEmail.csv' -NoTypeInformation

Foreach in Get-ADUser

I've tried lots of different combinations at this point and I'm coming up dry. I have a CSV file that contains usernames (Users) of people in the format of 117321, which refers to their login name. I'm trying to get the homedirectory path of all these users and export them to a CSV. Here's what I have so far, but it doesn't seem to work. I've even tried filter.
$InputFile = 'C:\Users.csv'
$Users = Import-CSV $InputFile
$OutputFile = 'C:\Directory Results.csv'
$HomeDirOutput = ForEach ($User in $Users) {
Get-ADUser -LDAPFilter "(sAMAccountName=$user)" -Properties homedirectory
}
$HomeDirOutput | Export-Csv $OutputFile -NoTypeInformation
All I'm getting is a blank spreadsheet.
sAMAccountName is a valid value to pass to the -Identity parameter of Get-ADUser. Assuming that the CSV contains a column "AccountName", you should be able to do
Import-CSV -Path $InputFile | ForEach-Object { Get-ADUser -Identity $_.AccountName -Property sAMAccountName,HomeDirectory } | SelectObject -Property sAMAccountName,HomeDirectory | Export-CSV -NoTypeInformation -Path $OutputFile -Append
(after making sure that the output file doesn't already exist).

Powershell, CSV-import

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

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

Writing an array to a specific csv column with powershell

I have a csv file that has a lot of data in it, with one column being a "Username" column. I created a loop to query AD and get each username and now I need to export each of those names to the specific column in the csv. After importing the csv with:
$data = Import-CSV .\data.csv
And using the loop:
foreach($user in $data)
And I use get-aduser $user -server $server and if($? -eq $true){ $user = $user + "01" }
I tried using
$data.Username | Export-CSV .\data.csv and $data.Username | out-file .\data.csv
but so far neither have worked.
You need to keep all the information in the pipeline so you can re-export the whole thing.
Try something like this:
$data | Foreach {
get-aduser $_.Username -server $server
if($? -eq $true){ $_.Username = $_.Username + "01" }
} | export-csv .\data.csv