Receive-Job

取得目前會話中PowerShell背景工作的結果。

Syntax

Receive-Job
       [-Job] <Job[]>
       [[-Location] <String[]>]
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [<CommonParameters>]
Receive-Job
       [-Job] <Job[]>
       [[-ComputerName] <String[]>]
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [<CommonParameters>]
Receive-Job
       [-Job] <Job[]>
       [[-Session] <PSSession[]>]
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [<CommonParameters>]
Receive-Job
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [-Name] <String[]>
       [<CommonParameters>]
Receive-Job
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [-InstanceId] <Guid[]>
       [<CommonParameters>]
Receive-Job
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [-Id] <Int32[]>
       [<CommonParameters>]

Description

Cmdlet Receive-Job 會取得 PowerShell 背景工作的結果,例如使用 Start-Job 任何 Cmdlet 的 Cmdlet 或 AsJob 參數啟動的作業。 您可以取得所有作業的結果,或藉由其名稱、標識碼、實例標識碼、計算機名稱、位置或會話,或提交作業對象來識別作業。

當您啟動PowerShell背景作業時,作業會啟動,但結果不會立即出現。 相反地,命令會傳回代表背景工作的物件。 作業物件包含作業的實用資訊,但不包含結果。 這個方法可讓您在作業執行時繼續在會話中工作。 如需 PowerShell 中背景工作的詳細資訊,請參閱 about_Jobs

Cmdlet Receive-Job 會取得提交命令時 Receive-Job 所產生的結果。 如果結果尚未完成,您可以執行其他 Receive-Job 命令以取得剩餘的結果。

根據預設,當您收到結果時,作業結果會從系統中刪除,但您可以使用 Keep 參數來儲存結果,以便再次接收結果。 若要刪除作業結果,請再次執行Receive-Job命令,而不使用 Remove-Job Keep 參數、關閉工作階段,或使用 Cmdlet 從工作階段中刪除作業。

從 Windows PowerShell 3.0 開始, Receive-Job 也會取得自定義作業類型的結果,例如工作流程作業和排程工作的實例。 若要啟用 Receive-Job 以取得自定義作業類型的結果,請在執行命令之前 Receive-Job ,先將支援自定義作業類型的模組匯入會話,方法是使用 Import-Module Cmdlet 或使用 或取得模組中的 Cmdlet。 如需特定自定義作業類型的相關信息,請參閱自定義作業類型功能的檔。

範例

範例 1:取得特定作業的結果

$job = Start-Job -ScriptBlock {Get-Process}
Receive-Job -Job $job

這些命令會使用Receive-Job Job 參數來取得特定作業的結果。

第一個命令會使用 Start-Job 啟動作業,並將作業物件儲存在變數中 $job

第二個命令會 Receive-Job 使用 Cmdlet 來取得作業的結果。 它會使用 Job 參數來指定作業。

範例 2:使用 Keep 參數

$job = Start-Job -ScriptBlock {Get-Service dhcp, fakeservice}
$job | Receive-Job -Keep

Cannot find any service with service name 'fakeservice'.
    + CategoryInfo          : ObjectNotFound: (fakeservice:String) [Get-Service], ServiceCommandException
    + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
    + PSComputerName        : localhost

Status   Name               DisplayName
------   ----               -----------
Running  dhcp               DHCP Client

$job | Receive-Job -Keep

Cannot find any service with service name 'fakeservice'.
    + CategoryInfo          : ObjectNotFound: (fakeservice:String) [Get-Service], ServiceCommandException
    + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
    + PSComputerName        : localhost

Status   Name               DisplayName
------   ----               -----------
Running  dhcp               DHCP Client

此範例會將作業儲存在變數中 $job ,並將作業管線傳送至 Receive-Job Cmdlet。 -Keep參數也可用來允許在第一次檢視之後再次擷取所有匯總數據流數據。

範例 3:取得數個背景工作的結果

當您使用的 Invoke-Command AsJob 參數啟動作業時,即使作業是在遠端電腦上執行,還是會在本機電腦上建立作業物件。 因此,您會使用本機命令來管理作業。

此外,當您使用 AsJob 時,PowerShell 會傳回一個工作物件,其中包含每個已啟動作業的子作業。 在此情況下,作業物件包含三個子工作,每個遠端計算機上的每個作業各一個。

# Use the Invoke-Command cmdlet with the -AsJob parameter to start a background job that runs a Get-Service command on three remote computers.
# Store the resulting job object in the $j variable
$j = Invoke-Command -ComputerName Server01, Server02, Server03 -ScriptBlock {Get-Service} -AsJob
# Display the value of the **ChildJobs** property of the job object in $j.
# The display shows that the command created three child jobs, one for the job on each remote computer.
# You could also use the -IncludeChildJobs parameter of the Get-Job cmdlet.
$j.ChildJobs

