【问题标题】:PowerShell implementing -AsJob for a cmdletPowerShell 为 cmdlet 实现 -AsJob
【发布时间】:2021-01-15 06:21:07
【问题描述】:

有没有像 Invoke-Command 那样在自定义 cmdlet 中实现开关参数 -AsJob 的好方法?

我想到的唯一方法是:

function Use-AsJob {
   [CmdletBinding()]
   [OutputType()]
   param (
      [Parameter(Mandatory = $true)]
      [string]
      $Message,

      [switch]
      $AsJob
   )

   # Wrap Script block in a variable
   $myScriptBlock = {
       # stuff
   }
   if ($AsJob) {
       Invoke-Command -ScriptBlock $myScriptBlock -AsJob
   }
   else {
       Invoke-Command -ScriptBlock $myScriptBlock
   }
}

有没有更好的方法?我在这方面找不到 Microsoft 文档,任何线索都有帮助。

【问题讨论】:

    标签: powershell jobs powershell-jobs


    【解决方案1】:

    如果我们做出以下假设:

    • 命令是脚本函数
    • 函数不依赖于模块状态

    然后您可以对任何命令使用以下样板:

    function Test-AsJob {
        param(
            [string]$Parameter = '123',
            [switch]$AsJob
        )
    
        if ($AsJob) {
            # Remove the `-AsJob` parameter, leave everything else as is
            [void]$PSBoundParameters.Remove('AsJob')
    
            # Start new job that executes a copy of this function against the remaining parameter args
            return Start-Job -ScriptBlock {
                param(
                    [string]$myFunction,
                    [System.Collections.IDictionary]$argTable
                )
    
                $cmd = [scriptblock]::Create($myFunction)
    
                & $cmd @argTable 
            } -ArgumentList $MyInvocation.MyCommand.Definition,$PSBoundParameters
        }
    
        # here is where we execute the actual function
        return "Parameter was '$Parameter'"
    }
    

    现在您可以执行以下任一操作:

    PS C:\> Test-AsJob
    Parameter was '123'
    PS C:\> Test-AsJob -AsJob |Receive-Job -Wait
    Parameter was '123'
    

    【讨论】:

    • 什么相当于:``` & $cmd @argTable 使用更详细的方法? ``` 我试过了:``` Invoke-Command -ScriptBlock $cmd -ArgumentList @argTable ``` 但这似乎不起作用
    • @Garbem & 不是别名,它是命令调用运算符。它已经很冗长了
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 2016-01-17
    • 2010-10-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多