1

我在单个 VIServer 中从模板创建多个 VMWARE VM 时遇到问题。在以下代码中,当在节流脚本中放置大于 1 的任何内容时,仅执行一个虚拟机并且不创建任何其他虚拟机(并行),保持会话似乎有问题,很可能只是重置它或在 $global:DefaultVIServer 中修改它.

下面的代码基于此线程中的问题: 线程不创建多个虚拟机(会话问题) 答案是始终保持相同的会话,但我无法让它工作

我还假设这篇文章与我遇到的问题相同: https ://communities.vmware.com/thread/463060?start=0&tstart=0

我想知道是否有人在使用 powershell 中的运行空间在 vmware 中创建多个虚拟机方面有有效的解决方案?

cls
Add-PSSnapin VMware.VimAutomation.Core | Out-Null 
#import csv
$VMs = Import-CSV 'filename.csv' -UseCulture
#connections array
$server = @()
#threads
$throttle = 2
# Create session state
$sessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
# Create runspace pool consisting of runspaces
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $throttle, $sessionState, $host)
$RunspacePool.Open()
#array for jobs
$Jobs = @()
#this contains all connected vSphere endpoints
$global:DefaultVIServer

$User = "domain\username"
$PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord   



# SctiptBlock to execute for each job
$ScriptBlock = {
    Param ($VM, $ses) 

    Add-PSSnapin VMware.VimAutomation.Core | Out-Null
    Write-Host $VM.Name "Father session:    "  $ses.SessionSecret    

    Connect-VIServer $VM.VIServer -Session $ses.SessionSecret -wa 0
    Write-Host $VM.Name "Child session:    "   $sessionf.SessionId

    New-VM -Name $VM.Name -ResourcePool "..." -Location "Windows Servers" -Datastore "..." -DiskStorageFormat "..." -Notes "..." -Template "..."
}


# Starting script
Write-Host ("Starting script: {0}" -f (Get-Date))
$startTime = Get-Date

$count = 0
ForEach($VM in $VMs)
{

    $count  = $count + 1

    Write-Host "Current connections:"
    $Global:DefaultVIServers.count

    $ses = Connect-VIServer $VM.VIServer -Credential $Credential -wa 0   

    $Job = [powershell]::create()
    $Job.RunspacePool = $RunspacePool
    $Job.AddScript($ScriptBlock).AddParameter("VM", $VM).AddParameter("ses", $ses)

    Write-Host "Adding job to jobs list"    
    $Jobs += New-Object PSObject -Property @{
        RunNum = $count
        Job = $Job
        Result = $Job.BeginInvoke() | Out-Null
        }    
}

Write-Host "Waiting.." -NoNewline
Do {
   Write-Host "." -NoNewline
   Start-Sleep -Seconds 1
} While ( $Jobs.Result.IsCompleted -contains $false)

$endTime = Get-Date
$totalSeconds = "{0:N4}" -f ($endTime-$startTime).TotalSeconds
Write-Host "All jobs finished in $totalSeconds seconds"
4

0 回答 0