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-ScheduledTaskAction
cmdlet. The action specifies that it will executepowershell.exe
. The-Argument
parameter specifies the arguments to be passed to the executable. In this case, it specifies-WindowStyle Hidden -File "C:\Scripts\autorun\start.ps1'
, where-WindowStyle Hidden
ensures that the PowerShell window is hidden, and-File
specifies 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-ScheduledTaskTrigger
cmdlet. The trigger is set to run once initially (-Once
) at the current date and time (-At (Get-Date)
). The-RepetitionInterval
parameter specifies the interval between repetitions, which is set to 1 hour usingNew-TimeSpan -Hours 1
. The-RepetitionDuration
parameter is set to[System.TimeSpan]::MaxValue
, indicating that the repetition should continue indefinitely.$settings = New-ScheduledTaskSettingsSet
This line creates a new scheduled task settings object using theNew-ScheduledTaskSettingsSet
cmdlet. This object provides additional settings for the scheduled task.Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "RunSrvGit" -Settings $settings
Finally, this line registers the scheduled task using theRegister-ScheduledTask
cmdlet. It specifies the task’s action ($action
), trigger ($trigger
), task name ("RunSrvGit"
), and settings ($settings
).