关于远程作业About Remote Jobs

简短说明Short Description

描述如何在远程计算机上运行作业。Describes how to run jobs on remote computers.

详细说明Detailed Description

PowerShell 通过作业并发运行命令和脚本。PowerShell concurrently runs commands and scripts through jobs. PowerShell 提供三种作业类型来支持并发。There are three jobs types provided by PowerShell to support concurrency.

  • RemoteJob -命令和脚本在远程会话中运行。RemoteJob - Commands and scripts run in a remote session.
  • BackgroundJob -命令和脚本在本地计算机上的单独进程中运行。BackgroundJob - Commands and scripts run in a separate process on the local machine. 有关详细信息,请参阅 about_JobsFor more information, see about_Jobs.
  • PSTaskJobThreadJob -命令和脚本在本地计算机上的同一进程内的单独线程中运行。PSTaskJob or ThreadJob - Commands and scripts run in a separate thread within the same process on the local machine. 有关详细信息,请参阅 about_Thread_JobsFor more information, see about_Thread_Jobs.

在单独的计算机上或在单独的进程中远程运行脚本可提供强大的隔离。Running scripts remotely, on a separate machine or in a separate process, provide great isolation. 远程作业中发生的任何错误都不会影响其他正在运行的作业或启动作业的父会话。Any errors that occur in the remote job do not affect other running jobs or the parent session that started the job. 但是,远程处理层增加了开销,包括对象序列化。However, the remoting layer adds overhead, including object serialization. 所有对象都将进行序列化和反序列化,因为在父会话与远程 (作业) 会话之间传递它们。All objects are serialized and deserialized as they are passed between the parent session and the remote (job) session. 大型复杂数据对象的序列化会消耗大量的计算和内存资源,并跨网络传输大量数据。Serialization of large complex data objects can consume large amounts of compute and memory resources and transfer large amounts of data across the network.

重要

创建作业的父会话还会监视作业状态和收集管道数据。The parent session that created the job also monitors the job status and collects pipeline data. 作业到达完成状态后,父进程终止了作业子进程。The job child process is terminated by the parent process once the job reaches a finished state. 如果终止了父会话,则所有正在运行的子作业都将与其子进程一起终止。If the parent session is terminated, all running child jobs are terminated along with their child processes.

可通过两种方法解决此问题:There are two ways work around this situation:

  1. 用于 Invoke-Command 创建在断开连接的会话中运行的作业。Use Invoke-Command to create jobs that run in disconnected sessions. 请参阅本文中的 分离进程 部分。See the detached processes section of this article.
  2. 使用 Start-Process 创建新进程,而不是作业。Use Start-Process to create a new process rather than a job. 有关详细信息,请参阅 开始处理For more information, see Start-Process.

远程作业Remote Jobs

您可以使用三种不同的方法在远程计算机上运行作业。You can run jobs on remote computers by using three different methods.

  • 在远程计算机上启动交互式会话。Start an interactive session on a remote computer. 然后在交互式会话中启动作业。Then start a job in the interactive session. 尽管所有操作都是在远程计算机上执行的,但过程与运行本地作业相同。The procedures are the same as running a local job, although all actions are performed on the remote computer.

  • 在将其结果返回到本地计算机的远程计算机上运行作业。Run a job on a remote computer that returns its results to the local computer. 如果要收集作业的结果并在本地计算机上的一个中心位置维护这些作业的结果,请使用此方法。Use this method when you want to collect the results of jobs and maintain them in a central location on the local computer.

  • 在远程计算机上运行作业,该作业在远程计算机上维护其结果。Run a job on a remote computer that maintains its results on the remote computer. 在源计算机上更安全地维护作业数据时使用此方法。Use this method when the job data is more securely maintained on the originating computer.

在交互式会话中启动作业Start a job in an interactive session

您可以启动与远程计算机的交互式会话,然后在交互式会话过程中启动作业。You can start an interactive session with a remote computer and then start a job during the interactive session. 有关交互式会话的详细信息,请参阅 about_Remote,并参阅 Enter-PSSessionFor more information about interactive sessions, see about_Remote, and see Enter-PSSession.

