Home > Software engineering >  Looping in Powershell I
Looping in Powershell I

Time:11-26

I would like to run a powershell script where I can loop a command until it comes back false.

tnc -ComputerName [Address] -port [port]
Start-Sleep -s 5 

The script is run every 5 seconds

ComputerName     : [Address]
RemoteAddress    : IP
RemotePort       : Port
InterfaceAlias   : WiFi
SourceAddress    : [Address]
TcpTestSucceeded : True

I need this to run every 5 seconds but only show on false then extract to a doc and continue running.

I don't know if this is possible, but any help

CodePudding user response:

The logic would look like this, note that, there are many variations for this. It's up to you.

  • DateTime.ToString('u') will have the following format for TimeStamp:
//    u Format Specifier      de-DE Culture                     2008-10-31 17:04:32Z
//    u Format Specifier      en-US Culture                     2008-10-31 17:04:32Z
//    u Format Specifier      es-ES Culture                     2008-10-31 17:04:32Z
//    u Format Specifier      fr-FR Culture                     2008-10-31 17:04:32Z

Source: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-6.0

$log = do # Do this
{
    # Store the result of TNC in this variable to be tested until(...) is False
    $tnc = Test-NetConnection -ComputerName [Address] -Port [port] |
    Select-Object @{
        Name = 'TimeStamp'
        Expression = { [datetime]::Now.ToString('u') }
    }, RemoteAddress, RemotePort, TcpTestSuceeded

    # Return this variable so it's captured in $log Variable to export the log later
    $tnc 
    Start-Sleep -Seconds 5
}
until ($tnc.TcpTestSuceeded) # Until this property is $False

$log | Export-Csv path/to/logfile.csv -NoTypeInformation

CodePudding user response:

Something like this. But the timeout of a down connection is ridiculously long at about 30 seconds.

while ( -not (tnc yahoo.com -port 81) ) { sleep 5 }

WARNING: TCP connect to (2001:4998:24:120d::1:1 : 81) failed
WARNING: TCP connect to (2001:4998:124:1507::f001 : 81) failed
  • Related