Ron
Ron

Reputation: 365

Using Powershell to enter results in a specific cell of a CSV

I have a CSV file and the last column (Column J) has usernames in it. I have a script that will run down column J and display the State by pulling the info from active directory. I want it to add the information to column K beside the current username. Below is the script. It works fine to get the information I just can’t get it to add it to column K. I placed a count function (the line that says $add1 = $add1 +1) with the hope I could find a solution that would let me pipe the results to my CSV file in Column K row $add1. I assume there is a way to do it but cant figure it out. Thanks

enter code here



Import-Module ActiveDirectory
$add1 = 1
Import-csv C:\Temp\newfile.csv | Select -expand MUID | ForEach {          
$add1 = $add1 +1   
Get-ADUser -Identity $_ -Properties st | select -ExpandProperty st

}

Upvotes: 2

Views: 2971

Answers (2)

Shay Levy
Shay Levy

Reputation: 126902

You can Select-Object to add the column with a calculated property:

Import-Module ActiveDirectory

Import-csv C:\Temp\newfile.csv | `
Select-Object *,@{n='k';e={ (Get-ADUser -Identity $_.MUID -Properties st).st }} | `
Export-Csv .\users.csv -NoTypeInformation

Upvotes: 0

manojlds
manojlds

Reputation: 301457

You can do something like this:

import-csv C:\Temp\newfile.csv | %{

    $k = Get-ADUser -Identity $_.MUID -Properties st | select -ExpandProperty st
    $_ | add-member -MemberType noteproperty -Name k -Value $k
    $_
}  | export-csv -NoTypeInformation C:\Temp\newfile2.csv

If the csv already had column k, you just have to assign the result you want to $_.k

Upvotes: 2

Related Questions