I have a script that runs through servers and prints out if they can connect to specific ports or not. The problem seems to be that it keeps on looping through existing servers its already done...hence I see multiple servers results and the CSV file keeps on getting re-written as each iteration restarts the cycle again to add on the next server.
Any ideas on ensuring it just cycles through one server at a time and not repeating the same server each time? The end CSV is fine as it contains the total servers but its taking ages to get there.
Output is below - you can see how it keeps on re-doing exisitng servers and just adding on one server more each time it runs:
Destination Port 3389 Port 445 Port 80
----------- --------- -------- -------
10.104.122.21 Failure Failure Failure
10.104.122.50 Failure Failure Failure
10.104.125.237 Failure Failure Failure
Destination Port 3389 Port 445 Port 80
----------- --------- -------- -------
10.104.122.21 Failure Failure Failure
10.104.122.50 Failure Failure Failure
10.104.125.237 Failure Failure Failure
10.104.125.66 Failure Failure Failure
Destination Port 3389 Port 445 Port 80
----------- --------- -------- -------
10.104.122.21 Failure Failure Failure
10.104.122.50 Failure Failure Failure
10.104.125.237 Failure Failure Failure
10.104.125.66 Failure Failure Failure
10.104.125.95 Failure Failure Failure
The code is below:
Function Test-PortConnections {
[CmdletBinding()]
# Parameters used in this function
Param
(
[Parameter(Position=0, Mandatory = $True, HelpMessage="Provide destination source", ValueFromPipeline = $true)]
$Destination,
[Parameter(Position=1, Mandatory = $False, HelpMessage="Provide port numbers", ValueFromPipeline = $true)]
$Ports = "80"
)
$ErrorActionPreference = "SilentlyContinue"
$Results = @()
ForEach($D in $Destination){
# Create a custom object
$Object = New-Object PSCustomObject
$Object | Add-Member -MemberType NoteProperty -Name "Destination" -Value $D
Write-Verbose "Checking $D"
ForEach ($P in $Ports){
#write-host "Port is $p"
$timeout=100
$requestCallback = $state = $null
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($d,$p,$requestCallback,$state)
Start-Sleep -milli $timeOut
if ($client.Connected -eq "True") { $Result = "True" } else { $Result = "False" }
$client.Close()
If($Result -eq "False"){ $status = "Failure" } else { $status = "Success" }
$Object | Add-Member Noteproperty "$("Port " + "$p")" -Value "$($status)"
}
$Results += $Object
If($Results){
$date = $(get-date -f yyyy-MM-dd)
$Results | Format-Table -AutoSize
$Results | Export-Csv -NoTypeInformation -Delimiter "," -Path H:\MyDocuments\Scripts\server_check_$($date).csv
}
}
}
Test-PortConnections -Destination (Get-Content -Path "H:\MyDocuments\Scripts\servers.txt") -Ports 3389,445,80
$Results | Format-Table -AutoSize