对于那些希望在模块中使用“并行”工作流程(无递归)的人来说,解决方案类似但略有不同。
例如,此工作流可用于并行启动/停止服务
Workflow Invoke-ServiceInParallelWF
{
<#
.SYNOPSIS
Workflow to stop/start services in parallel on a server.
.DESCRIPTION
Utilizes a workflow to start/stop services running on a server in parallel to shorten the start/stop duration.
#>
Param(
[Parameter(Mandatory=$true)]
[string[]]$Name,
[Parameter(Mandatory=$true)]
[ValidateSet("Start","Stop")]
[string]$Action
)
if (!($Name.Count -gt 0))
{
throw "No services provided!"
}
# run parrallel on services argument
foreach -parallel ($svc in $Name){
InlineScript{
#build object first for consistency
$props=[ordered]@{
Service=$using:svc;
Action=$using:action
Result=$null
Error=$null
}
# Wrap in exception handler
Try{
#Perform the desired service action
if ($using:action -eq 'stop') {
Stop-Service -name $using:svc -ErrorAction stop
} elseif ($using:action -eq 'start') {
Start-Service -name $using:svc -ErrorAction stop
} else {
$Action='unknown'
}
$props.Result='Success'
}
Catch{
$props.Result='Fail'
$props.Error="$_"
}
# generate object back to workflow
New-Object -TypeName PSCustomObject -Property $props
}
}
}
如果你把它放在你的 psm1 文件中并尝试导入它,它将失败并出现以下错误:
At C:\Source\Powershell\Common\Modules\MyModule\MyModule.psm1:1 char:1
+ #
+ ~
A workflow cannot use recursion.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : RecursiveWorkflowNotSupported
要将其嵌入到模块中,请不要将其放在 .psm1 文件中,创建一个单独的 ps1 文件并将其放在模块文件夹中。例如调用-ServiceInParallelWF.ps1
然后在您的清单 (psd1) 文件中,修改 ScriptsToProcess 以包含 ps1 文件。
@{
# Script module or binary module file associated with this manifest.
RootModule = 'MyModule.psm1'
# Version number of this module.
ModuleVersion = '1.47.1'
# ID used to uniquely identify this module
GUID = 'bd4390dc-a8ad-4bce-8d69-f53ccf8e4163'
# Author of this module
Author = 'Justin Marshall'
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
ScriptsToProcess = @('Invoke-ServiceInParallelWF.ps1')
}
最后,导入您的模块并测试功能:
PS C:\source\powershell> Import-Module MyModule -force
PS C:\source\powershell> Invoke-ServiceInParallelWF -Action Start -Name w3svc
Service : w3svc
Action : Start
Result : Success
Error :
PSComputerName : localhost
PSSourceJobInstanceId : 1a564d5d-f363-44b7-a27e-88670764de2d