scripts.team-holm.net
Hovedsiden
PowerShell Scripts
VMWare



GetvCenterServiceRuntime.ps1
#Atle Holm - 2013
#Lists the amount of time the vCenter service has been running.
#NB! Use this on a server with a vCenter service! :)

New-TimeSpan -Start (get-process vpxd).StartTime

Find Windows Guests.ps1
#Atle Holm - 2013
#Lists all guests with Windows OS

$vms = Get-VM | ?{$_.PowerState -eq "PoweredOn"}
foreach($vm in $vms) {
   Get-WmiObject -ComputerName $vm.Name Win32_OperatingSystem -EA SilentlyContinue `
   | Select-Object @{Name="ComputerName"; Expression={$vm.Name}}
}

Add-Disk.ps1
#Atle Holm - 2013
#Add Disk to VM
$vCenterHost = "xx.xx.xx.xx"
$vCenterUser = "lab\Administrator"
$vCenterPass = "xxxxxxx" 
$vmcluster = "CLUSTER 1"

$vmname = "PLATINUM"
$disk1 = "100"
$disk2 = ""
$Disks = @()
if($disk1.compareTo("0") -eq 0) { $disk1 = ""}
if($disk2.compareTo("0") -eq 0) { $disk2 = ""}
if($disk1 -and $disk2) {
   $Disks = @($disk1,$disk2)
}elseif($disk1 -and !$disk2) {
   $Disks = @($disk1)
}elseif(!$disk1 -and $disk2) {
   $Disks = @($disk2)
}   
$DiskStorageFormat = "Thin"
$datastorecluster = ""
$ErrorID = 0

if(-not (Get-PSSnapin VMware.VimAutomation.Core)) { 
    Add-PSSnapin VMware.VimAutomation.Core 
} 

Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -confirm:$false
Connect-VIServer -Server $vCenterHost -User $vCenterUser -Password $vCenterPass

$vmname = $vmname.toUpper()

try {
      $name = ((Get-VM $vmname).name).toUpper()
}catch{
   $ErrorID = "1"
   throw "ERROR: 100 Server not found" 
}

$datastorecluster = $datastorecluster.toUpper()

switch ($datastorecluster) { 
   "DatastoreCluster_xx" {   
      "Det er valgt et annet datastore"
           
      }    
   default { 
      "Default datastore er valgt"
      $datastorecluster = "DatastoreCluster_01"
   }
}
try {
   foreach ($nSize in $Disks) {
      Get-VM $vmname | New-HardDisk -DiskType flat -CapacityGB $nSize `
         -StorageFormat $DiskStorageFormat -Datastore $datastorecluster    
   }
} catch {
   $ErrorID = "2"
   throw "ERROR: 2 Could not add one or more disks to $vmname" 
}

Set-VLAN.ps1
#Atle holm - 2013
#Set VLAN on an existing VM guest
$vCenterHost = "xx.xx.xx.xx"
$vCenterUser = "lab\Administrator"
$vCenterPass = "xxxxxxx" 
$vmcluster = "CLUSTER 1"

$vmname = "PLATINUM"
$newNetworkName = "VLAN 123"
$ErrorID = 0

if(-not (Get-PSSnapin VMware.VimAutomation.Core)) { 
    Add-PSSnapin VMware.VimAutomation.Core 
} 

Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -confirm:$false
Connect-VIServer -Server $vCenterHost -User $vCenterUser -Password $vCenterPass

$vmname = $vmname.toUpper()

try {
      $name = ((Get-VM $vmname).name).toUpper()
} catch {
   $ErrorID = "1"
   throw "ERROR: 100 Server not found" 
}

try {
   get-vm $vmname | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $newNetworkName -Confirm:$false
} catch {
   $ErrorID = "2"
   throw "ERROR: 200 Could not set VLAN on server"
}

Delete VM.ps1
#Atle Holm - 2013
#1. Sletter VM.

$vCenterHost = "xx.xx.xx.xx"
$vCenterUser = "lab\Administrator"
$vCenterPass = "xxxxxxx" 

$ErrorID = "0"

$vmname = "PLATINUM"

if(-not (Get-PSSnapin VMware.VimAutomation.Core 2> $NULL)) { 
    Add-PSSnapin VMware.VimAutomation.Core 
} 

Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -confirm:$false
Connect-VIServer -Server $vCenterHost -User $vCenterUser -Password $vCenterPass

