简体   繁体   English

使用CSV和PowerSHell进行输出格式化

[英]Output formatting with CSV and PowerSHell

CSV formatted like this: CSV格式如下:

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

PowerShell Script: PowerShell脚本:

$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. 这是较大脚本的一部分,我需要能够使用$user.XXXX格式进行引用。 Articles I've read show this should work but I'm clearly missing something silly with the formatting. 我读过的文章显示这应该可行,但是我显然在格式上缺少一些愚蠢的东西。 What am I doing wrong? 我究竟做错了什么?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM