共用方式為


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-JobKeep 參數、關閉工作階段,或使用 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-JobJob 參數來取得特定作業的結果。

第一個命令會使用 啟動 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-CommandAsJob 參數來啟動作業時,即使作業在遠端電腦上執行,也會在本機電腦上建立作業物件。 因此,您是使用本機命令來管理工作。

此外,當您使用 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 會傳回或終止等候:

  • Completed
  • 失敗
  • 已停止
  • 暫止
  • 已中斷連接

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

此參數是在 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 參數預設會等到工作處於下列其中一種狀態:

  • Completed
  • 失敗
  • 已停止
  • 暫止
  • 已中斷連接

若要指示 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 會傳回作業中命令的結果。