You are here

Effortless Task Distribution Across Servers Using PowerShell


Effortless Task Distribution Across Servers Using PowerShell

The task of distributing a set of scheduled tasks across numerous servers arose. It brought back memories of a time when this could be accomplished through group policies. Although this option is still available, it no longer allows specifying a particular account, especially one with a password, under which the task should be executed. There's a workaround by manually tweaking the group policy files in sysvol, but it’s a risky and crude approach.

If you are faced with the challenge of copying, let's say, 20 tasks to 10 machines, the monotonous routine of exporting, importing, and password entering can be draining. As this tedious process nears completion, the likelihood of missing out on something increases. And what if the tasks need amendments later on?

To cut a long story short, this hurdle can be overcome with a compact PowerShell script, as demonstrated below:

$taskpath="\audit\"
$user="domain\scriptRunner"
$password="verysecret"
$tasks=get-ScheduledTask -taskpath $taskpath
$comps=Get-ADDomainController -filter * | Select-Object name
foreach ($comp in $comps){
    if ($comp.name -ne $env:computername){
        $comp.name
        Get-ScheduledTask -TaskPath $taskpath -CimSession $comp.name | Unregister-ScheduledTask -Confirm:$false
        foreach ($task in $tasks){
            $task.taskname
            $exported=export-scheduledtask -taskpath $taskpath -TaskName $task.taskname
            Register-ScheduledTask -Xml $exported -cimsession $comp.name -taskname $task.taskname -User $user -password $password -TaskPath $taskpath -force
        }
    }
}

 

In this scenario, all tasks from the audit folder are being copied to all domain controllers within the organization. The script scans all tasks in the specified folder, exports each task to XML (without any disk saving), and sequentially imports them to each computer. During the import, the username and password for the account, which will initiate the tasks, are specified.

Pay attention to this line:

Get-ScheduledTask -TaskPath $taskpath -CimSession $comp.name | Unregister-ScheduledTask -Confirm:$false

 

It clears the specified task folder on the target server. If this step is unnecessary, feel free to delete or comment it out.

The script can be found on ]]>GitHub]]>.

For those times when a change in the account password for scheduler tasks is necessary, I recommend checking out this post.

0 0

Share the article with your friends in social networks, maybe it will be useful to them.


If the article helped you, you can >>thank the author<<