PowerShell正在为cmdlet实现-AsJob



有没有一种很好的方法可以在自定义cmdlet中实现开关参数-AsJob,就像InvokeCommand一样?

我唯一的想法是:

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'

相关内容

  • 没有找到相关文章

最新更新