在交互式会话中启动作业的过程与在本地计算机上启动后台作业的过程几乎相同。The procedure for starting a job in an interactive session is almost identical to the procedure for starting a background job on the local computer. 但是,所有操作都在远程计算机上执行,而不是在本地计算机上进行。However, all of the operations occur on the remote computer, not the local computer.

  1. 使用 Enter-PSSession cmdlet 来启动与远程计算机的交互式会话。Use the Enter-PSSession cmdlet to start an interactive session with a remote computer. 您可以使用 ComputerName 参数 Enter-PSSession 为交互式会话建立临时连接。You can use the ComputerName parameter of Enter-PSSession to establish a temporary connection for the interactive session. 或者,可以使用 Session 参数 (PSSession) 在 PowerShell 会话中运行交互式会话。Or, you can use the Session parameter to run the interactive session in a PowerShell session (PSSession).

    以下命令在 Server01 计算机上启动交互式会话。The following command starts an interactive session on the Server01 computer.

    C:\PS> Enter-PSSession -computername Server01
    

    命令提示符更改为显示你现在已连接到 Server01 计算机。The command prompt changes to show that you are now connected to the Server01 computer.

    Server01\C:>
    
  2. 若要在会话中启动远程作业,请使用 Start-Job cmdlet。To start a remote job in the session, use the Start-Job cmdlet. 以下命令运行远程作业,该作业获取 Server01 计算机上的 Windows PowerShell 事件日志中的事件。The following command runs a remote job that gets the events in the Windows PowerShell event log on the Server01 computer. Start-JobCmdlet 将返回表示作业的对象。The Start-Job cmdlet returns an object that represents the job.

    此命令将作业对象保存在 $job 变量中。This command saves the job object in the $job variable.

    Server01\C:> $job = Start-Job -scriptblock {
      Get-Eventlog "Windows PowerShell"
    }
    

    作业运行时,可以使用交互式会话来运行其他命令,包括其他作业。While the job runs, you can use the interactive session to run other commands, including other jobs. 但是,必须在作业完成之前使交互式会话保持打开状态。However, you must keep the interactive session open until the job is completed. 如果结束该会话,则该作业将中断,结果将丢失。If you end the session, the job is interrupted, and the results are lost.

  3. 若要查看作业是否已完成,请显示变量的值 $job ,或使用 Get-Job cmdlet 来获取作业。To find out if the job is complete, display the value of the $job variable, or use the Get-Job cmdlet to get the job. 以下命令使用 Get-Job cmdlet 来显示作业。The following command uses the Get-Job cmdlet to display the job.

    Server01\C:> Get-Job $job
    
    SessionId  Name  State      HasMoreData  Location   Command
    ---------  ----  -----      -----------  --------   -------
    1          Job1  Complete   True         localhost  Get-Eventlog "Windows...
    

    Get-Job此输出显示作业正在 "localhost" 计算机上运行,因为该作业已在同一台计算机上运行, (在这种情况下,Server01) 。The Get-Job output shows that job is running on the "localhost" computer because the job was started on and is running on the same computer (in this case, Server01).

  4. 若要获取作业结果,请使用 Receive-Job cmdlet。To get the results of the job, use the Receive-Job cmdlet. 可以在交互式会话中显示结果,也可以将结果保存到远程计算机上的文件中。You can display the results in the interactive session or save them to a file on the remote computer. 下面的命令获取 $job 变量中的作业的结果。The following command gets the results of the job in the $job variable. 该命令使用重定向运算符 (>) 将作业结果保存到 Server01 计算机上的 PsLog.txt 文件中。The command uses the redirection operator (>) to save the results of the job in the PsLog.txt file on the Server01 computer.

    Server01\C:> Receive-Job $job > c:\logs\PsLog.txt
    
  5. 若要结束交互式会话,请使用 Exit-PSSession cmdlet。To end the interactive session, use the Exit-PSSession cmdlet. 命令提示符将更改为显示您返回到本地计算机上的原始会话中。The command prompt changes to show that you are back in the original session on the local computer.

    Server01\C:> Exit-PSSession
    C:\PS>
    
  6. 若要随时查看 PsLog.txt Server01 计算机上文件的内容,请启动另一交互式会话或运行远程命令。To view the contents of the PsLog.txt file on the Server01 computer at any time, start another interactive session, or run a remote command. 如果要使用多个命令来调查和管理文件中的数据,这种类型的命令最好在 PSSession (持久性连接) 中运行 PsLog.txtThis type of command is best run in a PSSession (a persistent connection) in case you want to use several commands to investigate and manage the data in the PsLog.txt file. 有关 Pssession 的详细信息,请参阅 about_PSSessionsFor more information about PSSessions, see about_PSSessions.

    以下命令使用 New-PSSession cmdlet 创建连接到 Server01 计算机的 PSSession ,并使用 Invoke-Command cmdlet Get-Content 在 pssession 中运行命令,以查看文件的内容。The following commands use the New-PSSession cmdlet to create a PSSession that is connected to the Server01 computer, and they use the Invoke-Command cmdlet to run a Get-Content command in the PSSession to view the contents of the file.

    $s = New-PSSession -computername Server01
    Invoke-Command -session $s -scriptblock {
      Get-Content c:\logs\pslog.txt}
    

