John
John

Reputation: 99

Powershell foreach loop with out-file issue

I'm trying to use powershell to test network connectivity to a list of servers, then dump to a text file ONLY if it returns true. What happens with my code is it includes servers that did not ping. Here's what I have:

$servers = Get-Content c:\script\servers.txt
foreach($server in $servers)
{
Test-Connection $server -count 1 -quiet
    if ($True){out-file -InputObject $server, $True -Encoding ASCII -Width 50 -Append c:\scriptoutput.txt}
    else { write-host "server $server could not be contacted"}
}

Now what I see in the output file is

server1
True
server2
True
server3
True

But what I see on the console is this:

PS C:\> C:\test.ps1
True
True
False

Server 3, which doesn't exist and therefore can't be pinged, still shows up as True in the output file, but reads False in the console. What gives?

Upvotes: 1

Views: 7807

Answers (1)

Keith Hill
Keith Hill

Reputation: 201662

Not only is the else statement never reached, but you're always outputting true to the file. Try this instead:

$servers = Get-Content c:\script\servers.txt
foreach ($server in $servers)
{
    $connected = Test-Connection $server -count 1 -quiet
    if ($connected) {
        $server,$connected | Out-File -Enc ASCII -Width 50 -Append c:\scriptoutput.txt
    }
    else { 
        write-host "server $server could not be contacted"
    }
}

Upvotes: 4

Related Questions