Tuesday, July 24, 2012

PowerCLI - IP reservation with PowerShell

Sometimes I receive questions which aren´t exactly my skill. In this case I was asked for a "IP management" from a .csv/.txt file to receive an IP address and reserve it. The IP address should be used for a vCloud Director vApp deployment. As a google junkie i searched for a ready-to-use solution but there wasn´t any.

So i decide to build a small script and a text file to play around with. The text file (ip_names.txt) only has three informations, comma separated:

ip address; dns name; state

and looks like this:;cjohannsen001;reserved;cjohannsen002;free;cjohannsen003;reserved;cjohannsen004;free;cjohannsen005;free;cjohannsen006;reserved

The goal was to select an ip address and if the address is chosen it should be reserved by changing the state keyword.

After a few attempts I figure out the following script:

$file = "ip_names.txt"
$Lines = Get-Content -path $file -readcount 0

For($i=0; $i -lt $Lines.Count; $i+=1){

$ip = $Lines[$i].ToString().Split(';')[0].Trim() 
$dns = $Lines[$i].ToString().Split(';')[1].Trim() 
$state = $Lines[$i].ToString().Split(';')[2].Trim() 
    if ($state –eq 'free') {
echo $ip "... is free"
$bool = Read-Host "Use IP?"
if($bool -eq "yes"){
$Lines[$i] = $Lines[$i].Replace("free", "reserved")
$Lines | Set-Content -Path $file
echo "IP address:"
echo "IP wasn´t chosen."

With this small script you will be able to "select" an IP address ;)

1 comment:

  1. Virtualization is running multiple virtual computers on one physical box. Ilabs Technology Solutions has certified Engineers and a virtualization solution provider .It provides Desktop, Server and Application Virtualization Services very effectively.Virtualization Technology