$vmname = $vmname.toUpper()

try {
      $name = ((Get-VM $vmname).name).toUpper() 2> $NULL
} catch {

}

if ($name -ne $vmname) { 
   $ErrorID = "1"
   throw "ERROR: 1 Did not find a server with that name" 
}

"Shutting down $vmname"
$vmobj = Get-VM $vmname
try {
   Shutdown-VMGuest $vmobj -Confirm:$false
   while (((Get-VM $vmname).PowerState).ToString().ToLower().compareTo(("PoweredOff").ToLower()) -ne 0) {
      "Waiting for VM to enter a powered off state before we delete it.."
      Start-Sleep -s 15
      if(((Get-VM $vmname).PowerState).ToString().ToLower().compareTo(("PoweredOff").ToLower()) -eq 0) { 
         "Deleting $vmname"
         Remove-VM $vmobj -DeletePermanently -Confirm:$false 
         exit 0
      }
   }
} catch {
   $ErrorID = "3"
   throw "ERROR: 2 Was not able to shut down and/or delete VM" 
}

ListVMInfo.ps1
#Atle Holm - 2013
# Lists comma separated information about all vms 
# starting with a ceratin name. Replace "namestart" below for the start of the name you want to search for.

if(-not (Get-PSSnapin VMware.VimAutomation.Core 2> $NULL)) { 
   Add-PSSnapin VMware.VimAutomation.Core 
} 
Connect-VIServer localhost #localhost is the vcenter in this case

get-vm namestart* | %{
   $name = $_.name
   $mem = $_.MemoryMB 
   $nCPU = $_.NumCpu
   $diskCapacities = $_.HardDisks | %{$_.CapacityKB/1024}
   $outputString = "$name, #CPU: $nCPU, Memory: $mem MB"
   $x = 0;
   foreach ($d in $diskCapacities) {
      $x++;
      $outputString = $($outputString + ", Disk" + $x + ": " + $d + "MB")
   }
   $x = 0;
   foreach($ip in $_.Guest.IPAddress) {
      $x++;
      $outputString = $($outputString + ", IP" + $x + ": "+$ip)
   } 
   Write-Output $outputString
}

Create VM.ps1
#Atle Holm - 2013
#1. Oppretter VM og plasserer i default plasseringer.
#2. Returmerer IP-adressen på server.
#3. Sette expiry date på server i notes field.

$vCenterHost = "xx.xx.xx.xx"
$vCenterUser = "lab\Administrator"
$vCenterPass = "xxxxxxx" 

$vmcluster = ""
$datastorecluster = ""
$ErrorID = 0

$vmname = "Platinum"
$NumCpu = "2"
$MemoryGB = "2"
$DiskStorageFormat = "Thin"
#win2003 | win2008
$osversion = "WIN2008"

if(-not (Get-PSSnapin VMware.VimAutomation.Core 2> $NULL)) { 
   Add-PSSnapin VMware.VimAutomation.Core 
} 

Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -confirm:$false
Connect-VIServer -Server $vCenterHost -User $vCenterUser -Password $vCenterPass

$vmname = $vmname.toUpper()
$vmname = "LAB-$vmname"

try {
   $name = ((Get-VM $vmname).name).toUpper() 2> $NULL
}catch{

}

if ($name -eq $vmname) { 
   $ErrorID = "1"
   throw "ERROR: 1 A server already exists with the same name" 
}

$osversion = $osversion.toUpper()

switch ($osversion) { 
   "WIN2012" {   "OS velges: Windows 2012"
      $OSCustomizationSpec = "W2K12-CUSTOMIZATION"
      $vmtemplate = "win2012_template"
   } 
   "WIN2008" {   "OS velges: Windows 2008"
      $OSCustomizationSpec = "W2K8-CUSTOMIZATION"
      $vmtemplate = "W2K8-MAL"
   }         
   default { 
      $ErrorID = "2"
      throw "ERROR: 2 Unknown OS version chosen" 
   }
}
$vmcluster = $vmcluster.toUpper()
switch ($vmcluster) { 
   "HOSTECluster_xx" {   
      "Annet VM cluster valgt"              
   }        
   default { 
      "Default VM Cluster velges"
      $vmcluster = "CLUSTER 1"
   }
}

$datastorecluster = $datastorecluster.toUpper()

