NealWalters
NealWalters

Reputation: 18227

Address Variables with PowerShell and Import-CSV foreach-loop

Input file:

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

Program

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

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

What I want:

Server-Name=Server1 ServiceName=lanmanserver
Server-Name=Server2 ServiceName=lanmanserverT

What I'm getting:

ServerName=@{ServerName=Server1; ServiceName=lanmanserver}.ServerName ServiceName=@{ServerName=Server1; ServiceName=lanmanserver}.ServiceN ame ServerName=@{ServerName=Server2; ServiceName=lanmanserverTest}.ServerName ServiceName=@{ServerName=Server2; ServiceName=lanmanserverTest}. ServiceName

I really don't care if the Headers come from the first row of the CSV or not, I'm flexible there.

Upvotes: 1

Views: 12105

Answers (1)

mjolinor
mjolinor

Reputation: 68331

You usually see subexpressions or format strings used to solve that:

Subexpression:

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

Format string:

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

Upvotes: 2

Related Questions