Quickly import template Hyper-V machine

Main features: its own Hyper-V manually import too much trouble, wrote the script quickly import templates make good machine, quickly rename its virtual machine name and Hostname, according to the needs of whether to raise domain.

Templates machine OS: Windows Server 2019 

powershell: PS5.1

1  # February 12, 2020 16:22:52 
2  # introduced Hyper-v virtual machine 
. 3  [CmdletBinding ()]
 . 4  param (
 . 5      [the Parameter (
 . 6          ValueFromPipelineByPropertyName = $ to true ,
 . 7          ValueFromPipeline = $ to true ,
 . 8          Mandatory = $ to true )]
 . 9      [String] $ VMNAME ,
 10      [the Parameter (
 . 11          Mandatory = $ to true ,
 12 is          HelpMessage = " whether to join the AD " 
13 is     )]
 14      [The ValidateSet ( " the Y " , " N " , " Y " , " n- " )]
 15      [String] $ ifdomain 
16  )
 . 17  
18 is  # Select Template 
. 19  
20 is  # import a virtual machine as administrator 
21 is  $ administraotr = " . \ Administrator " 
22  $ pwd = the ConvertTo-SecureString " xxxxxx " -AsPlainText - Force 
 23  $ Cerd1New Object-System.Management.Automation.PSCredential = ( $ administraotr , $ pwd )
 24  # introduced AD admin status 
25  
26 is  # Check whether the same name 
27  the while (GET-VM -Name $ VMNAME ) {
 28      $ VMNAME = the Read-the Host   " virtual machine the same name, a computer name, please re-enter "  
29  }
 30  # the VM path 
31 is  $ DSPath = " F.: \ the Hyper \ $ VMNAME " 
32  # import the VM 
33 is  $ 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 is  
57 is the Write-the Host " Import successful "

 


 

Guess you like

Origin www.cnblogs.com/gui-junhua/p/12339777.html