在 Powershell 中循环 I

Looping in Powershell I

我想要 运行 一个 powershell 脚本,我可以在其中循环命令直到它返回 false。

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

脚本每 5 秒 运行

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

我需要每 5 秒 运行 一次,但只在 false 时显示,然后提取到文档并继续 运行ning。

我不知道这是否可行,但有任何帮助

逻辑看起来像这样,请注意,这有很多变体。由你决定。

  • DateTime.ToString('u') 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

来源: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

像这样。但是断开连接的超时时间长得离谱,大约 30 秒。

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