PowerShell为cmdlet实现-AsJob [英] PowerShell implementing -AsJob for a cmdlet
本文介绍了PowerShell为cmdlet实现-AsJob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种很好的方法可以在自定义cmdlet中实现开关参数-AsJob,就像Invoke-Command一样?
Is there a nice way to implement the switch parameter -AsJob in custom cmdlets, like Invoke-Command has?
我想到的唯一方法是:
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文档,任何线索都可以帮助您.
Is there a better approach? I couldn't find Microsoft docs on this, any lead helps.
推荐答案
如果我们做出以下假设:
If we make the following assumptions:
- 命令是脚本功能
- 功能不依赖于模块状态
然后,您可以将以下样板用于任何命令:
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'
这篇关于PowerShell为cmdlet实现-AsJob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文