以下代码可以按顺序完美地工作,但是我想使其并行运行。我还有很多其他功能要转换,并希望该功能成为我计划进行的所有转换的模板。我不知道哪个最好用。工作流或运行空间。我都没有成功。
Function New-TestCimSession {
[CmdletBinding(
SupportsShouldProcess = $true
)]
param(
[Parameter(
Position = 0,
Mandatory = $false,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $True,
HelpMessage = "Computer(s) you want to create a CimSession to")]
[ValidateNotNullOrEmpty()]
[string[]]
$ComputerName = $env:COMPUTERNAME,
[Parameter(
Position = 1,
Mandatory = $false,
ValueFromPipelineByPropertyName = $True,
HelpMessage = "Describe what the value of the parameter should be")]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Credential()]
[System.Management.Automation.PSCredential]
$Credential = [System.Management.Automation.PSCredential]::Empty
)
begin {
Write-Verbose "New-TestCimSession: Started"
Set-StrictMode -Version 1.0 #Option Explicit
$ErrorActionPreference = 'Stop'
$AllComputerObjects = [System.Collections.ArrayList]@()
$SessionParams = @{
ErrorAction = 'Stop'
}
$Opt = New-CimSessionOption -Protocol DCOM
$SessionParams.SessionOption = $Opt
if ($PSBoundParameters['Credential']) {
$SessionParams.Credential = $Credential
}
else {
$SessionParams.Credential = Get-Credential
}
}
process {
foreach ($Computer in $ComputerName) {
$SessionParams.ComputerName = $Computer
$SessionParams.SessionOption = $Opt
$NewComputerObject = [PSObject] @{}
$NewComputerObject | Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value "$Computer"
try {
$NewComputerObject | Add-Member -MemberType NoteProperty -Name 'CimSession' -Value (New-CimSession @SessionParams)
}
catch {}
if ($null -ne $NewComputerObject.CimSession) {
$NewComputerObject | Add-Member -MemberType NoteProperty -Name 'CimSessionConnected' -Value $true
}
else {
$NewComputerObject | Add-Member -MemberType NoteProperty -Name 'CimSessionConnected' -Value $false
}
$AllComputerObjects += $NewComputerObject
}
}
end {
Write-Verbose "New-TestCimSession: Completed"
return , $AllComputerObjects
}
}
答案 0 :(得分:0)
有一些答案,但是我最了解的是使用Powershell Job
。这是有关如何使用它们的示例:
$asyncBlock = {
# Code to run asynchronously goes here
}
# Start the background job
$bgJob = Start-Job $asyncBlock
# Do other stuff here
# Wait for the background job to complete before continuing
$bgJob | Wait-Job
# Get the resulting output from the background job
$result = Receive-Job -Job $bgJob
如果您想完全异步运行New-TestCimSession
,请像这样调用它:
$bgJob = Start-Job { New-TestCimSession -Arguments go -Here }
$bgJob | Wait-Job
$result = $bgJob | Receive-Job
然后将$result
处理为该函数的输出。