user1158745
user1158745

Reputation: 2490

Powershell getting values from CSV file

I have a CSV file which looks like this:

  OldEmailAddress,NewEmailAddress
  [email protected],[email protected]

Power shell code to import the file:

 $UserInput = Import-csv "C:\Powershell\UserList.txt" -Delimiter ",";

I am going though a foreach loop and trying to write the values but it's print it out as an array in the powershell Window.

    foreach ($User in $UserInput) 
    {
     Write-Host $User.OldEmailAddress;
    }

The console doesn't display just that filed but the full array.

   @{[email protected]; [email protected]}

Why is this occurring?

Upvotes: 0

Views: 992

Answers (1)

postanote
postanote

Reputation: 16116

As for this...

"Testing $User.OldEmailAddress

...to make it work, do it this way...

 $UserInput = Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ','

 ForEach($User in $UserInput)
{$User.OldEmailAddress}
<#
# Results

[email protected]
#>

ForEach($User in $UserInput)
{$User.NewEmailAddress}
<#
# Results

[email protected]
#>

ForEach($User in $UserInput)
{"$User.OldEmailAddress"}
<#
# Results

@{[email protected]; [email protected]}.OldEmailAddress
#>

ForEach($User in $UserInput){"$($User.OldEmailAddress)"}
<#
# Results

[email protected]
#>

ForEach($User in $UserInput){"$($User.NewEmailAddress)"}
<#
# Results

[email protected]
#>

... no Write-Host needed since output to the screen is the PowerShell default unless you tell it otherwise. ;-}

Yet, why use that extra loop at all, for example:

Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ','
<#
# Results

OldEmailAddress NewEmailAddress
--------------- ---------------
[email protected]   [email protected]
#>

Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' | 
ForEach{$PSItem}

OldEmailAddress NewEmailAddress
--------------- ---------------
[email protected]   [email protected]


 Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' | 
ForEach{$PSItem.OldEmailAddress}
<#
# Results

[email protected]
#>

 Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' | 
ForEach{$PSItem.NewEmailAddress}

<#
# Results

[email protected]
#>

Upvotes: 1

Related Questions