Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am running the following powershell script to run executable on multiple server machines. This executable takes about 1 minute to complete and output results to console window:

$servers = 'Srv001', 'Srv002';
$ErrorActionPreference = "STOP";

$credentials = Get-Credential 'adm\runner';

foreach($srv in $servers){

	$session = New-PSSession -ComputerName $srv -Credential $credentials;

        Invoke-Command -Session $session -ScriptBlock {
		    Write-Host ('Executing task on ' + $args) -ForegroundColor Green;
            PowerShell.exe -Command "& ""cmd.exe /C C:\Miner.exe""";
            Write-Host '---TEST COMPLETE---' -ForegroundColor Green;
	    } -ArgumentList $srv; #-AsJob
}

Remove-PSSession *;


now - this all works fine, but in current example I need to wait 2 minutes as I am running this on 2 servers. To solve this I've added "-AsJob" switch to Invoke-Command cmdlet (commented out part in code), but now I lost the view of results, because now they run in the background as jobs and dont output the results into console.

Any thoughts how I could get this back? I have 2 new objects though - 2 jobs, but these dont seem to have a property of "output" or something....

Thanks!

What I have tried:

See the code in problem description.
Posted
Updated 12-Mar-17 22:49pm

1 solution

I managed to solve that myself:


1. Invoke-Command as a job.
2. When all remote jobs are invoked I am starting a loop that check if all my jobs are complete:

While($true){

    Write-Host ((Get-Date).ToString('HH:mm:ss')) -ForegroundColor Green;
    
    $allFinished = $true;

    for($i = 0; $i -le (Get-Job).Count - 1; $i++){
        $currentJobCompleted = (Get-Job)[$i].State -eq 'Completed';
        $allFinished = $allFinished -and $currentJobCompleted;
    }

    if($allFinished -eq $true){
        break;
    }else{
        for($i = 0; $i -le (Get-Job).Count - 1; $i++){
            Write-Host ((Get-Job)[$i].Location + ' ' + (Get-Job)[$i].State) -ForegroundColor Gray;
        }        
    }

    Start-Sleep -Seconds 10;
}

Remove-PSSession *;


after all jobs complete - i execute
Receive-job <job id>


easy as that!
hope that helps anyone
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900