使用CSV和PowerSHell输出格式

时间:2015-12-03 15:46:36

标签: csv powershell

CSV格式如下:

Username,Password
jsmith,Password!
jdoe,Password!
bob,Password!

PowerShell脚本:

$users = Import-CSV -Path "C:\path\users.csv"

foreach ($user in $users) {
     Write-Host "Username: $user.Username"
     Write-Host "Password: $user.Password"
}

输出:

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

这是较大脚本的一部分,我需要能够使用$user.XXXX格式进行引用。我读过的文章表明这​​应该有效,但我显然遗漏了格式化的愚蠢内容。我做错了什么?

1 个答案:

答案 0 :(得分:6)

你需要"逃避"尝试插入时将对象属性转换为变量。以下将改为:

foreach ($user in $users) {
     Write-Host "Username: $($user.Username)"
     Write-Host "Password: $($user.Password)"
}

或者,您可以使用格式字符串运算符:

foreach ($user in $users) {
     "Username: {0}" -f $user.Username
     "Password: {0}" -f $user.Password
}