Id   Name     State      HasMoreData   Location       Command
--   ----     -----      -----------   --------       -------
2    Job2     Completed  True          Server01       Get-Service
3    Job3     Completed  True          Server02       Get-Service
4    Job4     Completed  True          Server03       Get-Service

# Use the Receive-Job cmdlet to get the results of just the Job3 child job that ran on the Server02 computer.
# Use the *Keep* parameter to allow you to view the aggregated stream data more than once.
Receive-Job -Name Job3 -Keep

Status  Name        DisplayName                        PSComputerName
------  ----------- -----------                        --------------
Running AeLookupSvc Application Experience             Server02
Stopped ALG         Application Layer Gateway Service  Server02
Running Appinfo     Application Information            Server02
Running AppMgmt     Application Management             Server02

範例 4:取得多個遠端電腦上的背景工作結果

# Use the New-PSSession cmdlet to create three user-managed PSSessions on three servers, and save the sessions in the $s variable.
$s = New-PSSession -ComputerName Server01, Server02, Server03
# Use Invoke-Command run a Start-Job command in each of the PSSessions in the $s variable.
# The creates a new job with a custom name to each server
# The job outputs the datetime from each server
# Save the job objects in the $j variable.
$j = Invoke-Command -Session $s -ScriptBlock {​Start-Job -Name $('MyJob-' +$env:COMPUTERNAME) -ScriptBlock {(Get-Date).ToString()​}​}
# To confirm that these job objects are from the remote machines, run Get-Job to show no local jobs running.
Get-Job​​



# Display the three job objects in $j.
# Note that the Localhost location is not the local computer, but instead localhost as it relates to the job on each Server.
$j

Id   Name               State      HasMoreData   Location   Command
--   ----               -----      -----------   --------   -------
1    MyJob-Server01     Completed  True          Localhost  (Get-Date).ToString()
2    MyJob-Server02     Completed  True          Localhost  (Get-Date).ToString()
3    MyJob-Server03     Completed  True          Localhost  (Get-Date).ToString()

# Use Invoke-Command to run a Receive-Job command in each of the sessions in the $s variable and save the results in the $results variable.
# The Receive-Job command must be run in each session because the jobs were run locally on each server.
$results = Invoke-Command -Session $s -ScriptBlock {​Receive-Job -Name $('MyJob-' +$env:COMPUTERNAME)}

3/22/2021 7:41:47 PM
3/22/2021 7:41:47 PM
3/22/2021 9:41:47 PM

此範例示範如何取得在三部遠端計算機上執行背景工作的結果。 不同於先前的範例,使用 Invoke-Command 來執行 Start-Job 命令實際上在三部計算機上啟動三個獨立作業。 因此,命令會傳回三個工作物件,代表三個作業在三部不同計算機上本機執行。

範例 5:存取子作業

參數 -Keep 會保留作業匯總數據流的狀態,以便再次檢視它。 如果沒有此參數,所有匯總的數據流數據都會在收到作業時清除。 如需詳細資訊,請參閱 about_Job_Details

注意

匯總數據流包含所有子作業的數據流。 您仍然可以透過作業物件和子作業物件連線到個別數據流。

Start-Job -Name TestJob -ScriptBlock {dir C:\, Z:\}
# Without the Keep parameter, aggregated child job data is displayed once.
# Then destroyed.
Receive-Job -Name TestJob

Directory: C:\

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-r---        1/24/2019   7:11 AM                Program Files
d-r---        2/13/2019   8:32 AM                Program Files (x86)
d-r---        10/3/2018  11:47 AM                Users
d-----         2/7/2019   1:52 AM                Windows
Cannot find drive. A drive with the name 'Z' does not exist.
    + CategoryInfo          : ObjectNotFound: (Z:String) [Get-ChildItem], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
    + PSComputerName        : localhost

# It would seem that the child job data is gone.
Receive-Job -Name TestJob



# Using the object model, you can still retrieve child job data and streams.
$job = Get-Job -Name TestJob
$job.ChildJobs[0].Error

Cannot find drive. A drive with the name 'Z' does not exist.
    + CategoryInfo          : ObjectNotFound: (Z:String) [Get-ChildItem], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
    + PSComputerName        : localhost

參數

-AutoRemoveJob

指出此 Cmdlet 會在作業傳回結果之後刪除作業。 如果作業有更多結果,作業仍會遭到刪除,但 Receive-Job 會顯示訊息。

