How to add a callback function to an asynchronous job in powershell and get return data

后端 未结 3 1497
孤城傲影
孤城傲影 2021-01-16 01:38

I\'ve been searching around the internet and combining lots of different pieces of code, but I\'m just not succeeding at creating a callback for my asynchronous job.

3条回答
  •  梦毁少年i
    2021-01-16 02:23

    Try this one!

    `

    $rsPool = [runspacefactory]::CreateRunspacePool(1,2)
    $rsPool.Open();
    
    $WebRequest = {
        param($url)
        return Invoke-WebRequest -Uri ($url)
    }
    
    
    $jobs = @()
    
    $PSinstance = [powershell]::Create();
    $PSinstance.AddScript($WebRequest).AddArgument("https://google.com")
    $PSinstance.RunspacePool = $rsPool
    $Jobs += [PSCustomObject]@{ Pipe = $PSinstance; Status = $PSinstance.BeginInvoke() }
    
    $results=@()
    while ($Jobs.Status -ne $null)
    {
        start-sleep -s 1
        write-host "." -nonewline -fore cyan
        foreach ($completedjob in $Jobs|?{ $_.Status.IsCompleted -eq $true })
        {
            $results+=$completedjob.Pipe.EndInvoke($completedjob.Status)
            $completedjob.Status = $null
        }
    }
    
    $rsPool.close();
    
    $results|out-host
    

    `

提交回复
热议问题