PowerShell remote session and Start-Job issue

1.1k views Asked by At

I am trying to run following script with job but the code in the block only executes 1st command and exits. Job is displayed completed on my computer

$computers = get-adcomputer -filter * | where { ($_.DNSHostName -match 'server')} 

foreach ($computer in $computers) {
        $session = New-PSSession -ComputerName $computer.DNSHostName
        Invoke-Command -Session $session -ScriptBlock {
            Stop-Service  W3SVC -Force
            Remove-Item "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root" -Force -Recurse
            Start-Service  W3SVC     
        } -asjob -jobname IIS_Maintenance
        Remove-PSSession -Session $session
}

If I comment out -asjob -jobname IIS_Maintenance job runs fine but it's synchronous. It takes several seconds to stop IIS but I am not sure why job is not waiting on that.

Thoughts?

2

There are 2 answers

1
Sid On

Creating the session induces a lot of delay. Why did you chose to use the -Session instead of directly using -ComputerName ?

I think using the -ComputerName way will be more efficient to run with Start-Job. Either way, Since you are invoking the jobs on remote machines, your workstation would have no clue on the progress of the jobs.

If you want to track the progress of the jobs, you shouldn't be using Invoke-Command at all.

0
opti2k4 On

OK I figured it out... the point of confusion was:

1) I didn't know I can send block of code without Session and yes session implementation is slow

2) I also didn't know I send invoke-command to several computers are once without foreach. Thank you for that Ansgar Wiechers!