2015-12-03 144 views
1

CSV格式如下:輸出與CSV和PowerShell格式化

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格式進行參考。我已閱讀的文章顯示這應該工作,但我顯然錯過了與格式化愚蠢的東西。我究竟做錯了什麼?

回答

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 
} 
+0

或者乾脆'寫主機「用戶名:」 $ user.Username'和'寫主機「密碼:「$ user.Password」,因爲'write-host'嘗試將所有內容都轉換爲字符串,然後只加入所有字符串。 – TheMadTechnician