Hi,
I have put together two powershell scripts that will run in a scheduled task once a month. There is one script called start-patching. This script is triggered with a scheduled task, that runs like path\to\powershell.exe -command C:\script.ps1.
That first script will at its end, create a Register-ScheduledJob to run the second script at next boot. The first script runs fine, except that the line that does Register-ScheduledJob does not work. When i run the first script manually from powershell everything works.
First script:
# ------------------------------------- # Variables # ------------------------------------- $scriptName = "C:\Script\Patch\continue-patching.ps1" $trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30 function sendMail{ Write-Host "Sending Email" $nameofhost = hostname #SMTP server name $smtpServer = "smtp.domain.com" #Creating a Mail object $msg = new-object Net.Mail.MailMessage #Creating SMTP server object $smtp = new-object Net.Mail.SmtpClient($smtpServer) #Email structure $msg.From = "autopatch@domain.com" $msg.ReplyTo = "noreply@domain.com" $msg.To.Add("user@domain.com") $msg.subject = "Started patching $nameofhost" $msg.body = "$nameofhost" #Sending email $smtp.Send($msg) } #Script New-EventLog –LogName Application –Source “Patch script” -ErrorAction SilentlyContinue #write event log Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Running patch script start-patching” #Calling function sendMail #Import-Module Set-ExecutionPolicy Unrestricted ipmo PSWindowsUpdate #patch Get-WUInstall -AcceptAll #write event log Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Patching is complete. Computer will now reboot” #Create scheduled job at next startup Register-ScheduledJob -Trigger $trigger -FilePath $scriptName -Name Continue-Patching-Job #Reboot computer shutdown -r -t 0 exit
Second script:
function sendMailAfter{ Write-Host "Sending Email" #SMTP server name $smtpServer = "smtp.domain.com" #Creating a Mail object $msg = new-object Net.Mail.MailMessage #Creating SMTP server object $smtp = new-object Net.Mail.SmtpClient($smtpServer) #Email structure $msg.From = "autopatch@domain.com" $msg.ReplyTo = "noreply@domain.com" $msg.To.Add("user@domain.com") $msg.subject = "Finished patching $nameofhost" $msg.body = "$message" #Sending email $smtp.Send($msg) } #Script #Remove scheduled job Unregister-ScheduledJob -Name Continue-Patching-Job #write event log Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Computer has rebooted. Running script continue-patching” sendMailAfter #write event log Write-EventLog –LogName Application –Source “Patch script” –EntryType Information –EventID 1 –Message “Finished patching. Sending status email”
Server is 2008 R2 with WMF4.0
This posting is provided "AS IS" with no warranties or guarantees and confers no rights