Monday, July 9, 2012

PowerCLI snippets

Some PowerCLI snippets that I've used. Use with caution on a production system.
# Connect to multiple vCenters
Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Confirm:$false

# Add snap-in if required
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) {
    add-pssnapin VMware.VimAutomation.Core
}
else {
    Write-Host "Snap in already added."
}

Set-PowerCLIConfiguration -InvalidCertificateAction "Ignore" -Confirm:$false

# Connect to vCenter
Connect-VIServer 192.168.10.31 -User laura -Password xxxxxx

Get-VM | Get-View

# Get VM
$vmname="GoldenClient"
$vm = Get-VM $vmname | Get-View

# Get the guest IP address for one or more virtual machines
$vms = Get-VM -Name "vm-*"
foreach ($vm in $vms) {
  $name = $vm.Name
  $ip = $vm.Guest.IPAddress
  echo "Name: $name"
  echo "IP: $ip" 
}

# Get VM alarm state
foreach($state in $vm.DeclaredAlarmState){
    $alarm = Get-View $state.Alarm
    #Write-Host "name:"
    #Write-Host $alarm.info.name
    #Write-Host "overall status:"
    Write-Host $state.OverallStatus
}

# Get all VM's powered on named lnkc* (lnkc-1, lnkc-2, etc)
Get-VM -Name lnkc* | Where-Object{$_.PowerState -eq "PoweredOn"}

# Get count of all powered on VM's
$vms = Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"}
$vms.count

# Get count of all VM's
$vms = Get-VM
$vms.count

# Get all hosts
Get-Host 

# Remove from inventory and delete from disk
remove-vm -DeleteFromDisk:$true -RunAsync:$true -vm $vmName

# Shut down all powered on VM's gracefully
$clustername="rdc"
Get-Cluster -Name $clustername  | Get-VM | Where-Object{$_.PowerState -eq "PoweredOn"} | Shutdown-VMGuest -Confirm:$false

# Put all hosts in the cluster into maintenace mode
Get-Cluster -Name $clustername | Get-VMHost | Set-VMHost -State "Maintenance"

# Reboot all hosts
Get-Cluster -Name $clustername | Get-VMHost | Restart-VMHost -Confirm:$false

# Exit maintenance mode
Get-Cluster -Name $clustername | Get-VMHost | Set-VMHost -State "Connected"

# Power on a set of virtual machines
Get-Cluster -Name $clustername  | Get-VM -Name colo* | Start-VM

# Create port group on a specific VLAN
Get-Cluster -Name $clustername | Get-VMHost | Get-VirtualSwitch | New-VirtualPortGroup -name 'my-vlan' -VLanID 12

# Disconnect from vCenter
Disconnect-VIServer -Confirm:$false