此參數僅適用於自訂作業類型。 它是針對作業類型的實例所設計,可儲存作業或會話外部的類型,例如排程工作的實例。

如果沒有 Wait 參數,就無法使用此參數。

此參數是在 Windows PowerShell 3.0 中引進的。

Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-ComputerName

指定計算機名稱的陣列。

此參數會從儲存在本機計算機上的作業結果中選取。 它不會取得遠端電腦上執行的作業數據。 若要取得儲存在遠端電腦上的作業結果,請使用 Invoke-Command Cmdlet 從遠端執行 Receive-Job 命令。

Type:String[]
Aliases:Cn
Position:1
Default value:All computers available
Required:False
Accept pipeline input:True
Accept wildcard characters:True

-Force

指出此 Cmdlet 會繼續等候作業是否處於 「已暫止 」或 「已中斷連線 」狀態。 根據預設,當作業處於下列其中一種狀態時, Wait 參數 Receive-Job 會傳回或終止等候:

  • 已完成
  • 失敗
  • 已停止
  • 已暫停
  • 已中斷連接

Force 參數只有在命令中也使用 Wait 參數時才有效。

此參數是在 Windows PowerShell 3.0 中引進的。

Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Id

指定標識碼的陣列。 此 Cmdlet 會取得具有指定標識符之作業的結果。

標識碼是整數,可唯一識別目前會話中的作業。 比實例標識碼更容易記住和輸入,但只在目前的會話中是唯一的。 您可以輸入一或多個以逗號分隔的識別碼。 若要尋找作業的識別碼, 請使用 Get-Job

Type:Int32[]
Position:0
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-InstanceId

指定實例識別碼的陣列。 此 Cmdlet 會取得具有指定實例標識碼之作業的結果。

實例標識碼是可唯一識別計算機上作業的 GUID。 若要尋找作業的實例標識碼,請使用 Get-Job Cmdlet。

Type:Guid[]
Position:0
Default value:All instances
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-Job

指定要擷取結果的作業。

輸入包含作業的變數,或取得作業的命令。 您也可以使用管線將作業物件傳送至 Receive-Job

Type:Job[]
Position:0
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

-Keep

指出此 Cmdlet 會將匯總數據流數據儲存在系統中,即使您已收到它們也一定。 根據預設,使用 檢視之後,會清除匯總數據流 Receive-Job數據。

關閉會話,或使用 Cmdlet 移除作業 Remove-Job 也會刪除匯總的數據流數據。

Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Location

指定位置陣列。 此 Cmdlet 只會取得指定位置中作業的結果。

Type:String[]
Position:1
Default value:All locations
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Name

指定易記名稱的陣列。 此 Cmdlet 會取得具有指定名稱之作業的結果。 支援使用萬用字元。

Type:String[]
Position:0
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:True

-NoRecurse

表示此 Cmdlet 只會從指定的作業取得結果。 根據預設, Receive-Job 也會取得指定作業的所有子作業結果。

Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Session

指定工作階段陣列。 此 Cmdlet 會取得在指定 PowerShell 工作階段中執行之作業的結果(PSSession)。 輸入包含 PSSession 的變數,或取得 PSSession 的命令,例如Get-PSSession命令。

Type:PSSession[]
Position:1
Default value:All sessions
Required:False
Accept pipeline input:True
Accept wildcard characters:False

-Wait

表示這個 Cmdlet 會隱藏命令提示字元,直到收到所有作業結果為止。 根據預設, Receive-Job 會立即傳回可用的結果。

根據預設, Wait 參數會等候作業處於下列其中一種狀態:

  • 已完成
  • 失敗
  • 已停止
  • 已暫停
  • 已中斷連接

若要指示 Wait 參數在作業狀態為 Suspended 或 Disconnected 時繼續等候,請使用 Force 參數搭配 Wait 參數。

此參數是在 Windows PowerShell 3.0 中引進的。

Type:SwitchParameter
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-WriteEvents

指出此 Cmdlet 會在等候作業完成時報告作業狀態中的變更。

只有在命令中使用 Wait 參數且省略 Keep 參數時,此參數才有效。

此參數是在 Windows PowerShell 3.0 中引進的。

Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-WriteJobInResults

指出這個 Cmdlet 會傳回作業物件,後面接著結果。

只有在命令中使用 Wait 參數且省略 Keep 參數時,此參數才有效。

此參數是在 Windows PowerShell 3.0 中引進的。

Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

輸入

Job

您可以使用管線將工作物件傳送至此 Cmdlet。

輸出

PSObject

此 Cmdlet 會傳回作業中命令的結果。

備註

PowerShell 包含下列的 Receive-Job別名:

  • 所有平臺:
    • rcjb