Skip to content

Instantly share code, notes, and snippets.

@selfagency
Created July 7, 2023 17:12
Show Gist options
  • Save selfagency/b1061aaea05f8a1874a04305cff31112 to your computer and use it in GitHub Desktop.
Save selfagency/b1061aaea05f8a1874a04305cff31112 to your computer and use it in GitHub Desktop.
schedule remote windows tasks
# Set the command to execute on remote servers
$command = "YourCommandHere"
# Set the list of remote servers
$servers = "server1", "server2", "server3"
# Set the schedule for the task (every day at 8:00 AM)
$schedule = "0 8 * * *"
# Set the username and password for authentication on remote servers
$credential = Get-Credential
# Create the script block to be executed on remote servers
$scriptBlock = {
param($command)
Invoke-Expression $command
}
# Create a scheduled task for each server
foreach ($server in $servers) {
$taskAction = New-ScheduledTaskAction -Script "powershell.exe" -Argument "-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -Command `"$using:scriptBlock`" -command $command"
$taskTrigger = New-ScheduledTaskTrigger -Daily -At $schedule
$taskPrincipal = New-ScheduledTaskPrincipal -UserId $credential.UserName -Password $credential.Password
$taskSettings = New-ScheduledTaskSettingsSet
Register-ScheduledTask -TaskName "ExecuteCommandOnServer-$server" -Action $taskAction -Trigger $taskTrigger -Principal $taskPrincipal -Settings $taskSettings -RunLevel Highest -Force
}
# To use this script, follow these steps:
# Replace "YourCommandHere" with the actual command you want to execute on the remote servers.
# Update the $servers variable with the list of remote servers you want to run the command on.
# Modify the $schedule variable to set the desired schedule for the task. The current example is set to run the task every day at 8:00 AM.
# Provide the username and password for authentication on remote servers when prompted by Get-Credential.
# Save the script to a PowerShell script file (e.g., ExecuteCommandOnRemoteServers.ps1).
# Open a PowerShell session with administrative privileges.
# Run the script by executing .\ExecuteCommandOnRemoteServers.ps1.
# The script will create a scheduled task for each remote server that executes the specified command according to the provided schedule.
# Note: Make sure you have administrative privileges and appropriate access to the remote servers for executing commands remotely.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment