Search code examples
powershellinvoke-commandrunspace

powershell invoke-command returns upon completion


I would like to parallel copy using robocopy and returning log data when it is done.

if i were to use invoke-command server1,server2,server3 { robocopy }, it spits out the logs as it is copying for $1, $2, $3. this getting very confusing and hard to read. Is there a way to have the log or progress returns when copying is done?

for example:

server3 done.. display all copied files
server1 done.. display all copied files
server2 done.. display all copied files

instead of

$3 display copied files
server1 display copied files
server2 display copied files
server2 display copied files
server1 display copied files
server2 display copied files

I know i could use runspace to multi threads and check completion for handle to display the data (which i am currently using). but i would like to know if it is possible to do the same with invoke-command and it is easier :).

thanks


Solution

  • To expand on my comment, you could create your desired action as a scriptblock, use the -AsJob parameter to make background jobs for the copy actions, then wait for the jobs to finish and output the results when they're done.

    $SB = {
        & robocopy \\FileServer\Share\KittenPictures C:\webroot\MySite\Images *.*
    }
    $Servers = ('ServerA','ServerB','ServerC')
    $Jobs = Invoke-Command -ScriptBlock $SB -ComputerName $Servers -AsJob
    While($Jobs.JobStateInfo -Contains Running){
        $Jobs | Wait-Job -Any
        Get-Job -State Completed | ForEach{
            $_ | Receive-Job
            $_ | Remove-Job
        }
    }