I have 4 servers on which I need to do some processing. The processing is in two parts:
- Run a batch file
- Run a powershell script
I need the batch files to run simultaneously on all the servers, ideally at precisely the same time. I have currently set up scheduled tasks on all of the servers because we use a network time service so they are in synchronisation.
I then need to run the Powershell scripts one after the other, i.e. when the script on Server1 finishes, the script on Server2 begins, then when it finishes, Server3 begins, etc. This could be done in the same way as Part 1, i.e. scheduled tasks, however the tasks take massively varying lengths of time to complete.
I want to avoid the scheduled tasks option for the batch files, even though the time is in sync, I would rather have them all kick off from one place. Finally I need suggestions on how to go about invoking the Powershell scripts in a queue-like manner across different servers. Is this possible?
Edit 2012-04-11
With the help of Keith Hill’s answer I have managed to get closer to what I need. It would make sense for me to post my code at this point:
# $strServers[0] must correspond to $strFiles[0]
# $strServers[1] must correspond to $strFiles[1]
# etc.
$strServers = @(
"di-ads-02",
"di-ads-03",
"si-ads-02",
"vm-ads-02"
);
$strFiles = @(
"D:\Utilities\test.ps1",
"D:\Utilities\test.ps1",
"C:\Utilities\test.ps1",
"D:\Utilities\test.ps1"
);
try
{
for ($i = 0; $i -lt $strFiles.Count; $i++)
{
$job = Invoke-Command -cn $strServers[$i] -ScriptBlock {Invoke-Expression $strFiles[$i]} -AsJob;
# Wait for $job to finish for a maximum of 60 minutes
Wait-Job $job -Timeout 3600;
}
}
catch
{
Write-Host "ERROR : " + $_;
}
I get the following output from PowerShell:
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
47 Job47 Failed False di-ads-02 Invoke-Expression $str...
49 Job49 Failed False di-ads-03 Invoke-Expression $str...
51 Job51 Failed False si-ads-02 Invoke-Expression $str...
53 Job53 Failed False vm-ads-02 Invoke-Expression $str...
It looks to be getting halfway there, but the execution is failing. First I thought maybe it was running but just wasn’t reporting back correctly. I then modified the test.ps1 script so that it outputs two files (stderr and stdout) when it runs, so as to leave some proof behind. When I remote onto those servers and run the scripts locally, those files are generated, but doing it as the above script doesn’t work.
Any help would be appreciated.
If you can enable PowerShell remoting on the servers, you can orchestrate the execution of the PowerShell script using jobs from one machine e.g.: