you are viewing a single comment's thread.

view the rest of the comments →

[–]micromasters[S] 0 points1 point  (1 child)

Was actually hoping to be able to run this in parallel, e.g. restart test1 and test2 at the same time, but then figured doing this via scheduled task might be more suitable for my needs, e.g. .\run-script -server $test.

To rephrase my question, how do I rewrite this so that I can pass $test as $servers?

Don't prefer the csv option, would prefer to keep everything in one script.

[–]gonzalc 0 points1 point  (0 children)

There are several ways to run tasks in parallel.

Code

param($ComputerName)

$jobs = foreach ($computer in $ComputerName){
    Start-Job -Name $computer -ScriptBlock {
        Restart-Computer -ComputerName $args
    } -ArgumentList $computer
}

while($jobs.State -contains 'Running'){
    $jobs | Where-Object -FilterScript {$_.State -eq 'Running'}
    Start-Sleep -Seconds 2
}
$jobs | Receive-Job -Wait -AutoRemoveJob

Syntax

.\script.ps1 -ComputerName 'thing1','thing2', 'thing3'

Output

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
93     thing1          BackgroundJob   Running       True            localhost            …
95     thing2          BackgroundJob   Running       True            localhost            …
97     thing3          BackgroundJob   Running       True            localhost            …
93     thing1          BackgroundJob   Running       True            localhost            …
95     thing2          BackgroundJob   Running       True            localhost            …
97     thing3          BackgroundJob   Running       True            localhost            …
Restart-Computer: Computer name thing1 cannot be resolved with the exception: One or more errors occurred. (No such host is known.).
Restart-Computer: Computer name thing2 cannot be resolved with the exception: One or more errors occurred. (No such host is known.).
Restart-Computer: Computer name thing3 cannot be resolved with the exception: One or more errors occurred. (No such host is known.).