One of my friend asked for a PowerShell script for Nutanix Windows virtual machine cloning and configuration. This PowerShell script automates the process of cloning virtual machines and joining them to a domain. It uses the Nutanix PowerShell module to interact with the Nutanix cluster and clone virtual machines.
In short what does this script do?
This script reads a CSV file containing the source VM names, new VM names, IP addresses, and other configuration details. It clones each source VM using the Nutanix PowerShell module. After cloning, it powers on the new VM and waits for it to become available. The script then configures the new VM's network settings using an unattend.xml file. It joins the new VM to the domain using a PowerShell script. Finally, the script cleans up temporary files and logs the results.
Download this complete script bundle Nutanix windows vm clone zip here | It is also available on github.com.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
#Import-Module Nutanix.Cli -Prefix Ntnx #Import-Module Nutanix.Prism.Common -Prefix Ntnx #Import-Module Nutanix.Prism.PS.Cmds -Prefix Ntnx #Import-Module Posh-SSH $prism = '192.168.34.101' $userName = 'admin' $password = 'Computer@123' $csvFile = 'WINDOWS-inputparameters.csv' $prismSecureString = ConvertTo-SecureString -String $password -Force -AsPlainText $domainUserName = 'vjanvi' $domainPassword = 'Computer@123' $sourceVMUsername = 'administrator' $sourceVMPassword = 'Computer@123' $vmSecureString = ConvertTo-SecureString -String $sourceVMPassword -Force -AsPlainText $vmCredential = [System.Management.Automation.PSCredential]::new($sourceVMUsername,$vmSecureString) function Show-ProgressInfo { [CmdletBinding()] param ( [int] $totalSeconds = 360 ) $updateIntervalSeconds = 1 # spinner refresh $progressIntervalSeconds = 60 # 1 minute per progress update $spinner = @('/', '|', '-', '\') $spinnerIndex = 0 $startTime = Get-Date $endTime = $startTime.AddSeconds($totalSeconds) while ((Get-Date) -lt $endTime) { $elapsedSeconds = (Get-Date) - $startTime $elapsedSeconds = [int]$elapsedSeconds.TotalSeconds # Calculate progress in minutes $progressPercent = [math]::Min( [math]::Floor(($elapsedSeconds / $totalSeconds) * 100), 100 ) $elapsedMinutes = [math]::Floor($elapsedSeconds / 60) $spinChar = $spinner[$spinnerIndex % $spinner.Count] $spinnerIndex++ Write-Host -NoNewline "`r$spinChar Running... $elapsedMinutes minute(s) elapsed | Progress: $progressPercent%" Start-Sleep -Seconds $updateIntervalSeconds } Write-Host "`r✔ Completed: 6 minutes elapsed | Progress: 100% } $ntnxConnection = Connect-NTNXCluster -Server $prism -UserName $userName -Password $prismSecureString -AcceptInvalidSSLCerts -ForcedConnection #Connect-NutanixV3PrismServer #Disconnect-NutanixV3PrismServer Connect-NtnxPrismCentral Write-Host "$((Get-Date).DateTime) | Server: $($ntnxConnection.Server) | IsConnected: $($ntnxConnection.IsConnected) | UserName: $($ntnxConnection.UserName)" $currentPath = $PSScriptRoot $csvInfo = Import-Csv -Path $currentPath\$csvFile foreach ($row in $csvInfo) { $sourceVMName = $row.SourceVMName $sourceVM = Get-NTNXVM | Where-Object {$_.vmName -eq $sourceVMName } $newVMName = $row.NewVMName Write-Host "$((Get-Date).DateTime) | SourceVM: $sourceVMName | isFound: Yes" $cloneSpec = New-NTNXObject -Name VMCloneSpecDTO $cloneSpec.name = $newVMName Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | isCloning: Yes" Clone-NTNXVirtualMachine -vmId $sourceVM.VmId -SpecList $cloneSpec | Out-Null $cloneTask = Get-NTNXTask | Where-Object {($_.operationType -match 'VmClone|SnapshotCreate') -or ($_.progressStatus -eq 'VmClone')} While ($cloneTask) { Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | OperationType: $($cloneTask.operationType[0]) | ProgressStatus: $($cloneTask.progressStatus[0])" $cloneTask = Get-NTNXTask | Where-Object {($_.operationType -match 'VmClone|SnapshotCreate') -or ($_.progressStatus -eq 'VmClone')} #$cloneTask | Select-Object operationType, progressStatus Start-Sleep -Seconds 10 } Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | isCloned: Yes" #Write-Host "PowerOn VM: $newVMName" $createdVM = Get-NTNXVM | Where-Object {$_.vmName -eq $newVMName } $powerOnTask = Set-NTNXVMPowerOn -VmId $createdVM.vmId While (Test-Connection -ComputerName $row.SourceVMIP -Count 1 -Quiet ) { #$powerOnTask Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | isPoweredOn: Running" Start-Sleep -Seconds 15 } Start-Sleep -Seconds 10 Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | isPoweredOn: Completed" Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | PrepareUnattend: Running" $unattendEntries = @{ HOSTNAME = $row.NewVMName #'ritesh1' ETHCONTROLLERNAME = $row.SourceVMEthName #'Ethernet' IPV4ADDRESSLASHSSUBNET = "$($row.NewVMIP)/$($row.NewVMSubnet)" #'172.17.218.168/22' IPV4GATEWAY = $row.NewVMGateway #'172.17.216.1' ADMINUSERNAME = $sourceVMUsername ADMINPASSWORD = $sourceVMPassword } if (Test-Path -Path $currentPath\suppliments\unattend.xml) { Remove-Item -Path $currentPath\suppliments\unattend.xml -Force } $unattend = Get-Content $currentPath\suppliments\template-unattend.xml foreach ($entry in $unattendEntries.keys) { $unattend = $unattend.Replace($entry, $unattendEntries[$entry]) } $unattend | Out-File -FilePath $currentPath\suppliments\unattend.xml -Encoding utf8 Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | PrepareUnattend: Completed" Start-Sleep -Seconds 90 try { Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | OpenSession: Running | RemoteCommand: Running" $oldIPSession = New-PSSession -ComputerName $row.SourceVMIP -Credential $vmCredential -ErrorAction Stop $initialConf = Invoke-Command -Session $oldIPSession -ScriptBlock { if (-not (Test-Path -Path C:\Temp)) { New-Item -Path C:\ -Name Temp -ItemType Directory -Force } New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -PropertyType String -Name LegalNoticeCaption -Value '' -Force New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -PropertyType String -Name LegalNoticeText -Value '' -Force #reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v LegalNoticeCaption /t REG_SZ /d "" #reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v LegalNoticeText /t REG_SZ /d "" } $initialConf | Out-Null #| Select-Object PSComputerName, PSPath Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | OpenSession: Completed | RemoteCommand: Completed" } catch { Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | OpenSession: Failed | RemoteCommand: Failed" } Start-Sleep -Seconds 15 Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | OpenRDP: Running" cmdkey /generic:$($row.SourceVMIP) /user:$sourceVMUsername /pass:$sourceVMPassword #to support rdp without certificate warning #HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client >> New DWORD (32-bit) >> Value Name AuthenticationLevelOverride >> Value data to 0 (zero) mstsc /v:$($row.SourceVMIP) Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | OpenRDP: Completed" Start-Sleep -Seconds 30 Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | UnattendPushed: Running" Copy-Item -Path $currentPath\suppliments\unattend.xml -Destination C:\Temp -ToSession $oldIPSession Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | UnattendPushed: Completed | BatchPushed: Running | LoggedInUserFound: Running" try { $remoteLoggedInUsers = Invoke-Command -Session $oldIPSession -ScriptBlock { 'C:\Windows\System32\Sysprep\Sysprep.exe /generalize /reboot /oobe /unattend:C:\Temp\unattend.xml' > C:\Temp\generalize.bat quser } -ErrorAction Stop $loggedInUserId = ($remoteLoggedInUsers[1] -Split '\s+')[3] Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | BatchPushed: Yes | LoggedInUserFound: Yes" } catch { Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | LoggedInUserFound: No" -BackgroundColor DarkRed return } Write-Host "$((Get-Date).DateTime) | ClonedNewVM: $newVMName | Sysprep: Running" #PsExec.exe \\$($oldIPSession.ComputerName) -u Administrator -p 's#rT9012' -accepteula -nobanner -i 1 -d -c -f $currentPath\suppliments\generalize.bat PsExec.exe \\$($oldIPSession.ComputerName) -u $sourceVMUsername -p $sourceVMPassword -accepteula -nobanner -n 120 -i $loggedInUserId -c -f $currentPath\suppliments\generalize.bat #Start-Sleep -Seconds 360 Show-ProgressInfo -totalSeconds 360 Write-Host "$((Get-Date).DateTime) | PreparedNewVM: $newVMName | Sysprep: Completed" Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | PingTest: Running" if (Test-Connection -ComputerName $row.SourceVMIP -Quiet -Count 1) { Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | Source IP $($row.SourceVMIP) still reachable ... halting" -BackgroundColor DarkRed return } if (Test-Connection -ComputerName $row.NewVMIP -Quiet -Count 2) { Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | New IP $($row.SourceVMIP) reachable" } else { Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | New IP $($row.SourceVMIP) unreachable ... halting" -BackgroundColor DarkRed return } Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | PingTest: Completed" Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | PrepareDominJoinScript: Running" "`$userName = '$domainUsername'" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" "`$password = '$domainPassword'" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "# create secure string from plain-text string" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "`$secureString = ConvertTo-SecureString -AsPlainText -Force -String `$password" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "# convert secure string to encrypted string (for safe-ish storage to config/file/etc.)" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "`$encryptedString = ConvertFrom-SecureString -SecureString `$secureString" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "# convert encrypted string back to secure string" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "`$secureString = ConvertTo-SecureString -String `$encryptedString" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "# use secure string to create credential object" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "`$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList `$userName,`$secureString" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append "Add-Computer -DomainName vcloud-lab.com -Credential `$credential #-Restart -Force" | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append '$error[0].Exception.Message | Out-File -FilePath c:\temp\errors.log' | Out-File -FilePath "$currentPath\suppliments\Join-Domain.ps1" -Append Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | PrepareDominJoinScript: Completed" Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | OpenNewSession: Running | CopyFileRemotely: Running" $newIPSession = New-PSSession -ComputerName $row.NewVMIP -Credential $vmCredential -ErrorAction Stop $newVMDetails = Copy-Item -Path $currentPath\suppliments\Join-Domain.ps1 -Destination C:\Temp -ToSession $newIPSession Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | OpenNewSession: Completed | CopyFileRemotely: Completed" Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | RemoteDomainJoin: Running" $domainJoin = Invoke-Command -Session $newIPSession -ScriptBlock { & 'C:\temp\Join-Domain.ps1' Restart-Computer -Force } $domainJoin | Out-Null #Restart-Computer -ComputerName $row.NewVMIP -Credential $vmCredential -Force Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | RemoteDomainJoin: Completed | Cleanup: Running" cmdkey /delete:$($row.SourceVMIP) try { Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | RemoteCleanup: Running" #$newIPSession = New-PSSession -ComputerName $row.NewVMIP -Credential $vmCredential -ErrorAction Stop $cleanup = Invoke-Command -Session $newIPSession -ScriptBlock { Remove-Item -Path C:\Temp\* -Recurse -Force } $cleanup | Out-Null } catch { Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | OpenNewSession: Failed | RemoteCommand: Failed" } Write-Host "$((Get-Date).DateTime) | NewVM: $newVMName | Cleanup: Completed" } |
Related Article: Automating Linux VM Cloning and IP Configuration on Nutanix with PowerShell
This script automates the cloning and domain joining process, saves time and reduces manual errors. Uses PowerShell to interact with the Nutanix cluster and virtual machines.
Configures network settings and joins the domain using a script, ensuring consistency and reliability.
Below are the requirement:
Nutanix PowerShell module installed and configured. It can be download from prism central portal.
CSV file containing the source VM names, new VM names, IP addresses, and other configuration details.
Unattend.xml file template for configuring network settings.
PowerShell script for joining the domain.

