Friday, June 28, 2013

Vsphere PowerShell Script (1) - Update Network Adapter

This is a powershell script that help you to update the Network Adapter for the virtual machine in ESXi.

You can save this moveNet.ps1 and you will need to login to the ESXi server or your Vcenter before you can run this script.

The script basically help you to update the NetworkAdapter attribute of the Virtual machine using the Set-NetworkAdapter function.

In order to ensure the virtual machine get a new ip address after the network is changed, we put in some check to determine if the machine is powered on. If that's online, we will do ipconfig /release before updating the networkadapter and do an ipconfig /renew after that.

To use this script, in the PowerCli windows, after you connect to your ESXi or VCenter, you should run

./moveNet.ps1 -vmname VM123 -newnetwork VLAN1 -administrator Administrator -password password

Please refer to the detail and modify that to suit your environment!!

----start of moveNet.ps1-----

Param($vmname, $newnetwork, $administrator, $password)

$VM = Get-VM -Name $vmname
if ($vm.powerstate -eq "PoweredOff") {
Get-VM -Name $vmname | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $newnetwork -confirm:$false
}

if ($vm.powerstate -eq "PoweredOn") {
Invoke-VMScript "ipconfig /release" -vm $VM -GuestUser $administrator -GuestPassword $password -ScriptType "bat"
Get-VM -Name $vmname | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $newnetwork -confirm:$false
Invoke-VMScript "ipconfig /renew" -vm $VM -GuestUser $administrator -GuestPassword $password -ScriptType "bat"
}

-----end of script-----

No comments:

Post a Comment