cat VM.csv 
Name,Template,PhysicalHost,Datastore,Networkmgt,Networkpro,IPV4mgt,Cpu,Memory,DISK,Usage,cdir
p1_caiwu_web001,win2016,10.18.44.13,NAS03,P1_MGT_9,P1_PRO_c1_1109,10.10.124.130,6,32,350,Safe-app,caiwuchu
function ConnectToVCenter {
    param(
        [Parameter(Mandatory=$true)]
        [string]$server,
        [Parameter(Mandatory=$true)]
        [string]$user,
        [Parameter(Mandatory=$true)]
        [string]$password
    )
    try {
        Connect-VIServer -Protocol https -User $user -Password $password -Server $server
    } catch {
        Write-Error "Failed to connect to vCenter: $_"
        exit 1
    }
}

function CreateVM {
    param(
        [Parameter(Mandatory=$true)]
        [PSCustomObject]$vmData
    )
    try {
        New-VM -Name $vmData.Name -Template $vmData.Template -VMHost $vmData.PhysicalHost -NetworkName $vmData.Networkmgt ,$vmData.Networkpro  -Datastore $vmData.Datastore -RunAsync -Location $vmData.cdir
    } catch {
        Write-Error "Failed to create VM: $_"
    }
}

function WaitForVMCreation {
    param(
        [Parameter(Mandatory=$true)]
        [string]$vmName
    )
    $num = 0
    while($num -le 5){ 
        Start-Sleep -s 10
        if (Get-VM -Name $vmName 2> /dev/null | Where-Object {$_.Name -eq $vmName}) {
            "$vmName 创建成功"
            $num = 6
        } else {
            $num = 0
        }
    }
}

function ConfigureVM {
    param(
        [Parameter(Mandatory=$true)]
        [PSCustomObject]$vmData
    )
    try {
        Get-VM -Name $vmData.Name | Set-VM  -NumCPU $vmData.Cpu -MemoryGB $vmData.Memory  -Notes $vmData.Usage -Confirm:$false
        Start-Sleep -s 5
        if ($vmData.DISK -gt 0) {
            Get-VM -Name $vmData.Name  | New-HardDisk -CapacityGB $vmData.DISK -Persistence persistent -StorageFormat Thin
        }
        Start-Sleep -s 10
        Get-VM $vmData.Name | Start-VM
    } catch {
        Write-Error "Failed to configure VM: $_"
    }
}

# Main script starts here
$file = $args[0]
if ( $file -gt 0 ) {echo $file;} else {echo '请添加参数文件[ eg:pwsh pwshtest.ps1 VM.csv ]';exit;} 

$vms = Import-CSV $file

#连接vCenter 
ConnectToVCenter -server '110.118.24.115' -user 'administrator@vsphere.local' -password 'Sckl#2023!'

#创建新虚拟机
foreach ($vm in $vms){
    CreateVM -vmData $vm
}

"等待虚机完成!"
#判断虚拟机是否创建完成
foreach ($vm in $vms){
    WaitForVMCreation -vmName $vm.Name
}

"所有虚机创建完成,开始调整资源配置,并启动!"
#配置新虚拟机并开机
foreach ($vm in $vms){
    ConfigureVM -vmData $vm
}