Stage 1 shutdown for UPS, the vm’s we don’t care about

Stage 1, shutdown down vm’s we don’t care about
[powershell]
add-pssnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue
Connect-VIServer vcenter.www.alanrocks.com
#stage 1, shutdown or stop vm’s not on this list
$vmsilike = "dc1","vcenter","VPNstuff","quickbooks","dc2","files","wordpress-win","exchange2010","sharepoint","sql"
$vmson = (get-vm | where {$_.powerstate -eq "PoweredOn"})
$dievms = ($vmson -like $vmsilike)
foreach ($vmso in $vmson){if ($vmsilike -notcontains $vmso.Name){
# debug Write-Host $vmso.name "shut this bitch down"}}
$fvm = Get-VM $vmso
#findtoolsver
$toolver = (get-vm $fvm |% {get-View $_.id} | select @{Name="toolsver"; expression={$_.config.tools.toolsversion}})
if ($toolver.toolsver -gt 10000){$fvm | Stop-VM -Confirm:$false}
if ($toolver.toolsver -le 10000){$fvm | Shutdown-VMGuest -Confirm:$false}
}}
[/powershell]

Find all ver and build hosts

[powershell]
Get-View -ViewType HostSystem | Select Name, @{N="Version";E={$_.Summary.Config.Product.FullName}}
[/powershell]

Where { $_.Version -match “ESXi”}

add for only esx

Mass Migrate Port Groups

get-cluster HQ | get-vm | Get-NetworkAdapter | Where{$_.NetworkName -eq “Server”} | Set-NetworkAdapter -networkname “Server_192.168.11.X” -confirm:$false

copy templates!

[powershell]
Connect-VIServer *
$st = nas
$fold = "Nas_Templates"
$datasto = "z) nasvm01*"
$ho = "nasvm01*"

$spec = New-Object VMware.Vim.VirtualMachineCloneSpec

$folder = (Get-Folder $fold | Get-View)
$data = (Get-Datastore $datasto | Get-View)
$hos = (Get-VMHost $ho | get-view)

#$folder = New-Object VMware.Vim.ManagedObjectReference
#$folder.type = "Folder"
#$folder.value = "group-v12744"

$spec.location = New-Object VMware.Vim.VirtualMachineRelocateSpec
$spec.location.datastore = New-Object VMware.Vim.ManagedObjectReference
$spec.location.datastore.type = "Datastore"
$spec.location.datastore.value = $data.moref.value
$spec.location.host = New-Object VMware.Vim.ManagedObjectReference
$spec.location.host.type = "HostSystem"
$spec.location.host.value = $hos.moref.value
$spec.location.transform = "sparse"
$spec.template = $true
$spec.powerOn = $false

$_this = Get-View -Id ‘VirtualMachine-vm-12257’
$_this.CloneVM_Task($folder.moref, "_nas_template_2008_STD32", $spec)

$_this = Get-View -Id ‘VirtualMachine-vm-12259’
$_this.CloneVM_Task($folder.moref, "_nas_template_2003_STD32", $spec)

$_this = Get-View -Id ‘VirtualMachine-vm-12348’
$_this.CloneVM_Task($folder.moref, "_nas_template_2008R2_STD", $spec)

$_this = Get-View -Id ‘VirtualMachine-vm-12697’
$_this.CloneVM_Task($folder.moref, "_nas_template_2008_STD64", $spec)
[/powershell]

Memory Ballons

