1

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I knew it had to be simple. So what is $line.ServerName, and why does it need the extra $() around it?
This is where I'm really going with this: Write-Host "ServerName=$($line.ServerName) ServiceName=$($line.ServiceName)" $status = (get-service -Name $line.ServiceName -ComputerName $line.ServerName).Status So it looks like I only $() inside the quotes.
It's just the way the parser works on double quoted strings. To use a property of an object in an expandable string, the $object.property must be wrapped in $(), making it a subexpression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.