【问题标题】:Adding an if statement to change text output添加 if 语句以更改文本输出
【发布时间】:2015-04-23 23:05:14
【问题描述】:

我有一些 PowerShell 代码可以获取服务器列表的正常运行时间,并输出服务器正常运行的天数、小时数和分钟数。

我正在尝试添加一条运行时间少于 10 小时并输出到文本文件的语句 - 已重新启动

如果服务器运行 30 天或更长时间,则输出到文本将是 - Reboot Needed

我只是不确定如何做到这一点。这是我的正常运行时间......

    $names = Get-Content "C:\Users\david.sechler\Documents\PowerShell\Get Uptime\servers.txt"
    @(
       foreach ($name in $names)
      {
        if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) 
      {
        $wmi = gwmi -class Win32_OperatingSystem -computer $name
        $LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
        [TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
        Write-output "$name Uptime is  $($uptime.days) Days $($uptime.hours) Hours $($uptime.minutes) Minutes $($uptime.seconds) Seconds"

      }
         else {
            Write-output "$name is not pinging"
              }
        }
     ) | Out-file -FilePath "C:\Users\david.sechler\Documents\PowerShell\Get Uptime\results.txt"

【问题讨论】:

  • 这是什么语言? batch-file?
  • 对不起,丹,好问题!这是 powershell。

标签: if-statement powershell-2.0 uptime


【解决方案1】:

试试这个

$toreboot = @()
$rebooted = @()
[timespan]$recentboot = new-timespan $(get-date).AddHours(-10) $(get-date)
[timespan]$needboot = new-timespan $(get-date) $(get-date).Adddays(30) 

$recentboot
$needboot

$names = Get-Content "d:\scrap\servers.txt"
foreach ($name in $names)
  {
    if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction     SilentlyContinue ) 
              {
                $wmi = gwmi -class Win32_OperatingSystem -computer $name
                $LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
                [TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
                Write-output "$name Uptime is  $($uptime.days) Days $($uptime.hours) Hours $($uptime.minutes) Minutes $($uptime.seconds) Seconds"
                if ($uptime -lt $recentboot)
                    {$rebooted += $names}
                if($uptime -gt $needboot)
                    {$toreboot += $name}

               }
     else {
        Write-output "$name is not pinging"
          }

          if ($toreboot -ne $null)
            {set-content -Path "d:\scrap\serverstoboot.txt" -Value $toreboot}
          if ($rebooted -ne $null)
            {set-content -Path "d:\scrap\recentlybooted.txt" -value $rebooted}
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多