1

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

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

$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') 

发送确认服务已成功重启

Start-Sleep -s 5 

Send-MailMessage -To $recipients -Subject $Subject -Body $body ((gsv Apache) | out-string) -From $from -SmtpServer $smtpServer -Attachments $attachment
4

1 回答 1

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-Sleepcmledt 调用输出被发送到管道 ( Start-sleep - s 5 |...)。我的猜测是它Start-sleep不会返回任何东西,所以没有任何东西发送到管道。基于此Write-Output不称为。

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

  $output = "D:\Testing\Restart.txt" 
于 2019-06-24T13:57:47.550 回答