启动将结果返回到本地计算机的远程作业 (AsJob) Start a remote job that returns the results to the local computer (AsJob)

若要在将命令结果返回到本地计算机的远程计算机上启动作业,请使用 cmdlet 的 AsJob 参数,如 Invoke-Command cmdlet。To start a job on a remote computer that returns the command results to the local computer, use the AsJob parameter of a cmdlet such as the Invoke-Command cmdlet.

使用 AsJob 参数时,实际上会在本地计算机上创建作业对象,即使该作业在远程计算机上运行也是如此。When you use the AsJob parameter, the job object is actually created on the local computer even though the job runs on the remote computer. 完成作业后,结果将返回到本地计算机。When the job is completed, the results are returned to the local computer.

你可以使用包含 job 名词的 cmdlet (作业 cmdlet) 管理任何 cmdlet 创建的任何作业。You can use the cmdlets that contain the Job noun (the Job cmdlets) to manage any job created by any cmdlet. 许多具有 AsJob 参数的 cmdlet 不使用 PowerShell 远程处理,因此您甚至可以在未配置为进行远程处理并且不满足远程处理要求的计算机上使用它们。Many of the cmdlets that have AsJob parameters do not use PowerShell remoting, so you can use them even on computers that are not configured for remoting and that do not meet the requirements for remoting.

  1. 以下命令使用的 AsJob 参数 Invoke-Command 在 Server01 计算机上启动作业。The following command uses the AsJob parameter of Invoke-Command to start a job on the Server01 computer. 作业运行 Get-Eventlog 可获取系统日志中的事件的命令。The job runs a Get-Eventlog command that gets the events in the System log. 可以使用 JobName 参数为作业指定显示名称。You can use the JobName parameter to assign a display name to the job.

    Invoke-Command -computername Server01 -scriptblock {
      Get-Eventlog system} -AsJob
    

    命令的结果类似于以下示例输出。The results of the command resemble the following sample output.

    SessionId   Name   State    HasMoreData   Location   Command
    ---------   ----   -----    -----------   --------   -------
    1           Job1   Running  True          Server01   Get-Eventlog system
    

    使用 AsJob 参数时, Invoke-Command 将返回返回的相同类型的作业对象 Start-JobWhen the AsJob parameter is used, Invoke-Command returns the same type of job object that Start-Job returns. 可以将作业对象保存在变量中,也可以使用 Get-Job 命令来获取作业。You can save the job object in a variable, or you can use a Get-Job command to get the job.

    请注意,Location 属性的值显示作业在 Server01 计算机上运行。Note that the value of the Location property shows that the job ran on the Server01 computer.

  2. 若要管理使用 cmdlet 的 AsJob 参数启动的作业 Invoke-Command ,请使用作业 cmdlet。To manage a job started by using the AsJob parameter of the Invoke-Command cmdlet, use the Job cmdlets. 由于表示远程作业的作业对象位于本地计算机上,因此无需运行远程命令来管理该作业。Because the job object that represents the remote job is on the local computer, you do not need to run remote commands to manage the job.

    若要确定作业是否已完成,请使用 Get-Job 命令。To determine whether the job is complete, use a Get-Job command. 以下命令将获取在当前会话中启动的所有作业。The following command gets all of the jobs that were started in the current session.

    Get-Job
    

    由于远程作业是在当前会话中启动的,因此本地 Get-Job 命令会获取该作业。Because the remote job was started in the current session, a local Get-Job command gets the job. 作业对象的 State 属性显示该命令已成功完成。The State property of the job object shows that the command was completed successfully.

    SessionId   Name   State      HasMoreData   Location   Command
    ---------   ----   -----      -----------   --------   -------
    1           Job1   Completed  True          Server01   Get-Eventlog system
    
  3. 若要获取作业结果,请使用 Receive-Job cmdlet。To get the results of the job, use the Receive-Job cmdlet. 由于作业结果会自动返回到作业对象所在的计算机,因此你可以使用本地命令获取结果 Receive-JobBecause the job results are automatically returned to the computer where the job object resides, you can get the results with a local Receive-Job command.

    以下命令使用 Receive-Job cmdlet 来获取作业的结果。The following command uses the Receive-Job cmdlet to get the results of the job. 它使用会话 ID 来标识作业。It uses the session ID to identify the job. 此命令将作业结果保存在 $results 变量中。This command saves the job results in the $results variable. 你还可以将结果重定向到文件。You can also redirect the results to a file.

    $results = Receive-Job -id 1
    

