当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] Receive-Job (Microsoft.PowerShell.Core)

作者:精品下载站 日期:2024-12-14 02:14:48 浏览:12 分类:玩电脑

Receive-Job (Microsoft.PowerShell.Core)


Receive-Job

模块 :Microsoft.PowerShell.Core

获取当前会话中 PowerShell 后台作业的结果。

句法

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
       [-Name] <string[]>
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [<CommonParameters>]
Receive-Job
       [-InstanceId] <guid[]>
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [<CommonParameters>]
Receive-Job
       [-Id] <int[]>
       [-Keep]
       [-NoRecurse]
       [-Force]
       [-Wait]
       [-AutoRemoveJob]
       [-WriteEvents]
       [-WriteJobInResults]
       [<CommonParameters>]

描述

Receive-Job cmdlet 获取 PowerShell 后台作业的结果,例如使用 Start-Job cmdlet 或 AsJob 参数启动的作业任何 cmdlet。您可以获取所有作业的结果,或者通过作业的名称、ID、实例 ID、计算机名称、位置或会话来识别作业,或者通过提交作业对象来识别作业。

当您启动 PowerShell 后台作业时,作业会启动,但结果不会立即显示。相反,该命令返回一个代表后台作业的对象。作业对象包含有关作业的有用信息,但不包含结果。此方法允许您在作业运行时继续在会话中工作。有关 PowerShell 中后台作业的更多信息,请参阅 about_Jobs。

Receive-Job cmdlet 获取提交 Receive-Job 命令时生成的结果。如果结果尚未完成,您可以运行其他 Receive-Job 命令来获取剩余结果。

默认情况下,当您收到作业结果时,作业结果将从系统中删除,但您可以使用保留参数保存结果,以便您可以再次接收它们。要删除作业结果,请再次运行不带 Keep 参数的 Receive-Job 命令、关闭会话或使用 Remove-Job cmdlet从会话中删除作业。

从 Windows PowerShell 3.0 开始,Receive-Job 还获取自定义作业类型的结果,例如工作流作业和计划作业的实例。要使 Receive-Job 能够获取自定义作业类型的结果,请在运行 Receive-Job 命令之前将支持自定义作业类型的模块导入到会话中,或者通过使用 Import-Module cmdlet 或获取模块中的 cmdlet。有关特定自定义作业类型的信息,请参阅自定义作业类型功能的文档。

示例

示例 1:获取特定作业的结果

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

这些命令使用 Receive-JobJob 参数来获取特定作业的结果。

第一个命令使用 Start-Job 启动作业,并将作业对象存储在 $job 变量中。

第二个命令使用 Receive-Job cmdlet 来获取作业的结果。它使用 Job 参数来指定作业。

示例 2:使用 Keep 参数

$job = Start-Job -ScriptBlock {Get-Service dhcp, fakeservice}
Start-Sleep -Seconds 1
$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 code 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.
$invokeCommandSplat = @{
    Session = $s
    ScriptBlock = {
        Start-Job -Name $('MyJob-' +$env:COMPUTERNAME) -ScriptBlock {
            (Get-Date).ToString()
        }
    }
}
$j = Invoke-Command @invokeCommandSplat
# 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 中引入的。

类型 :

SwitchParameter

位置:

命名

默认值:

False

必需的:

False

接受管道输入:

False

接受通配符:

False

-ComputerName

指定计算机名称的数组。

此参数从存储在本地计算机上的作业结果中进行选择。它不会获取在远程计算机上运行的作业的数据。要获取存储在远程计算机上的作业结果,请使用 Invoke-Command cmdlet 远程运行 Receive-Job 命令。

类型 :

String[]

别名:

Cn

位置:

1

默认值:

所有可用的计算机

必需的:

False

接受管道输入:

True

接受通配符:

True

-Force

指示如果作业处于已挂起已断开状态,则此 cmdlet 将继续等待。默认情况下,当作业处于以下状态之一时,Receive-JobWait 参数返回或终止等待:

  • 完全的
  • 失败的
  • 已停止
  • 暂停
  • 已断开连接。

仅当命令中同时使用Wait参数时,Force参数才有效。

此参数是在 Windows PowerShell 3.0 中引入的。

类型 :

SwitchParameter

位置:

命名

默认值:

False

必需的:

False

接受管道输入:

False

接受通配符:

False

-Id

