PowerShell 为 cmdlet 实施 -AsJob

PowerShell implementing -AsJob for a cmdlet

有没有像 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 文档,任何线索都有帮助。

如果我们做以下假设:

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

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

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'