Tuesday, June 9, 2015

Rename interfaces based on IP range with Invoke-VMScript

Invoke-VMScript is a lifesaver if you need to do things inside a VM, and you don't want to spend hours logging on to each machine.

Here I needed to rename multiple network interface labels based on IP range:

$renamescript = @'

$adapter1 = Get-NetAdapter | Get-NetIPAddress |where IPaddress -Like "10.168.73.*"| Select interfacealias

$adapter2 = Get-NetAdapter | Get-NetIPAddress |where IPaddress -Like "192.168.72.*"| Select interfacealias

'@

Rename-NetAdapter -Name $adapter1.interfacealias -NewName "Frontend Network"

Rename-NetAdapter -Name $adapter2.interfacealias -NewName "Backend Network"


For each machine you can then do:

Invoke-VMScript -VM $hostname -GuestUser administrator -GuestPassword P4ssw0rd -ScriptText $renamescript

Combine this with the CSV file post I made before, and you can start your script, get a cup of whatever, and have Powershell do the hard work for you.

Reading in a CSV file in Powershell

CSV files make my life a whole lot easier, especially with large numbers. If you have an excel file with a hostname and an IP address, you get a csvfile like:

Server,IPAddress
server1,192.168.1.10
server2,192.168.1.11


You can import it with the following statement:

$csvfile = Import-Csv C:\Book2.csv

foreach ($value in $csvfile){

$hostname = $value.server

$IP = $value.IPAddress

Write-Host "do whatever here to $hostname with IP address: $IP"

}