2013-10-17 55 views
1

輸入文件:地址變量使用PowerShell和Import-CSV的foreach循環

"Server1","lanmanserver" 
"Server2","lanmanserverTest" 

計劃

$csvFilename = "D:\Scripts\ServerMonitorConfig.csv" 
$csv = Import-Csv $csvFilename -Header @("ServerName","ServiceName") 

foreach ($line in $csv) { 
    Write-Host "ServerName=$line.ServerName ServiceName=$line.ServiceName" 
    } 

我想要什麼:

服務器名稱= Server1的服務名稱= lanmanserver
Server-Name = Server2 ServiceName = lanmanserverT

什麼我越來越:

服務器名稱= @ {服務器名稱= Server1的; ServiceName = lanmanserver} .ServerName ServiceName = @ {ServerName = Server1; ServiceName = lanmanserver} .ServiceN ame ServerName = @ {ServerName = Server2; ServiceName = lanmanserverTest} .ServerName ServiceName = @ {ServerName = Server2;的ServiceName = lanmanserverTest}。 服務名稱

我真的不在乎頭部是否來自CSV的第一行或者不是,我在那裏很靈活。

回答

2

大家平時看到的用來解決子表達式或格式字符串:

子表達式:

Write-Host "ServerName=$($line.ServerName) ServiceName=$($line.ServiceName)" 

格式字符串:

Write-Host ('ServerName={0} ServiceName={1}' -f $line.ServerName,$line.ServiceName) 
+0

我知道它是簡單的。那麼$ line.ServerName是什麼,爲什麼它需要額外的$()呢? – NealWalters

+0

這是我真正想要的:Write-Host「ServerName = $($ line.ServerName)ServiceName = $($ line.ServiceName)」 $ status =(get-service -Name $ line.ServiceName - ComputerName $ line.ServerName).Status因此,它看起來像我只有$()引號內。 – NealWalters

+0

這只是解析器在雙引號字符串上的工作方式。要在可擴展字符串中使用對象的屬性,$ object.property必須包裝在$()中,使其成爲子表達式。 – mjolinor