Reputation: 11
CSV formatted like this:
Username,Password
jsmith,Password!
jdoe,Password!
bob,Password!
PowerShell Script:
$users = Import-CSV -Path "C:\path\users.csv"
foreach ($user in $users) {
Write-Host "Username: $user.Username"
Write-Host "Password: $user.Password"
}
Output:
Username: @{Username=jsmith; Password=Password!}.Username
Password: @{Username=jsmith; Password=Password!}.Password
Username: @{Username=jdoe; Password=Password!}.Username
Password: @{Username=jdoe; Password=Password!}.Password
Username: @{Username=bob; Password=Password!}.Username
Password: @{Username=jsmith; Password=Password!}.Password
This is part of a larger script and I need to be able to reference using $user.XXXX
format. Articles I've read show this should work but I'm clearly missing something silly with the formatting. What am I doing wrong?
Upvotes: 1
Views: 246
Reputation: 22831
You need to "escape" the object property into a variable when trying to interpolate it. The below would work instead:
foreach ($user in $users) {
Write-Host "Username: $($user.Username)"
Write-Host "Password: $($user.Password)"
}
Alternatively, you could use the format string operator:
foreach ($user in $users) {
"Username: {0}" -f $user.Username
"Password: {0}" -f $user.Password
}
Upvotes: 6