PowerShell运行计划任务

时间:2017-12-01 21:14:35

标签: powershell

我创建了一个power-shell脚本,它将执行以下操作:1。停止Windows服务,等待60秒,检查服务是否仍在运行,是否发送电子邮件,然后重新启动服务器,如果它不运行只是重启。以管理员身份运行时,脚本运行正常,但在使用计划任务进行设置时,脚本将执行除引导设备之外的所有操作。我已将计划任务配置为对参数使用-executionpolicy bypass。

    $ServiceName = 'Print Spooler'
    Stop-Service -Name $ServiceName
    sleep -Seconds 60
    function FuncCheckService{
    param($ServiceName)
    $arrService = Get-Service -Name $ServiceName
    if ($arrService.Status -eq "Running"){
      FuncMail -To "to-email" -From "from-email"  -Subject "Servername : 
    ($ServiceName) Failed." -Body "Service $ServiceName Failed to Stop" -
    smtpServer "email-smtp.us-east-1.amazonaws.com"
        Restart-Computer
    }
    else {
    Restart-Computer
    }
    } 
   function FuncMail {
   #param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
   param($To, $From, $Subject, $Body, $smtpServer)
   $msg = new-object Net.Mail.MailMessage
   $smtp = new-object Net.Mail.SmtpClient($smtpServer, 587)
   $smtp.Credentials = New-Object System.Net.NetworkCredential(“Username”, 
   “Password”);
   $smtp.EnableSsl = $true
   $msg.From = $From
   $msg.To.Add($To)
   $msg.Subject = $Subject
   $msg.IsBodyHtml = 1
   $msg.Body = $Body
   $smtp.Send($msg)
   } 
   FuncCheckService -ServiceName "Print Spooler"

计划任务运行脚本并重新启动

计划任务只会停止Windows任务并在60秒后仍然运行时发送电子邮件。

0 个答案:

没有答案