启动远程作业以在远程计算机上保留结果Start a remote job that keeps the results on the remote computer

若要在远程计算机上启动将命令结果保存在远程计算机上的作业,请使用 Invoke-Command cmdlet Start-Job 在远程计算机上运行命令。To start a job on a remote computer that keeps the command results on the remote computer, use the Invoke-Command cmdlet to run a Start-Job command on a remote computer. 您可以使用此方法在多台计算机上运行作业。You can use this method to run jobs on multiple computers.

远程运行命令时 Start-Job ,将在远程计算机上创建作业对象,并在远程计算机上维护作业结果。When you run a Start-Job command remotely, the job object is created on the remote computer, and the job results are maintained on the remote computer. 从作业的角度来看,所有操作都是本地的。From the perspective of the job, all operations are local. 你只需远程运行命令来管理远程计算机上的本地作业。You are just running commands remotely to manage a local job on the remote computer.

  1. 使用 Invoke-Command cmdlet Start-Job 在远程计算机上运行命令。Use the Invoke-Command cmdlet to run a Start-Job command on a remote computer.

    此命令需要 PSSession (持久性连接) 。This command requires a PSSession (a persistent connection). 如果使用 ComputerName 参数 Invoke-Command 来建立临时连接,则在 Invoke-Command 返回作业对象时,该命令被视为已完成。If you use the ComputerName parameter of Invoke-Command to establish a temporary connection, the Invoke-Command command is considered to be complete when the job object is returned. 因此,临时连接将关闭,并且该作业将被取消。As a result, the temporary connection is closed, and the job is canceled.

    以下命令使用 New-PSSession cmdlet 创建连接到 Server01 计算机的 PSSession。The following command uses the New-PSSession cmdlet to create a PSSession that is connected to the Server01 computer. 该命令将 PSSession 保存在 $s 变量中。The command saves the PSSession in the $s variable.

    $s = New-PSSession -computername Server01
    

    下一个命令使用 Invoke-Command cmdlet Start-Job 在 PSSession 中运行命令。The next command uses the Invoke-Command cmdlet to run a Start-Job command in the PSSession. Start-Job命令和 Get-Eventlog 命令括在大括号中。The Start-Job command and the Get-Eventlog command are enclosed in braces.

    Invoke-Command -session $s -scriptblock {
      Start-Job -scriptblock {Get-Eventlog system}}
    

    结果类似于以下示例输出。The results resemble the following sample output.

    Id       Name    State      HasMoreData     Location   Command
    --       ----    -----      -----------     --------   -------
    2        Job2    Running    True            Localhost  Get-Eventlog system
    

    远程运行命令时 Start-JobInvoke-Command 将返回返回的相同类型的作业对象 Start-JobWhen you run a Start-Job command remotely, Invoke-Command returns the same type of job object that Start-Job returns. 可以将作业对象保存在变量中,也可以使用 Get-Job 命令来获取作业。You can save the job object in a variable, or you can use a Get-Job command to get the job.

    请注意, Location 属性的值显示作业在本地计算机上运行,也称为 "LocalHost",即使该作业在 Server01 计算机上运行也是如此。Note that the value of the Location property shows that the job ran on the local computer, known as "LocalHost", even though the job ran on the Server01 computer. 由于作业对象是在 Server01 计算机上创建的,并且作业在同一台计算机上运行,因此将其视为本地后台作业。Because the job object is created on the Server01 computer and the job runs on the same computer, it is considered to be a local background job.

  2. 若要管理远程作业,请使用 作业 cmdlet。To manage a remote job, use the Job cmdlets. 由于作业对象位于远程计算机上,因此您需要运行远程命令来获取、停止、等待或检索作业结果。Because the job object is on the remote computer, you need to run remote commands to get, stop, wait for, or retrieve the job results.

    若要查看作业是否已完成,请使用 Invoke-Command 命令 Get-Job 在连接到 Server01 计算机的 PSSession 中运行命令。To see if the job is complete, use an Invoke-Command command to run a Get-Job command in the PSSession that is connected to the Server01 computer.

    Invoke-Command -session $s -scriptblock {Get-Job}
    

    该命令返回一个作业对象。The command returns a job object. 作业对象的 State 属性显示该命令已成功完成。The State property of the job object shows that the command was completed successfully.

    SessionId   Name  State      HasMoreData   Location   Command
    ---------   ----  -----      -----------   --------   -------
    2           Job2  Completed  True          LocalHost   Get-Eventlog system
    
  3. 若要获取作业结果,请使用 Invoke-Command cmdlet Receive-Job 在已连接到 Server01 计算机的 PSSession 中运行命令。To get the results of the job, use the Invoke-Command cmdlet to run a Receive-Job command in the PSSession that is connected to the Server01 computer.

    以下命令使用 Receive-Job cmdlet 来获取作业的结果。The following command uses the Receive-Job cmdlet to get the results of the job. 它使用会话 ID 来标识作业。It uses the session ID to identify the job. 此命令将作业结果保存在 $results 变量中。This command saves the job results in the $results variable. 它使用 Keep 参数将 Receive-Job 结果保存在远程计算机上的作业缓存中。It uses the Keep parameter of Receive-Job to keep the result in the job cache on the remote computer.

    $results = Invoke-Command -session $s -scriptblock {
      Receive-Job -SessionId 2 -Keep
    }
    

    你还可以将结果重定向到本地或远程计算机上的文件。You can also redirect the results to a file on the local or remote computer. 以下命令使用重定向运算符将结果保存到 Server01 计算机上的文件中。The following command uses a redirection operator to save the results in a file on the Server01 computer.

    Invoke-Command -session $s -command {
      Receive-Job -SessionId 2 > c:\logs\pslog.txt
    }
    

