【问题标题】:Looping in Powershell I在 Powershell I 中循环
【发布时间】:2022-01-03 19:45:01
【问题描述】:

我想运行一个 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,然后提取到文档并继续运行。

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

【问题讨论】:

  • 您已经具备执行Test-NetConnection 的逻辑,只需对其应用whiledo 循环即可。见docs.microsoft.com/en-us/powershell/module/…docs.microsoft.com/en-us/powershell/module/…
  • 嗨,圣地亚哥,非常抱歉。我(还)不太擅长这个。我已尝试完成已显示的内容,但我遗漏了什么?执行 {tnc address-port port -InformationLevel Quiet} 直到 ()
  • 还有时间标记结果吗?
  • 如果您对日期格式不挑剔,可以使用Get-Date。否则你可以使用Get-Date -Format。您可以查找 Get-Date 以查看格式样式
  • 得到日期/时间,谢谢 :) 只是现在无法解决错误

标签: powershell powershell-2.0


【解决方案1】:

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

  • 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

【讨论】:

  • 我会好好庆祝一下,谢谢
  • @Gary 没问题,如果答案有帮助请考虑accepting
  • 谢谢你,按我的需要工作
【解决方案2】:

类似的东西。但是断开连接的超时时间非常长,大约 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

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多