简体   繁体   中英

Run Powershell Script on Boot without being logged in

have searched around but cant get this to work. I have as PS script that sends email on server boot. It works when I run it through a cmd file. I have setup a Task under Task Scheduler to run that cmd file and selected 'Run whether user is logged in or not' and also 'Run wit highest privileges'

When I restart the PC it doesnt run the script.

The script only gets run when I log in.

Any ideas please?


When computer starts. Sent output to log as suggested get this:


Exception calling "Send" with "4" argument(s): "Failure sending mail." At C:\\Users\\ravlo\\sendEmail.ps1:9 char:1 + $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SmtpException


Full Script is this:


$EmailFrom = "x"
$EmailTo = "y"
$Subject = "SERVER JUST REBOOTED"
$Body = "z"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("emaillogin", "emailpwd");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Runs OK when I actually log in.

Can you test your mail server accessibility before you execute Send() ? You can add

if ((Test-NetConnection -ComputerName $SMTPServer -Port 25).TcpTestSucceeded) {
    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
} else {
    Write-Output "SMTP Server not accessible"
}

If you have Windows Pro and higher, you can use Group Policy startup scripts in Computer configuration scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM