Usefull PowerCLI scripts

Last couple of days i have been making some small but very usefull “scripts” to perform some tedious tasks where i did not feel like clicking in the GUI to make it all happen.

Chapter 1 : Check MAC to find VM’s

I think the title says it all, simple import of csv file with mac addresses (dont forget to start line 1 with “mac”) and then loop through the list to find the corresponding vm. If you connect multiple vcenters it will check all of them. Also it will output the findings to a txt file!

$maclist = Import-Csv -Path "D:\maclist.csv" -Delimiter ";"
$output = ForEach ($mac in $maclist){
    Get-VM | Get-NetworkAdapter | Where {$_.MacAddress -eq $mac.mac} | Select-Object Parent,Name,MacAddress,Uid
$output | Out-File -FilePath "D:\mac-vms.txt"

Chapter 2 : Set Custom Attribute for Hosts

The simplest one, get hosts of a certain cluster and loop through them to set the Datacenter value. You can use this to set any value ofcourse.

$allhosts = get-cluster "clustername" | get-vmhost
foreach ($hostname in $allhosts){
    Set-Annotation -Entity $hostname -CustomAttribute Datacenter -Value Datacenter1

Chapter 3 : Create standard vSwitch on multiple hosts

This one creates a standard switch on whatever hosts you need it to, just edit the $firsthosts variable to accomodate your needs and rename the switch… or not :). Then it will import a CSV file with portgroup names and vlan numbers and loops through each portgroup to check if it exists and creates it if needed with a second loop inside it to loop through the hosts. underneath the code is a sample of a csv you need to supply.

#Create Standard vSwitch
$firsthosts = get-cluster cluster1*,cluster2*,cluster3*,cluster4* | Get-VMHost | Where {$_.Name -like "*name*"}
foreach ($node in $firsthosts){
    New-VirtualSwitch -VMHost $node -Name "StagingSwitch"

#Import Portgroup Table
$portgroups = Import-Csv -Path "D:\localpgs.csv" -Delimiter ";"

#Create all Portgroups from Table $portgroups
$firsthosts = get-cluster cluster1*,cluster2*,cluster3*,cluster4* | Get-VMHost | Where {$_.Name -like "*name*"}
foreach ($portgroup in $portgroups){
    foreach ($node in $firsthosts){
        if (Get-VMHost $node | Get-VirtualSwitch -Standard -Name "StagingSwitch" | Get-VirtualPortGroup | Where-Object {$_.Name -eq $portgroup.Name}){
            Write-Host Portgroup $portgroup.Name already exists on $node! -ForegroundColor Cyan
        } else {
            Get-VMHost $node | Get-VirtualSwitch -Standard -Name "StagingSwitch" | New-VirtualPortGroup -Name $portgroup.Name -VLanId $portgroup.VlanNumber | Out-Null
            Write-Host Portgroup $portgroup.Name Created on $node! -ForegroundColor Green

Leave a Reply