Reputation: 13
What I am trying to do is I import data from a csv file which has UserPrincipalnames and I am taking the names before the @ symbol and then I want to export that data to a specific column in the same CSV file which in this case is o365Users.csv. I am able to write it out to a text file but I need to know how to export it out to Column G with the header name as SAM
This is my code:
$Addys = Import-Csv "C:\scripts\o365Users.csv"
$UPNs = $Addys.UserPrincipalName
foreach ($UPN in $UPNs) {
$Name = $UPN.Split("@")[0]
Write-Output $Name >> c:\scripts\o365Names.txt
}
Upvotes: 0
Views: 8306
Reputation:
To append a new column with the header SAM
use Select-Object
with a calculated property:
(Import-Csv 'C:\scripts\o365Users.csv') |
Select-Object -Property *,@{n='SAM';e={$_.UserPrincipalName.Split('@')[0]}}
If the new property has to be in a specific position you can't use the wildcard *
but will have to enumerate all headers/columns/properties in the desired order, i.e.
(Import-Csv 'C:\scripts\o365Users.csv') |
Select-Object -Property ColA,ColB,ColC,ColD,ColE,ColF,@{n='SAM';e={$_.UserPrincipalName.Split('@')[0]}},ColH
replace Col_
with your real headers.
Due to enclosing the (Import-Csv)
in parentheses you can export to the same file name (not recommended while still testing) - simply append
| Export-Csv 'C:\scripts\o365Users.csv' -NoTypeInformation
Upvotes: 1
Reputation: 394
Here is a quick way to get just the output you are looking for. You would import the current CSV. Create an blank output array and in your loop add each name. Then export the CSV
$Addys = Import-Csv "C:\scripts\o365Users.csv"
$UPNs = $Addys.UserPrincipalName
[System.Collections.ArrayList]$Output = @()
foreach ($UPN in $UPNs) {
$Name = $UPN.Split("@")[0]
$Output.Add($Name) | Out-Null
}
$Output | Export-Csv -Path "C:\scripts\o365Users.csv" -NoTypeInformation
Upvotes: 0