PowerShell implementing -AsJob for a cmdlet

不问归期 提交于 2021-01-29 05:36:13

问题


Is there a nice way to implement the switch parameter -AsJob in custom cmdlets, like Invoke-Command has?

The only way I thought about this is:

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
   }
}

Is there a better approach? I couldn't find Microsoft docs on this, any lead helps.


回答1:


If we make the following assumptions:

  • Command is a script function
  • Function does not rely on module state

Then you can use the following boilerplate for any command:

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'"
}

Now you can do either:

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


来源:https://stackoverflow.com/questions/64122992/powershell-implementing-asjob-for-a-cmdlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!