我正在运行用作管理服务器的Windows Server 2012。在这里,我设置了将PowerShell scrips作为计划任务运行,以使用Windows远程管理 aka 远程PowerShell在远程服务器上执行各种任务。
以下脚本是4个脚本之一,其中#############下的所有内容都保持完全相同。上面#############是我设置不同变量以针对不同服务器运行的地方。
我遇到一个问题,如果我将4个脚本中的一个作为计划任务运行,它会坚持告诉我结果应该是相反的结果。所有其他计划任务脚本运行完美,给出预期结果。如果我从PowerShell ISE 发送电子邮件说明 adfssrv 服务正在运行,则此脚本可以完美地运行预期结果。但是,如果使用计划任务运行此确切脚本,我会收到一封电子邮件,说明 adfssrv 服务未运行,等待15分钟,然后再通过电子邮件告诉我< strong> adfssrv 服务未运行。
计划任务的设置与其他任务完全相同, powershell.exe - 命令c:\ Scripts \ XA-US-FS-02_adfssrv.ps1 ,所有脚本都位于完全相同的本地目录 c:\ Scripts
$FirstCheck = @()
$arrService = @()
$computername = @()
$MyHost = @()
$cred = @()
$password = @()
$cmdAutoAdmin = @()
$WinRMPort = @()
$password = ConvertTo-SecureString "some_password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("xa-us-fs-02\svc.tasks", $password )
$computername = "xa-us-fs-02.cloudapp.net"
$cmdAutoAdmin = {Get-Service -Name adfssrv}
$WinRMPort = 61573
$MyHost = "XA-US-FS-02"
$mytime = Get-Date -displayhint time
$SMTPServer = "smtp.sendgrid.net"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("User", "SendGridPassword");
$EmailFrom = "Email_Alerts@xyz.com"
$EmailTo = "receiver@xyz.com"
#########################################
$arrService = Invoke-Command -ComputerName $computername -Port $WinRMPort -Credential $cred -UseSSL -ScriptBlock $cmdAutoAdmin
if ($arrService.Status -eq "Running"){
$Subject = "$MyHost - ADFS service"
$Body = "Hi, I just checked the ADFS service (adfssrv) on $MyHost at $mytime and it is running :)"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
$FirstCheck = "Success"
}
elseif ($arrService.Status -ne "Running"){
Invoke-Command -ComputerName $computername -Port $WinRMPort -Credential $cred -UseSSL -ScriptBlock {Start-Service -Name adfssrv}
$Subject = "$MyHost - ADFS NOT RUNNING"
$Body = "This is an email to say that the ADFS service on $MyHost was checked at $mytime and it was not started. `
I have attempted to start the ADFS service just now. `
I will check again in 15 minutes"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Start-Sleep -Seconds 900
}
if ($arrService.Status -ne "Running" -and $FirstCheck -ne "Success"){
$Subject = "$MyHost - ADFS NOT RUNNING AGAIN!"
$Body = "This is the SECOND email to say that the ADFS service on $MyHost was checked at $mytime and it was not started. `
Manual human intervention required"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
elseif ($arrService.Status -eq "Running" -and $FirstCheck -ne "Success"){
$Subject = "$MyHost - ADFS service"
$Body = "Hi, I just checked the ADFS service (adfssrv) for a SECOND time on $MyHost at $mytime and it is now running :)"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}