1

I have a dynamic list of server names coming from a report on an internal website. I'm looking to have PowerShell get this list from URL, then use it as a variable that I can cycle through.

Currently, this is what I have.

$servers = Invoke-WebRequest -URI http://myserver/hostgroup.php?hostgroup=test | Select -expand Content

This returns a simple list, such as "SERVER1","SERVER2","SERVER3",. I want to loop through this list to run reports on. Here's a simple foreach as a starting point (which doesn't work).

foreach ($s in $servers) {
    if(Test-Connection -Quiet $s -Count 1) { 
        Write-Host "Online"

    } else {
        # connection test failed 
        Write-Host "`a`n" $s "is unreachable" -ForegroundColor Red 
    }
}

The output I receive looks like it's using the whole string as the server name, and it's not breaking it down.

Here's the output.

 "SERVER1","SERVER2","SERVER3", is unreachable

2 Answers 2

5

In addition to splitting up the single string into an array of strings, you will need to trim off the double-quotes e.g.:

$result = ($servers = Invoke-WebRequest -URI http://myserver/hostgroup.php?hostgroup=test).Content
$servers = $result -split ',' -replace '"','' | Where {$_ -notmatch '^\s*$'}
Sign up to request clarification or add additional context in comments.

3 Comments

This worked. Splitting the commas only didn't make it. Trimming the quotes did. It seems to be cycling through the foreach now. Thanks! Can you explain the regex you have at the end?
@Pat Keith is filtering out entries that are just whitespace(\s) only from start to finish.
Yup. The sample text looked like it had a trailing comma - "SERVER3", and the split operation would have created an empty entry because of it.
2

If $servers contains a single string, just split it:

$servers = $servers -split ','

This will return an array, which can be used with your Foreach statement.

1 Comment

That helps! It breaks it up, but not quite out of the woods yet. I'm still getting the "Unreachable" portion of the foreach. If I manually type in a variable with the server names, it works. If I fetch from a URL, it's still not working.

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.