Parallel VM restore in PowerShell
Deal All,
When I try to run Parallel VM restore in PowerShell, I receive the following error message. We have functions for restoring, but the Parallel one does not work, could someone please assist me with this?
# Function to run the restore process for VMs in parallel using PowerShell runspaces
function Restore-VMsInParallel {
param (
[array]$VMsInfo
)
$runspacePool = [RunspaceFactory]::CreateRunspacePool(1, [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace)
$runspacePool.Open()
$jobs = @()
foreach ($vmInfo in $VMsInfo) {
$job = [PowerShell]::Create().AddScript({
param ($info)
Restore-VMAndSnapshots -SubscriptionId $info.SubscriptionId -ResourceGroupName $info.ResourceGroupName -VMName $info.VMName
}).AddArgument($vmInfo)
$job.RunspacePool = $runspacePool
$jobs += $job
}
$results = $jobs | ForEach-Object { $_.BeginInvoke() }
$jobs | ForEach-Object { $_.EndInvoke($_) }
$runspacePool.Close()
$runspacePool.Dispose()
}
# Read VM details with snapshot information from the CSV file
$csvFilePath = "C:\CSV\file.csv"
$vms = Import-Csv -Path $csvFilePath
# Create an array to store VM information
$vmInfoArray = @()
# Convert CSV data to VM information array
foreach ($vm in $vms) {
$vmInfo = @{
ResourceGroupName = $vm.ResourceGroupName
VMName = $vm.VMName
SubscriptionId = $vm.SubscriptionId
}
$vmInfoArray += New-Object PSObject -Property $vmInfo
}
# Restore all VMs in parallel
Restore-VMsInParallel -VMsInfo $vmInfoArray