Powershell is powerful (random MAC Address)

I've been to a few Microsoft conferences where people contantly bang on about PowerShell. Until now its been something I have tried to avoid, as it looks a little bit too much like DOS for my liking!

However, working on another project has lead me to look into powershell for creating Virtual Machines, and I've been blown away by what it can do.

The beauty of MS System Centre Products is that they all execute tasks using powershell, even if you use an admin console to create the task. You could quite happily never know that powershell was being used, and I imagine 90% of users never need to know. The brilliant thing is tha whenever you do something with the GUI, be it create a user in Exchange 2007 or deploy a Virtual Machine, a powershell script is generated, which you can use, reuse and tweek for your own requirments.

In my case I used it as a foundation for provisioning new VMs in Virtual Machine Manager 2007. Having created a VM Template (by sys-preping an XP install), I've been able to write a script which using one command can create a new VM, name it, install all our core software, generate a mac address & network card and join the domain!

I've spent the last 2 days trying to come up with a random MAC address generator in powershell, which I'm pasting below. It works a treat, and I'll be posting the full script (including the VM provisioning script) over the next couple of weeks. This random MAC generator is extreamly useful when wanting to give users the ability to create VMs on the fly, and after a lot of digging online I wasnt able to find anything like this...so hopefuly someone else can use it;

----------------------------------------------------------
param(
[int] $len = 12,
[string] $chars = "0123456789abcdef"
)


$bytes = new-object "System.Byte[]" $len

$rnd = new-object System.Security.Cryptography.RNGCryptoServiceProvider
$rnd.GetBytes($bytes)

#define the fields
$macraw = ""

for( $i=0; $i -lt $len; $i++ )
{
$macraw += $chars[ $bytes[$i] % $chars.Length ]
}

#add collons to the random macraw so that it is properly formatted
$macaddress = $macraw[0]+$macraw[1]+":"+$macraw[2]+$macraw[3]+":"+$macraw[4]+$macraw[5]+":"+$macraw[6]+$macraw[7]+":"+$macraw[8]+$macraw[9]+":"+$macraw[10]+$macraw[11]

$macaddress

----------------------------------------------------------

0 comments: