Wednesday, May 19, 2021

Run PowerShell script automatically after reboot

If you are working with scripting languages, you might have to do various scripts to fulfill requirements such as reboot the machine in the middle of installation until installation fully done. As scenario, You can think of Windows updates and the Reboot and check for further updates. This blog explains how to achieve it using schedule tasks.

Let's try to understand the script step by step.

  • Following first few lines of the script is for make sure the script is run as administrator.




  • Next section of the script explains how to use schedule task to achieve the given requirement. First it is looking for any pending windows updates. If there are any pending updates, set this script to run at reboot by adding new scheduler task. You can learn more about Register-ScheduledTask task by reading this document. Once, update is done, reboot the machine and this script will be triggered via scheduler task. It looks for the pending updates again. If there are any pending updates repeat the process until all the updates are installed. Once, all the updates are installed, remove the script from the scheduler task. You can read more about Unregister-ScheduledTask by reading this document.


You can find the full sample script as follows,


set-executionpolicy -scope CurrentUser -executionPolicy Bypass -Force
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
  # Relaunch as an elevated process:
  Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
  exit
}
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateupdateSearcher()
$Updates = @($UpdateSearcher.Search("IsHidden=0 and IsInstalled=0").Updates)
if ($Updates.Count -gt 0)
{
    # Pending updates 
    $Updates | Select-Object Title
    $scriptPath = "$PSScriptRoot\checkWinUpdates.ps1";
    Write-Host ("Script path is " + $scriptPath);
    # register schedule task so that the script runs at reboot
    Register-ScheduledTask -TaskName "smpleupdatetask" -Trigger (New-ScheduledTaskTrigger -AtLogon) -Action (New-ScheduledTaskAction -Execute "${Env:WinDir}\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument ("-Command `"& '" + $scriptPath + "'`"")) -RunLevel Highest -Force; 

    Install-PackageProvider NuGet -Force
    Import-PackageProvider NuGet -Force
    Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
   
 #  update and reboot if necessary
    Install-Module PSWindowsUpdate
    Get-Command module PSWindowsUpdate
    Add-WUServiceManager -ServiceID sampleserviceid -Confirm:$false
    Get-WUInstall MicrosoftUpdate AcceptAll AutoReboot
}
else
{
    # remove script from running at startup
    Unregister-ScheduledTask -TaskName "smpleupdatetask" -Confirm:$false
}

No comments:

Post a Comment