Below is unattend.xml example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
<?xml version="1.0" encoding="utf-8"?> <unattend xmlns="urn:schemas-microsoft-com:unattend"> <settings pass="windowsPE"> <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SetupUILanguage> <UILanguage>en-US</UILanguage> </SetupUILanguage> <InputLocale>en-US</InputLocale> <SystemLocale>en-US</SystemLocale> <UILanguage>en-US</UILanguage> <UserLocale>en-US</UserLocale> </component> </settings> <settings pass="specialize"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <ComputerName>HOSTNAME</ComputerName> </component> <component name="Microsoft-Windows-TCPIP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Interfaces> <Interface wcm:action="add"> <Identifier>ETHCONTROLLERNAME</Identifier> <Ipv4Settings> <DhcpEnabled>false</DhcpEnabled> </Ipv4Settings> <UnicastIpAddresses> <IpAddress wcm:action="add" wcm:keyValue="1">IPV4ADDRESSLASHSSUBNET</IpAddress> </UnicastIpAddresses> <Routes> <Route wcm:action="add"> <Identifier>1</Identifier> <Prefix>0.0.0.0/0</Prefix> <NextHopAddress>IPV4GATEWAY</NextHopAddress> </Route> </Routes> </Interface> </Interfaces> </component> <component name="Microsoft-Windows-DNS-Client" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Interfaces> <Interface wcm:action="add"> <Identifier>ETHCONTROLLERNAME</Identifier> <DNSServerSearchOrder> <IpAddress wcm:action="add" wcm:keyValue="1">192.168.34.11</IpAddress> <IpAddress wcm:action="add" wcm:keyValue="2">192.168.34.12</IpAddress> </DNSServerSearchOrder> <EnableAdapterDomainNameRegistration>true</EnableAdapterDomainNameRegistration> <DisableDynamicUpdate>false</DisableDynamicUpdate> </Interface> </Interfaces> </component> <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <RunSynchronous> <RunSynchronousCommand wcm:action="add"> <Order>1</Order> <Description>Remove Legal Caption</Description> <Path>reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v LegalNoticeCaption /t REG_SZ /d "" /f</Path> </RunSynchronousCommand> <RunSynchronousCommand wcm:action="add"> <Order>2</Order> <Description>Remove Legal Text</Description> <Path>reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v LegalNoticeText /t REG_SZ /d "" /f</Path> </RunSynchronousCommand> </RunSynchronous> </component> </settings> <settings pass="oobeSystem"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <AutoLogon> <Password> <Value>ADMINPASSWORD</Value> <PlainText>true</PlainText> </Password> <Enabled>true</Enabled> <LogonCount>1</LogonCount> <Username>ADMINUSERNAME</Username> </AutoLogon> <UserAccounts> <AdministratorPassword> <Value>ADMINPASSWORD</Value> <PlainText>true</PlainText> </AdministratorPassword> </UserAccounts> <OOBE> <HideEULAPage>true</HideEULAPage> <HideLocalAccountScreen>true</HideLocalAccountScreen> <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen> <HideOnlineAccountScreens>true</HideOnlineAccountScreens> <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> <ProtectYourPC>1</ProtectYourPC> </OOBE> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <InputLocale>en-US</InputLocale> <SystemLocale>en-US</SystemLocale> <UILanguage>en-US</UILanguage> <UserLocale>en-US</UserLocale> </component> </settings> </unattend> |
Useful Articles
How to join vCenter Server appliance to Active Directory
Add a vCenter Single Sign On Identity Source Active Directory (Windows Integrated Authentication)
Configure vCenter SSO Active Directory (Integrated Windows Authentication) as identity source
PASSED VMWARE CERTIFIED PROFESSIONAL 6 - DATA CENTER VIRTULIZATION DELTA EXAM (VCP6-DCV, 2V0-621D)
UPGRADING FROM VMWARE VCENTER 6.0 TO 6.5 PROCEDURE AND VSPHERE HTML5 WEB CLIENT
Part 1 - Copy or clone distributed virtual switch portgroups to standard switch portgroups - Powercli
Migrating move back from Distributed virtual switch to Standard virtual switch - VMKernal Adapter - Part 2
Migrating move back from Distributed virtual switch to Standard virtual switch - VMs (Virtual Machine) - Part 3
Part 4: Remove ESXi Host from Distributed switch and migrate to virtual switch completely

