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:



127.0.0.1;cjohannsen001;reserved
127.0.0.2;cjohannsen002;free
127.0.0.3;cjohannsen003;reserved
127.0.0.4;cjohannsen004;free
127.0.0.5;cjohannsen005;free
127.0.0.6;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"
$Lines[$i]
$bool = Read-Host "Use IP?"
if($bool -eq "yes"){
$Lines[$i] = $Lines[$i].Replace("free", "reserved")
$Lines | Set-Content -Path $file
echo "IP address:"
$ip
break
}
else{
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

    ReplyDelete