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
格式引用.我读过的文章表明这应该有效,但我显然遗漏了格式化的愚蠢内容.我究竟做错了什么?
在尝试插值时,您需要将对象属性"转义"为变量.以下将改为:
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 }