Creating a Scheduled Task Using PowerShell to Run A Script Every Hour
To create a scheduled task that runs a specific batch file every 1 hour using PowerShell, you can use the New-ScheduledTask cmdlet. Here’s an example command:
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-WindowStyle Hidden -File "C:\Scripts\autorun\start.ps1'
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration ([System.TimeSpan]::MaxValue)
$settings = New-ScheduledTaskSettingsSet
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "RunSrvGit" -Settings $settings
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-WindowStyle Hidden -File "C:\Scripts\autorun\start.ps1'This line creates a new scheduled task action using theNew-ScheduledTaskActioncmdlet. The action specifies that it will executepowershell.exe. The-Argumentparameter specifies the arguments to be passed to the executable. In this case, it specifies-WindowStyle Hidden -File "C:\Scripts\autorun\start.ps1', where-WindowStyle Hiddenensures that the PowerShell window is hidden, and-Filespecifies the path to the PowerShell script to be executed (C:\Scripts\autorun\start.ps1).$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration ([System.TimeSpan]::MaxValue)This line creates a new scheduled task trigger using theNew-ScheduledTaskTriggercmdlet. The trigger is set to run once initially (-Once) at the current date and time (-At (Get-Date)). The-RepetitionIntervalparameter specifies the interval between repetitions, which is set to 1 hour usingNew-TimeSpan -Hours 1. The-RepetitionDurationparameter is set to[System.TimeSpan]::MaxValue, indicating that the repetition should continue indefinitely.$settings = New-ScheduledTaskSettingsSetThis line creates a new scheduled task settings object using theNew-ScheduledTaskSettingsSetcmdlet. This object provides additional settings for the scheduled task.Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "RunSrvGit" -Settings $settingsFinally, this line registers the scheduled task using theRegister-ScheduledTaskcmdlet. It specifies the task’s action ($action), trigger ($trigger), task name ("RunSrvGit"), and settings ($settings).