如何作为分离的进程运行How to run as a detached process

如前所述,当终止父会话时,所有正在运行的子作业都将与其子进程一起终止。As previously mentioned, when the parent session is terminated, all running child jobs are terminated along with their child processes. 你可以使用本地计算机上的远程处理来运行未附加到当前 PowerShell 会话的作业。You can use remoting on the local machine to run jobs that are not attached to the current PowerShell session.

在本地计算机上创建新的 PowerShell 会话。Create a new PowerShell session on the local machine. 用于 Invoke-Command 在此会话中启动作业的。The use Invoke-Command to start a job in this session. Invoke-Command 允许您断开远程会话的连接,并终止父会话。Invoke-Command allows you to disconnect a remote session and terminate the parent session. 稍后,可以启动新的 PowerShell 会话并连接到之前断开连接的会话,以恢复监视作业。Later, you can start a new PowerShell session and connect to the previously disconnected session to resume monitoring the job. 但是,当终止该会话时,返回到原始 PowerShell 会话的任何数据都将丢失。However, any data that was returned to the original PowerShell session is lost when that session is terminated. 重新连接后,只会返回断开连接后生成的新数据对象。Only new data objects generated after the disconnect are returned when re-connected.

# Create remote session on local machine
PS> $session = New-PSSession -cn localhost

# Start remote job
PS> $job = Invoke-Command -Session $session -ScriptBlock { 1..60 | % { sleep 1; "Output $_" } } -AsJob
PS> $job

Id     Name     PSJobTypeName   State         HasMoreData     Location      Command
--     ----     -------------   -----         -----------     --------      -------
1      Job1     RemoteJob       Running       True            localhost     1..60 | % { sleep 1; ...

# Disconnect the job session
PS> Disconnect-PSSession $session

Id Name         Transport ComputerName    ComputerType    State         ConfigurationName     Availability
-- ----         --------- ------------    ------------    -----         -----------------     ------------
1 Runspace1     WSMan     localhost       RemoteMachine   Disconnected  Microsoft.PowerShell          None

PS> $job

Id     Name     PSJobTypeName   State         HasMoreData     Location      Command
--     ----     -------------   -----         -----------     --------      -------
1      Job1     RemoteJob       Disconnected  True            localhost     1..60 | % { sleep 1;

# Reconnect the session to a new job object
PS> $jobNew = Receive-PSSession -Session $session -OutTarget Job
PS> $job | Wait-Job | Receive-Job
Output 9
Output 10
Output 11
...

在此示例中,作业仍附加到父 PowerShell 会话。For this example, the jobs are still attached to a parent PowerShell session. 但是,父会话并不是运行的原始 PowerShell 会话 Invoke-CommandHowever, the parent session is not the original PowerShell session where Invoke-Command was run.

另请参阅See also