How to use a PowerShell script/code against a list of servers from a text file

Hi Respected Members,

Can anyone help me with this code to adapt it to run against a list of server from a text file .

Task - I am trying to find RDP port connectivity against a list of servers . 

- The code is running fine if a give the server name in the code but when i am trying to run it against a set of servers form a text file the code is not giving me any results as expected .

My ? - I want to run the below code against a list of servers from a text file but i am failing to get the expected results 


$Computername = 'xx'
  [int[]]$Port  = 3389
  #Timeout in milliseconds
$TCPTimeout = 100
ForEach ($Item  in $Port)  {
  $TCPClient  = New-Object  -TypeName   System.Net.Sockets.TCPClient
  $AsyncResult  = $TCPClient.BeginConnect($Computername,$Item,$null,$null)
  $Wait = $AsyncResult.AsyncWaitHandle.WaitOne($TCPtimeout)
  If ($Wait) {
  Try  {
  $Null  = $TCPClient.EndConnect($AsyncResult)
  } Catch  {
  Write-Warning  $_
  $Issue  = $_.ToString()
  } Finally  {
  Computername = $Computername
  Port =  $Item
  IsOpen =  $TCPClient.Connected
  Notes =  $Issue
  } Else  {
  Computername = $Computername
  Port =  $Item
  IsOpen =  $TCPClient.Connected
  Notes =  'Timeout occurred connecting to port'
  $Issue  = $Null

PS C:\Users\anand\Desktop> .\3389.ps1
Computername                                                                     Port                                    IsOpen Notes
------------                                                                     ----                                    ------ -----
xx                                                                      3389                                     False Timeout occurred connecting to port
No Data
  • Create a list of servers in a file, or a variable and pass that via a pipeline in a ForLoop. 

    This is basic PowerShell looping use case, regardless of what you are targeting. 

    See Youtube videos on PowerShell loops or the PowerShell docs on Loops. 

No Data