指定 ID 数组。此 cmdlet 获取具有指定 ID 的作业的结果。

ID 是一个整数,唯一标识当前会话中的作业。它比实例 ID 更容易记住和输入,但它仅在当前会话中是唯一的。您可以键入一个或多个 ID,并用逗号分隔。要查找作业的 ID,请使用 Get-Job

类型 :

Int32[]

位置:

0

默认值:

None

必需的:

True

接受管道输入:

True

接受通配符:

False

-InstanceId

指定实例 ID 的数组。此 cmdlet 获取具有指定实例 ID 的作业的结果。

实例 ID 是唯一标识计算机上作业的 GUID。要查找作业的实例 ID,请使用 Get-Job cmdlet。

类型 :

指导[]

位置:

0

默认值:

所有实例

必需的:

True

接受管道输入:

True

接受通配符:

False

-Job

指定正在检索结果的作业。

输入包含作业的变量或获取作业的命令。您还可以通过管道将作业对象传递给 Receive-Job。

类型 :

工作[]

位置:

0

默认值:

None

必需的:

True

接受管道输入:

True

接受通配符:

False

-Keep

指示此 cmdlet 会将聚合的流数据保存在系统中,即使您已收到这些数据也是如此。默认情况下,聚合流数据在使用 Receive-Job 查看后会被删除。

关闭会话或使用 Remove-Job cmdlet 删除作业也会删除聚合的流数据。

类型 :

SwitchParameter

位置:

命名

默认值:

False

必需的:

False

接受管道输入:

False

接受通配符:

False

-Location

指定位置数组。此 cmdlet 仅获取指定位置的作业结果。

类型 :

String[]

位置:

1

默认值:

所有地点

必需的:

False

接受管道输入:

False

接受通配符:

False

-Name

指定友好名称的数组。此 cmdlet 获取具有指定名称的作业的结果。支持通配符。

类型 :

String[]

位置:

0

默认值:

None

必需的:

True

接受管道输入:

True

接受通配符:

True

-NoRecurse

指示此 cmdlet 仅从指定作业获取结果。默认情况下,Receive-Job 还会获取指定作业的所有子作业的结果。

类型 :

SwitchParameter

位置:

命名

默认值:

False

必需的:

False

接受管道输入:

False

接受通配符:

False

-Session

指定会话数组。此 cmdlet 获取在指定 PowerShell 会话 (PSSession) 中运行的作业的结果。输入包含 PSSession 的变量或获取 PSSession 的命令,例如 Get-PSSession 命令。

类型 :

PS会话[]

位置:

1

默认值:

所有会议

必需的:

False

接受管道输入:

True

接受通配符:

False

-Wait

指示此 cmdlet 抑制命令提示符,直到收到所有作业结果。默认情况下,Receive-Job 立即返回可用结果。

默认情况下,Wait 参数会一直等待,直到作业处于以下状态之一:

  • 完全的
  • 失败的
  • 已停止
  • 暂停
  • 已断开连接

要在作业状态为“暂停”或“断开连接”时指示 Wait 参数继续等待,请将 Force 参数与 Wait 参数一起使用。

此参数是在 Windows PowerShell 3.0 中引入的。

类型 :

SwitchParameter

位置:

命名

默认值:

None

必需的:

False

接受管道输入:

False

接受通配符:

False

-WriteEvents

指示此 cmdlet 在等待作业完成时报告作业状态的更改。

仅当命令中使用Wait参数且省略Keep参数时,该参数才有效。

此参数是在 Windows PowerShell 3.0 中引入的。

类型 :

SwitchParameter

位置:

命名

默认值:

False

必需的:

False

接受管道输入:

False

接受通配符:

False

-WriteJobInResults

指示此 cmdlet 返回作业对象,后跟结果。

仅当命令中使用Wait参数且省略Keep参数时,该参数才有效。

此参数是在 Windows PowerShell 3.0 中引入的。

类型 :

SwitchParameter

位置:

命名

默认值:

False

必需的:

False

接受管道输入:

False

接受通配符:

False

输入

工作

您可以通过管道将作业对象传递给此 cmdlet。

输出

PSObject

此 cmdlet 返回作业中命令的结果。

笔记

PowerShell 包含以下 Receive-Job 别名:

  • 所有平台:

      rcjb

    您需要 登录账户 后才能发表评论

    取消回复欢迎 发表评论:

    关灯