从Get-Job返回scriptblock的输出?

时间:2016-08-08 16:03:17

标签: asynchronous powershell-v3.0

我试图在PowerShell 3中测试异步功能。

所以我想我会远程查询某些服务器的正常运行时间,并编写以下脚本:

function getServerUptimes() {
    # Obtain credentials for logging into 
    # the remote machines...
    $cred = Get-Credential

    $compsHash = @{
       "server1.domain.com" = $null;
       "server2.domain.com" = $null;
    }

    # Define an async block to run...no blocking in this script...
    $cmd = {
        param($computer, $dasCred)

        Write-Host "which: $($computer)"
        $session = new-cimsession $computer -Credential $dasCred

        return (get-CimInstance win32_operatingsystem -CimSession $session | Select PScomputername, LastBootuptime);
    }

    ForEach($comp in $compsHash.Keys) {
        Write-Host "${comp}"

        # Kick off an async process to create a cimSession 
        # on each of these machines...
        Start-Job -ScriptBlock $cmd -ArgumentList $comp, $cred -Name "Get$($comp)"  
    }

    $results = Get-Job | Wait-Job | Receive-Job

    # Retrieve the job, so we can look at the output
    ForEach($comp in $compHash.Keys) {
        $dasJob = Get-Job -Name "Get$($comp)"
        Write-Host $dasJob.output
    }

}

但是,我似乎并没有在生成的$dasJob对象中找回任何输出,我在scriptblock中返回了值,它在哪里?

1 个答案:

答案 0 :(得分:0)

您已在变量Write-Host中输出(当然不包括$results输出)。在PowerShell中,您可以通过Receive-Job检索作业输出。属性Output似乎总是空的(不确定原因)。