主要功能:自己的Hyper-V手动导入太麻烦了,就写了脚本快速导入制作好的模板机,快速重命名其虚拟机名称和Hostname,根据需求是否加域。
模板机OS:Windows Server 2019
powershell: PS5.1
1 #2020年2月12日 16:22:52 2 #导入Hyper-v虚拟机 3 [cmdletbinding()] 4 param ( 5 [Parameter( 6 ValueFromPipelineByPropertyName = $true, 7 ValueFromPipeline = $true, 8 Mandatory = $true)] 9 [string]$VMNAME, 10 [Parameter( 11 Mandatory = $true, 12 HelpMessage = "是否需要加入AD" 13 )] 14 [ValidateSet("Y","N","y","n")] 15 [string]$ifdomain 16 ) 17 18 #选择模版 19 20 #导入虚拟机administrator身份 21 $administraotr = ".\administrator" 22 $pwd = ConvertTo-SecureString "xxxxxx" -AsPlainText -Force 23 $Cerd1 = New-Object System.Management.Automation.PSCredential($administraotr,$pwd) 24 #导入AD admin身份 25 26 #检查是否重名 27 while (get-vm -Name $VMNAME) { 28 $VMNAME = Read-Host "虚拟机重名,请重新输入一个计算机名" 29 } 30 #VM的路径 31 $Dspath = "F:\Hyper\$VMNAME" 32 #导入VM 33 $import = Import-VM -Path 'F:\templor\T-template-2019-unattend\Virtual Machines\8C451E35-4A02-4734-8E40-67358548301D.vmcx' -Copy ` 34 -VirtualMachinePath "$Dspath" -SnapshotFilePath "$Dspath" -SmartPagingFilePath "$Dspath" -VhdDestinationPath "$Dspath" -GenerateNewId 35 #重命名VM 36 $VM = Get-VM -Id $import.Id 37 $VM | Rename-VM -NewName $VMNAME 38 #启动VM 39 Start-VM -VM $VM 40 Start-Sleep -s 30 41 42 #重命名&加域 43 if (($ifdomain -eq "y") -or ($ifdomain -eq "Y")){ 44 Invoke-Command -VMId $VM.Id -ScriptBlock { 45 $admin = "admin" 46 $pwd = ConvertTo-SecureString "xxxxxxx" -AsPlainText -Force 47 $Cerd2 = New-Object System.Management.Automation.PSCredential($admin,$pwd); 48 Add-Computer -NewName "$using:VMNAME" -Credential $Cerd2 -DomainName icccuat.com -Restart 49 } -Credential $Cerd1 50 }else { 51 Invoke-Command -VMId $VM.Id -ScriptBlock { 52 Rename-Computer -NewName "$using:VMNAME" -Restart 53 } -Credential $Cerd1 54 } 55 56 57 Write-Host "导入成功"