Virtu-Al.Net

Virtually everything is poshable

PowerCLI: Changing a VM IP Address with Invoke-VMScript

One of the cmdlets that has been much improved in the recent version of PowerCLU 4 U1 is the Invoke-VMScript cmdlet,

This cmdlet runs a script or command inside the guest OS of each of the specified virtual machines. To run Invoke-VMScript, the user must have read access to the folder containing the virtual machine and a Virtual Machine.Interaction.Console Interaction privilege.

The virtual machines must be powered on and have PowerShell and VMware Tools installed.

Network connectivity to the ESX system hosting the virtual machine on port 902 must be present.

You must also have both the Host and guest credentials available.

One question asked of me recently was “Is there a way to set the IP address of some windows virtual machines with PowerCI ?”.

So with the power of the invoke-cmdlet in the following example you can see how you can change the ip address by using the netsh command inside the VM.

As a note, you no longer need PowerShell inside the guest OS for this cmdlet to work, as you can see below I am calling a batch command, you can also use this cmdlet against *nix machines to run shell commands.

This of course can easily be adjusted to read all ip addresses from a csv file or text file and apply them to multiple virtual machines if needed.

The script is as follows:

Function Set-WinVMIP ($VM, $HC, $GC, $IP, $SNM, $GW){
 $netsh = "c:\windows\system32\netsh.exe interface ip set address ""Local Area Connection"" static $IP $SNM $GW 1"
 Write-Host "Setting IP address for $VM..."
 Invoke-VMScript -VM $VM -HostCredential $HC -GuestCredential $GC -ScriptType bat -ScriptText $netsh
 Write-Host "Setting IP address completed."
}

Connect-VIServer MYvCenter

$VM = Get-VM ( Read-Host "Enter VM name" )
$ESXHost = $VM | Get-VMHost
$HostCred = $Host.UI.PromptForCredential("Please enter credentials", "Enter ESX host credentials for $ESXHost", "root", "")
$GuestCred = $Host.UI.PromptForCredential("Please enter credentials", "Enter Guest credentials for $VM", "", "")

$IP = "192.168.0.81"
$SNM = "255.255.255.0"
$GW = "192.168.0.1"

Set-WinVMIP $VM $HostCred $GuestCred $IP $SNM $GW

And to see it in action I shot a quick video of the script in action:

PowerCLI Invoke-VMScript cmdlet from Alan Renouf on Vimeo.

Further examples of this cmdlet can be found in Arnim’s great example here:

http://www.van-lieshout.com/2010/01/powercli-get-wmi-info-from-isolated-guests/

And  Arne’s great script here:

http://ict-freak.nl/2010/01/20/update-linux-vms-with-powercli-thanks-to-invoke-vmscript/

, ,

11 Responses to “PowerCLI: Changing a VM IP Address with Invoke-VMScript”

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>