将停止和启动服务的时间戳打印到.txt文件中

时间:2019-06-24 12:05:17

标签: powershell window-server

我想要停止/重新启动服务然后输出到文件时的时间戳。该文件将作为附件发送给支持人员。

我无法输出到文件,因为我的以下查询似乎出错。

=TEXT(SUMPRODUCT((B:B="x")*(A:A)), "[h]:mm:ss")

停止服务

$hostname = $env:computername
$smtpServer = 'smtpServer' 
$from = "from" 
$recipients = 'recipients'
$Subject = "Services Restarted Successfully on $hostname $ipv4" 
$body = "This mail confirms that the service on $hostname $ipv4 is now running." 
$ipv4 = (Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString
$natip = Invoke-WebRequest ifconfig.me
$timestamp = (Get-Date)
$output = D:\Testing\Restart.txt
$attachment = $output
$service = 'Apache' 

启动服务

Stop-Service -name $service -Verbose 

do { 
    Start-sleep -s 5 | Write-Output "$timestamp Services is stopped" | Out-file $output
    }  
        until ((get-service $service).Status -eq 'Stopped') 

发送确认服务已成功重启

    start-Service -name $service -Verbose 
do { 
    Start-sleep -s 5 | Write-Output "$timestamp Services is restarted" | Out-file $output
    }  
        until ((get-service $service).Status -eq 'Running') 

1 个答案:

答案 0 :(得分:1)

如以上注释所述,将代码更改为

Stop-Service -name $service -Verbose
do { 
      Start-sleep -s 5 
      Write-Output "$timestamp Services is stopped" | Out-file $output 
  } until ((get-service $service).Status -eq 'Stopped')

实际上,您的Start-Sleep cmledt呼叫输出已发送到管道(Start-sleep - s 5 |...)。我的猜测是Start-sleep不返回任何内容,因此没有任何内容发送到管道。基于此,Write-Output不被调用。

另一个猜测:由于您的路径不是字符串,因此分配给$output的操作失败,Powershell可能会在命令模式下解释该分配。更改为:

  $output = "D:\Testing\Restart.txt"