$myCol = @()
foreach($vm in (Get-View -ViewType VirtualMachine | Where-Object `
{$_.Summary.QuickStats.BalloonedMemory -ne “0”})){
$Details = “” | Select-Object VM, `
SwappedMemory ,BalloonedMemory

$Details.VM = $vm.Name
$Details.SwappedMemory = $vm.Summary.QuickStats.SwappedMemory
$Details.BalloonedMemory = $vm.Summary.QuickStats.BalloonedMemory

$myCol += $Details
}
$myCol

[powershell]
$myCol = @()
foreach($vm in (Get-View -ViewType VirtualMachine | Where-Object `
{$_.Summary.QuickStats.BalloonedMemory -ne "0"})){
$Details = "" | Select-Object VM, `
SwappedMemory ,BalloonedMemory

$Details.VM = $vm.Name
$Details.SwappedMemory = $vm.Summary.QuickStats.SwappedMemory
$Details.BalloonedMemory = $vm.Summary.QuickStats.BalloonedMemory

$myCol += $Details
}
$myCol
[/powershell]

find stupid 100 meg links

Get-VMHost | Get-VMHostNetworkAdapter | where {$_.BitRatePerSec -eq “100”} | fl VMhost,BitRatePerSec,DeviceName

[powershell]
Get-VMHost | Get-VMHostNetworkAdapter | where {$_.BitRatePerSec -eq "100"} | fl VMhost,BitRatePerSec,DeviceName
[/powershell]

Copy vSwitches and Portgroups to everybody in a cluster (like a boss)

Does just what it says, set up one host, and copys everything to the rest of the host, helps me set stuff up faster 🙂

#alan harrington, copy networking one host to another.
Connect-VIServer vcenter.www.alanrocks.com
$src = Read-Host "Please enter the golden host for networking: "
$destclu = Read-Host "Please enter the name of the cluster to copy too: "
foreach ($dest in (get-cluster $destclu | Get-VMHost)){

$desthost = Get-VMhost $dest
get-vmhost $src | Get-VirtualPortGroup | select VirtualSwitchName,Name,VLanId | export-csv c:\hostnetworking.txt -NoTypeInformation
$infohizzle = import-csv c:\hostnetworking.txt | where-object {$_.name -notmatch "vmotion" -and $_.name -notmatch "VMkernel" -and $_.name -notmatch "Service" -and $_.name -notmatch "Management Network"}

$infohizzle | % {
$Vportgrp = $_.Name
$vswitch = $_.VirtualSwitchName
$vlan = $_.VlanId

If (($desthost |Get-Virtualportgroup -Name $Vportgrp -ErrorAction SilentlyContinue)-eq $null){
if (($desthost |Get-VirtualSwitch -Name $vswitch -ErrorAction SilentlyContinue)-eq $null){$desthost | New-VirtualSwitch -Name $vswitch}
$desthost | Get-VirtualSwitch -Name $vswitch | New-VirtualPortGroup -ErrorAction "SilentlyContinue" -Name $Vportgrp -VLanId $vlan}}}

Finding stuff in all the cool datastores you never knew you had (or that you knew you had, you just really didn’t want to click alot)

Lucd has been my number one source of scripts for pretty much like ever. He is always willing to helping out in the community, uber smart and knows his stuff. I often will use his scripts to start and do something else with them, mostly because I don’t know how, and I am lazy. his most awesome script was something that i started to do, and did back in bash in the good ol esx days, since esx pretty much is dead (it’s about freaking time), i needed to convert it PS to make it work, but low and behold, he already did it.

Here. Raiders of the lost VMX

These things are amazing for scripting DR when the client just isn’t big enough to justify SRM

Anywho how this started is I recently had a client’s site the VDR appliance blow up and start making snapshot files with failing the snapshot, since it failed it never removed the vmsn files, and it was only on a few particular datastores. I am not gonna name names, but I’m 99% sure it had to do with the buggy 5.0.1 equallogic firmware and its Atomic Lock and Set, but now that that is fixed its pretty freaking awesome.
so with the permission of LucD himself, here is the modified script to look for vmsn files plus all the other cool stuff it could do beforehand!

without more delay, here it is!
[powershell]
function Register-VMX {
param($entityName = $null,$dsNames = $null,$template = $false,$ignore = $null,$checkNFS = $false,$whatif=$false,$snapshot = $false)

function Get-Usage{
Write-Host "Parameters incorrect" -ForegroundColor red
Write-Host "Register-VMX -entityName -dsNames [,…]"
Write-Host "entityName : a cluster-, datacenter or ESX hostname"
Write-Host "dsNames : one or more datastorename names"
Write-Host "ignore : names of folders that shouldn’t be checked"
Write-Host "template : register guests ($false)or templates ($true) – default : $false"
Write-Host "checkNFS : include NFS datastores – default : $false"
Write-Host "whatif : when $true will only list and not execute – default : $false"
Write-Host "snapshot : finds vmsn files if set to ($true) – default : $false"
}

if($entityName -ne $null -and $dsNames -ne $null){
Get-Usage
exit
}

if($dsNames -eq $null){
switch((Get-Inventory -Name $entityName).GetType().Name.Replace("Wrapper","")){
"Cluster"{
$dsNames = Get-Cluster -Name $entityName | Get-VMHost | Get-Datastore | where {$_.Type -eq "VMFS" -or $checkNFS} | % {$_.Name}
}
"Datacenter"{
$dsNames = Get-Datacenter -Name $entityName | Get-Datastore | where {$_.Type -eq "VMFS" -or $checkNFS} | % {$_.Name}
}
"VMHost"{
$dsNames = Get-VMHost -Name $entityName | Get-Datastore | where {$_.Type -eq "VMFS" -or $checkNFS} | % {$_.Name}
}
Default{
Get-Usage
exit
}
}
}
else{
$dsNames = Get-Datastore -Name $dsNames | where {$_.Type -eq "VMFS" -or $checkNFS} | % {$_.Name}
}

$dsNames = $dsNames | Sort-Object
$pattern = "*.vmx"
if($template){
$pattern = "*.vmtx"
}
if($snapshot){
$pattern = "*.vmsn"
}

foreach($dsName in $dsNames){
Write-Host "Checking " -NoNewline; Write-Host -ForegroundColor red -BackgroundColor yellow $dsName
$ds = Get-Datastore $dsName | Get-View
$dsBrowser = Get-View $ds.Browser
$dc = Get-View $ds.Parent
while($dc.MoRef.Type -ne "Datacenter"){
$dc = Get-View $dc.Parent
}
$tgtfolder = Get-View $dc.VmFolder
$esx = Get-View $ds.Host[0].Key
$pool = Get-View (Get-View $esx.Parent).ResourcePool

$vms = @()
foreach($vmImpl in $ds.Vm){
$vm = Get-View $vmImpl
$vms += $vm.Config.Files.VmPathName
}
$datastorepath = "[" + $ds.Name + "]"

$searchspec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
$searchspec.MatchPattern = $pattern

$taskMoRef = $dsBrowser.SearchDatastoreSubFolders_Task($datastorePath, $searchSpec)

$task = Get-View $taskMoRef
while ("running","queued" -contains $task.Info.State){
$task.UpdateViewData("Info.State")
}
$task.UpdateViewData("Info.Result")
foreach ($folder in $task.Info.Result){
if(!($ignore -and (&{$res = $false; $folder.FolderPath.Split("]")[1].Trim(" /").Split("/") | %{$res = $res -or ($ignore -contains $_)}; $res}))){
$found = $FALSE
if($folder.file -ne $null){
foreach($vmx in $vms){
if(($folder.FolderPath + $folder.File[0].Path) -eq $vmx){
$found = $TRUE
}
}
if (-not $found){
if($folder.FolderPath[-1] -ne "/"){$folder.FolderPath += "/"}
$vmx = $folder.FolderPath + $folder.File[0].Path
if($snapshot){
Write-Host "`t" $vmx
write-host " Snapshot file found" -ForegroundColor blue -BackgroundColor white
}
if($template){
$params = @($vmx,$null,$true,$null,$esx.MoRef)
}
else{
$params = @($vmx,$null,$false,$pool.MoRef,$null)
}
if((!$whatif) -and (!$snapshot)){
$taskMoRef = $tgtfolder.GetType().GetMethod("RegisterVM_Task").Invoke($tgtfolder, $params)
Write-Host "`t" $vmx "registered"
}
elseif($whatif){
Write-Host "`t" $vmx "registered" -NoNewline; Write-Host -ForegroundColor blue -BackgroundColor white " ==> What If"
}
}
}
}
}
Write-Host "Done"
}
}

# Register-VMX -entityName "MyDatacenter" -snapshot:$true
# Register-VMX -entityName "MyDatacenter"
# Register-VMX -dsNames "datastore1","datastore2"
# Register-VMX -dsNames "datastore1","datastore2" -template:$true
# Register-VMX -entityName "MyDatacenter" -ignore "SomeFolder"
# Register-VMX -dsNames "datastore3","datastore4" -ignore "SomeFolder" -checkNFS:$true
# Register-VMX -entityName "MyDatacenter" -whatif:$true
[/powershell]

One Liners, We All Love Them

CD-Rom
Finds all the vm’s with a cd-rom connected and disconnects them

[powershell]
Get-VM | Where-Object {$_ | Get-CDDrive | Where-Object { $_.ConnectionState.Connected -eq "true" } } | Get-CDDrive | Set-CDDrive -Connected $false -Confirm:$false[/powershell]

Mark the vm’s starting with zT as a template*
[powershell]
foreach ($d in (get-vm zT*)){$vm2 = Get-VM $d | Get-View; $vm2.MarkAsTemplate()}
[/powershell]

Deletes all Snapshots over 2 days old
[powershell]foreach ($snap in (Get-VM | get-snapshot)){if ($snap.Created -lt (Get-Date).AddDays(-2)){Remove-Snapshot $snap -Confirm:false}}[/powershell]

Connects all VM’s with a certain name to the same iso

[powershell]
get-datacenter dc | get-cluster cl | get-vm 2008* | get-cddrive | set-cddrive -IsoPath "[Datastore Name] -isoname.iso" -Connected:$true -Confirm:$false[/powershell]

Let’s Find the HAL level for vm’s

[powershell]
Get-VM |Where {$_.PowerState -eq “PoweredOn“} |Sort Name |Select Name, NumCPU, @{N=“OSHAL“;E={(Get-WmiObject -ComputerName $_.Name-Query “SELECT * FROM Win32_PnPEntity where ClassGuid = ‘{4D36E966-E325-11CE-BFC1-08002BE10318}’“ |Select Name).Name}}, @{N=“OperatingSystem“;E={(Get-WmiObject -ComputerName $_ -Class Win32_OperatingSystem |Select Caption).Caption}}, @{N=“ServicePack“;E={(Get-WmiObject -ComputerName $_ -Class Win32_OperatingSystem |Select CSDVersion).CSDVersion}}
[/powershell]

VMHost
Disable vMotion All the host in a cluster

[powershell]
get-datacenter DC | get-cluster CL | get-vmhost | set-vmhostadvancedconfiguration -Name Migrate.Enabled -Value 0
[/powershell]