switch ($datastorecluster) { 
   "DatastoreCluster_xx" {   
      "Annet datastore valgt"              
   }         
   default { 
      "Default Datastore velges"
      $datastorecluster = "DatastoreCluster_01"
   }
}
$expiryDate = (Get-Date).AddDays(60)
Get-Cluster $vmcluster | New-VM -Name $vmname -OSCustomizationSpec $OSCustomizationSpec -DiskStorageFormat `
$DiskStorageFormat -Template $vmtemplate -Datastore $datastorecluster
Get-VM $vmname | Set-VM -NumCpu $NumCpu -MemoryGB $MemoryGB -Notes `
"Expires: $expiryDate - NB! Removing this text will automatically expire your VM!" -confirm:$false
Get-VM $vmname | Start-VM


while ($guestIpAddress -eq $NULL) {
   "Waiting for server to get an IP address from DHCP..."
   Start-Sleep -s 15
   $guestIpAddress = (get-vm $vmname).guest.IPAddress[0]
}
"Servers IP-adresse er: $guestIpAddress"

Remove Unity From VMWare Tools.ps1
#Atle Holm - 2013
# This script fixes error messages found in the event viewer 
# described in http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2038263
# Run the script against desired computers
[cmdletbinding()]
param(
   [parameter(Mandatory=$true)]
   $ComputerName=$env:COMPUTERNAME)
$service = Get-WmiObject -ComputerName $ComputerName -Class Win32_Service -Filter "Name='VMTools'"
$service.stopservice()
Start-Sleep -s 10
$Processes = Get-WmiObject -Class Win32_Process -ComputerName $ComputerName -Filter "name='vmtoolsd.exe'"
if($Processes) {
  foreach ($process in $processes) {
    $processid = $process.handle
    $processcreationtime = $Process.Converttodatetime($Process.creationdate)
    write-host "`nThe vmtoolsd.exe `($processid`) process creation time is $processcreationtime"
   $returnval = $process.terminate()
   if($returnval.returnvalue -eq 0) {
      write-host "`n`tThe process vmtoolsd.exe `($processid`) terminated successfully"
   } else {
      write-host "`n`tThe process vmtoolsd.exe `($processid`) termination has some problems"
   }
  }
} else {
  write-host "`nNo Process found with name vmtoolsd.exe"
}
Start-Sleep -s 12
$file = "\\$ComputerName\c$\Program Files\VMware\VMware Tools\plugins\vmusr\Unity.dll" 
write-host "`nEvaluating $file"
if (test-path $file) {
   write-host "`n$ComputerName: File exists" 
   Remove-Item $file -force 
   write-host "`n$ComputerName: File is deleted" 
} else {
   write-host "`n$ComputerName File does not exist" 
   write-host "`n`tNot touching any files.."
}
 $service.startservice()

DisconnectIdleSessions.ps1
#Atle Holm - 2013
#Disconnect all users that have been idle more then 300 minutes / 5 hours

if(-not (Get-PSSnapin VMware.VimAutomation.Core 2> $NULL)) { 
   Add-PSSnapin VMware.VimAutomation.Core 
} 
Connect-VIServer localhost #localhost is the vcenter
Get-ViSession | Where {$_.IdleMinutes -gt 300 -and $_.FullName.Trim().ToString().ToLower() -ne "excludeUserName1Here" `
-and $_.FullName.Trim().ToString().ToLower() -ne "excludeUserName2Here"} | Disconnect-VISession

GetUsersVDIMachine.ps1
#Atle Holm - 2013
# CMDlets used here are available and installed on the VDI View Manager Server in your environment.
# These examples will get the name of the users VDI machine that he is assigned(1), 
# and reset a users VDI machine based on the users logon name(2).

import-module PowershellServiceCmdlets
 
Write-Output "Enter user name: "
$username = Read-Host

#(1)
Write-Host "Getting VDI name for user $username"
Get-RemoteSession -username domain\$username | %{Write-host @("`nUsers vm is named: " + (($_.DNSName).split(".")[0]) + "`n")}
 
Write-Host "Press enter to continue:"
Read-Host

#(2)
Write-Host "Resetting the VDI VM for user $username"
Get-RemoteSession -username domain\$username | %{Get-DesktopVM -name (($_.DNSName).split(".")[0])} | send-vmreset

Perl
VisualBasic
BASH
Powershell