PowerShell批量部署Hyper-V Windows虛機

來源:互聯網
上載者:User

標籤:powershell vm scvmm hyper-v

第一步:製作模板VHDX檔案(略);第二步:製作初始化系統指令碼(自動化佈建IP、GW等);將以下2個指令碼放置到模板VHDX中的C:\Windows\Setup\Scripts目錄下:第1個指令碼:FirstRun.ps1#擷取電腦名稱$VMname=hostname#根據電腦名稱擷取IP地址後6位[int]$IP1=$VMname.Substring($VMname.Length - 6,3)[int]$IP2=$VMname.Substring($VMname.Length - 3,3)#設定FSNNetwork$IPaddr1=$IPaddr1=‘172.1.‘ + $IP1 + ‘.‘ + $IP2New-NetIPAddress -InterfaceIndex 12 -IPAddress $IPaddr1 -PrefixLength 16 -DefaultGateway 172.1.0.250Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses ("172.1.0.1","172.1.0.2")exit第2個指令碼:SetupComplete.cmd (該指令碼名稱必須為SetupComplete)Powershell -Command "C:\Windows\Setup\Scripts\‘FirstRun.ps1‘"timeout 3gpupdate /forcecd  C:\Windows\System32wuauclt.exe /DetectNow /UpdateNow::cd  C:\FalconAgent::falcon-agent.exe -service install::sc.exe config  falconagent Start=delayed-auto::falcon-agent.exe -service startdel C:\Windows\Setup\Scripts\FirstRun.ps1del %0第三步:建立自動化部署指令碼# ================================ ##    Create-VM_V1.0(Windows).PS1   #   #   通過PowerShell建立Hyper-V虛機  #  # ================================ ##Param($VM_Name,$VM_HostName)Write-Host -NoNewline -ForegroundColor Magenta ‘請輸入要建立的虛機名稱(如:VWSR******)‘[String]$VM_Name = Read-HostWrite-Host -NoNewline -ForegroundColor Magenta ‘請輸入需要放在哪台宿主機上(如:PWSR******)‘[String]$VM_HostName= Read-HostWrite-Host -NoNewline -ForegroundColor Magenta ‘要部署App Server還是SQL Server?預設App Server斷行符號即可(如:sql 斷行符號或者2 斷行符號)‘[String]$VM_OSClass= Read-Host#判斷虛機名稱是否為大寫字母if ($VM_Name |findstr ‘vwsr‘)   { Write-Host -NoNewline -ForegroundColor Yellow ‘注意:虛機名需要使用大寫字母!!!‘     break } Else   { }   $VM_Memory= 4GB$VM_CpuCount= 4$Owner= "IT"$Org= "sxleilong.com"$NetworkSwitch= "FSNNetwork"#$AdminPassword = "Administrator Password"$SourcePath= "D:\VM_Deploy_Script"$DjoinSource= $SourcePath + ‘\‘ + $VM_Name +‘.txt‘#if判斷要部署App Server還是SQL Server,預設是App Serverif (($VM_OSClass -eq ‘2‘) -or ($VM_OSClass -eq ‘sql‘) -or ($VM_OSClass -eq ‘SQL‘))   {$Template_VHDX= $SourcePath + ‘\‘ + ‘En_WinSrv12R2_For_SQL.vhdx‘    Write-Host -ForegroundColor Green "您選擇安裝SQL虛機!!!"    }Else   {$Template_VHDX= $SourcePath + ‘\‘ + ‘En_WinSrv12R2_For_APP.vhdx‘    Write-Host -ForegroundColor Green "您選擇安裝App虛機!!!"    }#if判斷如果虛機所在宿主機為管理系,虛機檔案存放位置為E盤  if (( $VM_HostName -eq ‘PWSR252001‘ ) -or ($VM_HostName -eq ‘PWSR252002‘ ))   { $VM_Path = ‘E:\‘ + $VM_HostName + ‘_E_VMs‘     $VM_RemotePath = ‘\\‘ + $VM_HostName + ‘\E$\‘ + $VM_HostName + ‘_E_VMs‘ }Else   { $VM_Path = ‘D:\‘ + $VM_HostName + ‘_D_VMs‘     $VM_RemotePath = ‘\\‘ + $VM_HostName + ‘\D$\‘ + $VM_HostName + ‘_D_VMs‘ } $VM_VHDPath = $VM_Path + ‘\‘ + $VM_Name + ‘\Virtual Hard Disks\‘+ $VM_Name + ‘.vhdx‘$VM_VHDRemotePath = $VM_RemotePath + ‘\‘ + $VM_Name + ‘\Virtual Hard Disks\‘ + $VM_Name + ‘.vhdx‘#if判斷是否為0系管理伺服器,用以自動加入不同OUif ($VM_Name |findstr ‘VWSR000‘)   { $VM_MachineOU= "OU=MgmtServers,OU=sxleilong,DC=sxleilong,DC=cn" }Else   { $VM_MachineOU= "OU=NewInfra,OU=Production Servers,OU=sxleilong,DC=sxleilong,DC=cn" }#編輯應答檔案模板$UnattendTemplate= "Unattend-template.xml"$Unattendfile= New-Object XML$Unattendfile.Load($SourcePath+"\"+$UnattendTemplate)$Unattendfile.unattend.settings.component[2].ComputerName=$VM_Name$Unattendfile.unattend.settings.component[2].RegisteredOrganization=$Org$Unattendfile.unattend.settings.component[2].RegisteredOwner=$Owner$Unattendfile.unattend.settings.Component[3].RegisteredOrganization=$Org$Unattendfile.unattend.settings.Component[3].RegisteredOwner=$Owner#$UnattendFile.unattend.settings.component[3].UserAccounts.AdministratorPassword.Value=$AdminPassword#$UnattendFile.unattend.settings.component[3].autologon.password.value=$AdminPassword$UnattendXML=$SourcePath+"\"+$VM_Name+".xml"$Unattendfile.save($UnattendXML)#Mount模板VHDXMount-diskimage $Template_VHDX$DriveLetter=((Get-DiskImage $Template_VHDX | get-disk | get-partition | Where-Object Type -eq "Basic").DriveLetter)+":"#注入Unattend.xml檔案到VHDX中$UnattendXml_Destination=$Driveletter+"\Windows\System32\Sysprep\unattend.xml"Copy-Item $UnattendXml $UnattendXml_Destination -Force#產生Offline JoinDomain檔案Djoin /Provision /Domain sxleilong.com /Machine $VM_Name /MachineOU $VM_MachineOU /Savefile $DjoinSource /Reuse#注入Offline JoinDomain檔案,並移除曆史DjoinFile$DjoinDestination= $Driveletter+‘\Windows‘$His_DjoinFile= $DjoinDestination +‘\‘+‘VWSR*.txt‘Remove-Item -Path $His_DjoinFile -ForceCopy-Item $DjoinSource  $DjoinDestination -ForceDjoin /RequestODJ /Loadfile  "$VM_Name.txt" /WindowsPath $DjoinDestination /LocalOS#注入開機運行指令碼$ScriptFolder=$DriveLetter+"\Windows\Setup\Scripts\"$Scriptname=$Scriptfolder+"FirstRun.ps1"If (Test-Path $ScriptFolder)   {}Else   {    New-Item $ScriptFolder -ItemType Directory    Copy-Item "$SourcePath\Scripts\*" $ScriptFolder -Force   }#DisMount模板VHDXdismount-diskimage $Template_VHDX#Remove應答檔案和Djoin檔案Remove-Item -Path $DjoinSourceRemove-Item -Path $UnattendXml#Copy虛擬機器VHDX檔案New-item -path $VM_RemotePath\$VM_Name -name "Virtual Hard Disks" -ItemType directoryCopy-Item -Path $Template_VHDX -Destination $VM_VHDRemotePath#建立虛機New-VM –Name $VM_Name -ComputerName $VM_HostName –Generation 2 -MemoryStartupBytes $VM_Memory -SwitchName $NetworkSwitch –Path $VM_Path -VHDPath $VM_VHDPath#設定CPU個數Set-VM -Name $VM_Name -ComputerName $VM_HostName -ProcessorCount $VM_CpuCount#禁用動態記憶體功能#Set-VMMemory -Name $VM_Name -ComputerName $VM_HostName -DynamicMemoryEnabled $False  #添加DVDDriveGet-VM -Name $VM_Name -ComputerName $VM_HostName |Add-VMDvdDrive -ControllerNumber 0#設定VLANID#Set-VMNetworkAdapterVlan -ComputerName $VM_HostName -VMName $VM_Name -Access -VlanId 1112#通過SCVMM分配靜態MACAddress#Import-Module virtualmachinemanagerRead-SCVMHost -VMHost $VM_HostName |Out-Null$VM=Get-SCVirtualMachine -Name $VM_Name$Adapter=$VM.VirtualNetworkAdapters[0]Set-SCVirtualNetworkAdapter -VirtualNetworkAdapter $Adapter[0] -MACAddressType "Static" -MACAddress "00-00-00-00-00-00" |Out-Null#啟動虛機#Start-VM -Name $VM_Name -ComputerName $VM_HostNameStart-SCVirtualMachine -VM $VM_Name

本文出自 “Ray” 部落格,請務必保留此出處http://sxleilong.blog.51cto.com/5022169/1916614

PowerShell批量部署Hyper-V Windows虛機

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.