Powershell

Windows Server 8 PowerShell Cmdlets for Hyper-V help

In Windows 2008 & Windows R2 there were no official PowerShell Cmdlets available for Hyper-V. This is changed in Windows 8. Windows Server 8 has 162 PowerShell Cmdlets available for Hyper-V. Windows 8 uses PowerShell version 3.

Cmdlets are very powerful, that lets you automate all aspects of Hyper-V.  Here some guidance how-to find the Cmdlets you need.

 

To view all the Hyper-V PowerShell Cmdlets:

Get-Command -Module Hyper-V

To search for Cmdlets, for example with the name “host” in it: 

Get-Command -Module Hyper-V -Noun *host*

image

To get the Cmdlet syntax:

Get-VMHost -?

image

Get the Cmdlet syntax and available parameters, details and examples:

get-Help Get-VMHost -Full

image

More information over the Hyper-V Cmdlets can be found here. PowerShell 3.0 is available as Community Technology Preview (CTP) found here.

 

List VM settings to CSV, HTML, gridview, screen and email

 

This PowerCLI script will display specified VM settings for all VMs in the vCenter server you specify. If you do an inventory, a health check or need to troubleshoot VMware environment this PowerCLI script can be useful.

The following VM settings will be displayed:

VMName, Hostname, IP address, OS version, Boottime, VMstate, Total vCPUs, CPU afinnity, CPU hot add status, CPU share, CPU limit, Overall CPU usage, CPU reservation, Total memory, Memory share, Memory usage, Memory hot add status, Memory limit, Memory reservation, Memory swap, Memory ballooning, Memory compression, Total NICs, VMware tools status, VMware Tools version, VM hardware version, Timesync status and CBT status.

 

The output can be specified in the scripts. The following formats:

- CSV

- HTML

image

- GridView. The cool about gridview is that you can easily sort and filter columns.

2011-06-09 11h44_42

- On screen

- HTML file can be send by email.

Requirements:

- Microsoft Powershell v2.0

- VMware PowerCLI 4.1 U1 build 332441

What do I need to change:

The following variables can be changed to suit your needs:

001
002
003
004
005
006
007
008
009
010
011
012
013
# Variable to change
$CreateCSV= "yes"
$GridView = "yes"
$HTML = "yes"
$DisplayHTMLOnScreen = "yes"
$EmailHTML = "yes"
$SendEmail = "yes"
$EmailFrom = "vm@ivobeerens.nl"
$EmailTo = "info@ivobeerens.nl"
$EmailSubject = "VMs settings information"
$EmailSMTP = "smtpserver"
$FileHTML = New-Item -type file "D:\temp\VMInfo_$datefile.html"
$FileCSV = New-Item -type file "D:\temo\VMInfo_$datefile.csv"

 

The PowerCLI script listing:

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<#
.SYNOPSIS
Displays VM settings

.DESCRIPTION
Display VM settings by CSV, HTML, GridView, screen and as HTML by email
 
.Author(s)
Ivo Beerens www.ivobeerens.nl

.EXAMPLE
PS C:\> ./vminfo.ps1

#>

#Initialize PowerCLI
Add-PSSnapin VMware.VimAutomation.Core
C:\"Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1" 

#Connect to vCenter
$VCServer = Read-Host "Enter the vCenter server name"
$Username= Read-Host "Enter the username"
$Password = Read-Host "Enter password"
Connect-VIServer $VCServer -User $username -Password $password -port 443

#Variables
$Date = get-date
$Datefile = ( get-date ).ToString(‘yyyy-MM-dd-hhmmss’)
$ErrorActionPreference = "SilentlyContinue"
# Variable to change
$CreateCSV= "yes"
$GridView = "yes"
$HTML = "yes"
$DisplayHTMLOnScreen = "yes"
$EmailHTML = "yes"
$SendEmail = "yes"
$EmailFrom = "vm@ivobeerens.nl"
$EmailTo = "info@ivobeerens.nl"
$EmailSubject = "VMs settings information"
$EmailSMTP = "smtpserver"
$FileHTML = New-Item -type file "D:\temp\VMInfo_$datefile.html"
$FileCSV = New-Item -type file "D:\temo\VMInfo_$datefile.csv"

#Add Text to the HTML file
Function Create-HTMLTable
{
param([array]$Array)
$arrHTML = $Array | ConvertTo-Html
$arrHTML[-1] = $arrHTML[-1].ToString().Replace(‘</body></html>’,"")
Return $arrHTML[5..2000]
}

$output = @()
$output += ‘<html><head></head><body>’
$output += 
‘<style>table{border-style:solid;border-width:1px;font-size:8pt;background-color:#ccc;width:100%;}th{text-align:left;}td{background-color:#fff;width:20%;border-style:so
lid;border-width:1px;}body{font-family:verdana;font-size:12pt;}h1{font-size:12pt;}h2{font-size:10pt;}</style>’

$output += ‘<H1>VMware VM information</H1>’
$output += ‘<H2>Date and time</H2>’,$date

#Gathering VM settings
Write-Host "Gathering VM statistics"
$Report = @()
Get-VM | Sort Name -Descending | %

 {
 
 
$vm = Get-View $_.
ID
   
$vms = "" | Select-Object VMName, Hostname, IPAddress, OS, Boottime, VMState, TotalCPU, CPUAffinity, CPUHotAdd, CPUShare, CPUlimit, OverallCpuUsage, CPUreservation, TotalMemory, MemoryShare, MemoryUsage, MemoryHotAdd, MemoryLimit, MemoryReservation, Swapped, Ballooned, Compressed, TotalNics, ToolsStatus, ToolsVersion, HardwareVersion, TimeSync, CBT
    $vms.VMName = $vm.
Name
   
$vms.Hostname = $vm.guest.hostname
$vms.IPAddress = $vm.guest.ipAddress
$vms.OS = $vm.Config.GuestFullName
$vms.Boottime = $vm.Runtime.BootTime
$vms.VMState = $vm.summary.runtime.
powerState
   
$vms.TotalCPU = $vm.summary.config.
numcpu
   
$vms.CPUAffinity = $vm.Config.CpuAffinity
$vms.CPUHotAdd = $vm.Config.CpuHotAddEnabled
$vms.CPUShare = $vm.Config.CpuAllocation.Shares.Level
$vms.TotalMemory = $vm.summary.config.
memorysizemb
   
$vms.MemoryHotAdd = $vm.Config.MemoryHotAddEnabled
$vms.MemoryShare = $vm.Config.MemoryAllocation.Shares.Level
$vms.TotalNics = $vm.summary.config.numEthernetCards
$vms.OverallCpuUsage = $vm.summary.quickStats.
OverallCpuUsage
   
$vms.MemoryUsage = $vm.summary.quickStats.
guestMemoryUsage
   
$vms.ToolsStatus = $vm.guest.
toolsstatus
   
$vms.ToolsVersion = $vm.config.tools.toolsversion
$vms.TimeSync = $vm.Config.Tools.SyncTimeWithHost
$vms.HardwareVersion = $vm.config.
Version
   
$vms.MemoryLimit = $vm.resourceconfig.memoryallocation.
limit
   
$vms.MemoryReservation = $vm.resourceconfig.memoryallocation.
reservation
   
$vms.CPUreservation = $vm.resourceconfig.cpuallocation.
reservation
   
$vms.CPUlimit = $vm.resourceconfig.cpuallocation.limit
$vms.CBT = $vm.Config.ChangeTrackingEnabled
$vms.Swapped = $vm.Summary.QuickStats.SwappedMemory
$vms.Ballooned = $vm.Summary.QuickStats.BalloonedMemory
$vms.Compressed = $vm.Summary.QuickStats.CompressedMemory
$Report += $vms
}

#Output
if ($GridView -eq "yes") {
$report | Out-GridView }

if ($CreateCSV -eq "yes") {
$report | Export-Csv $FileCSV -NoTypeInformation }

if ($HTML -eq "yes") {
$output += ‘<p>’
$output += ‘<H2>VMware VM information</H2>’
$output += ‘<p>’
$output += Create-HTMLTable 
$report
$output
 += ‘</p>’
$output += ‘</body></html>’
$output | Out-File $FileHTML }

if ($DisplayHTMLOnScreen -eq "yes") {
ii $FileHTML}

if ($SendEmail -eq "yes") {
Send-MailMessage –From $EmailFrom –To $EmailTo –Subject $EmailSubject –SmtpServer $EmailSMTP -Attachments $FileHTML }

#Disconnect session from VC
Disconnect-VIserver -Confirm:$false

 

Download link

VMware ESX Post installation configuration via PowerCLI

 

    I made a simple example script using the VMware PowerCLI that can be used to do the post installation configuration of a VMware ESX 4 server. This script does the following things:

    • - Connect to VMware ESX server

    • - Set the SC memory to 800MB

    • - Creates vSwitch2 and add vmnic2 and vmnic3

    • - Add several PortGroups and VLANs to vSwitch2

    • - Remove default PortGroup VM Network

    • - Creates a VMkernel VMotion port with IP address, subnetmask and VLAN

    • - Add vmnic0 and vmnic1 to vSwitch0, set for the VMotion port vmnic1 active and vmnic0 standby and for the Service Console port vmnic0 active and vmnic1 standby

    • - Configure NTP servers and open the firewall

    • - Sets advanced settings Disk.UseDeviceReset to 0 and Disk.UseLUNReset  to 1

    • - Sets he Qlogic HBA queue depth and the Disk.SchedNumReqOutstandig to 64

    • - Enable VMhost Startup and stop

    Here’s the listing of the script:

    # Title: VMware ESX4 Post config #
    #
    Filename:    esx4postconfig.sp1 # 
    #
    Created by: Ivo Beerens #                                                      
    #
    Date: February 2010 #                                                            
    #
    Version: 1.0 #
    #
    Website: www.ivobeerens.nl #                                                        
    #
    E-mail: ivo[AT]ivobeerens.nl #                                                        

    # Variables #
    #
    vCenter name and port #
    $vcserver = "vc01"
    $portvc = "443"
    #Service Console memory #
    $SCMemory = 800
    # default PortGroup #
    $DefaultPG = Get-VirtualPortgroup -Name VM Network
    # VMotion IP, subnetmask and VLAN
    $VMotionIP = 172.16.1.50“
    $VMotionSubnet = “255.255.0.0“
    $VMotionVLan =
    "3"
    # HBA Queue depth #
    $HBAqueudepth = 64
    # vSwitch names #
    $Switch1 =
    "vSwitch0"
    $Switch2 =
    "vSwitch2"

    Connect-VIServer $vcserver -User root -Password idontknow -port $portvc

    # Set SC memory to 800MB #
    Get-VMHost | Get-View | %{(Get-View -Id $_.ConfigManager.MemoryManager).ReconfigureServiceConsoleReservation($SCMemory*1mb)}

    # Create vSwitch1 and add vmnic2 and vmnic3 #
    New-VirtualSwitch -Name $Switch2 -Nic vmnic2,vmnic3

    # Add PortGroups and VLANs  to the vSwitch2 #
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name"VLAN999 Management" -VLANID 999
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN100 Servers" -VLANID 100
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN99 Clients Ser-D" -VLANID 99
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN98 Clients Ser-B" -VLANID 98
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN33 Secure LAN" -VLANID 33
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN32 DMZ3" -VLANID 32
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN31 DMZ1" -VLANID 31
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN30 DMZ0" -VLANID 30
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN7 VOiP" -VLANID 7
    get-vmhost | Get-VirtualSwitch -Name $Switch2 | New-VirtualPortGroup -Name
    "VLAN1 Default"

    # Remove default Port Group after default installation #
    Remove-VirtualPortGroup -VirtualPortGroup $DefaultPG -Confirm:$false

    # Creates a VMkernel port VMotion on vSwitch0 #
    New-VMHostNetworkAdapter -PortGroup “VMotion“ -VirtualSwitch $Switch1 -IP $VMotionIP -SubnetMask $VMotionSubnet -VMotionEnabled:$true

    # Set VLAN of the VMotion VMkernel #
    $VMotionPG = Get-VirtualPortgroup -Name ‘VMotion’
    Set-VirtualPortGroup -VirtualPortGroup $VMotionPG -VlanId $VMotionVLan

    # Add vmnic0 and vmnic1 to vSwitch0 #
    $vs = get-virtualswitch -name $Switch0
    Set-VirtualSwitch -VirtualSwitch $vs -Nic vmnic0,vmnic1

    # Set VMotion vmnic1 active vmnic0 standby #
    get-virtualportgroup -name VMotion | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive vmnic1
    get-virtualportgroup -name VMotion | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicStandby vmnic0

    # Set Service Console vmnic0 active, vmnic1 standby #
    get-virtualportgroup -name ‘Service Console’ | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive vmnic0
    get-virtualportgroup -name ‘Service Console’ | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicStandby vmnic1

    # Configures NTP, add NTP servers, starts NTP and open the firewall port #
    Add-VmHostNtpServer -NtpServer "0.vmware.pool.ntp.org"
    Add-VmHostNtpServer -NtpServer
    "1.vmware.pool.ntp.org"
    Add-VmHostNtpServer -NtpServer
    "2.vmware.pool.ntp.org"
    Get-vmhostfirewallexception
    "NTP Client" | Set-VMHostFirewallException -enabled:$true

    # Advanced settings instellen #
    Set-VMHostAdvancedConfiguration -Name"Disk.UseDeviceReset" -Value 0
    Set-VMHostAdvancedConfiguration -Name
    "Disk.UseLunReset" -Value 1

    # Set the queuedepth for the Qlogic HBA and SchedNumReqOutstanding setting #
    Get-VMhostModule "qla2xxx" | Set-VMHostModule -Options"ql2xmaxqdepth=$HBAqueudepth"
    Set-VMHostAdvancedConfiguration -Name
    "Disk.SchedNumReqOutstanding" -Value $HBAqueudepth

    # Enable VMHostStartup #
    $VMstart = Get-VMHostStartPolicy
    Set-VMHostStartPolicy -VMHostStartPolicy $VMstart -Enabled:$true -StartDelay 60 -StopDelay 60 -StopAction GuestShutDown

    # Disconnect #
    disconnect-viserver -confirm:$false

    It’s easy to adjust the settings for your need. This shows the strength to use the PowerCLI for doing automation in VMware. If you have suggestions please let me know.

    Powershell Windows Eventlog script

    This week i found the report-events Powershell script (see figure 1). The script is made by Jeffrey Hicks. It generates a nice HTML file with errors and warnings from the Windows eventlog.

    image

    figure 1. Output reports-event script

    You can specify multiple servers in a text file, select how many hours from the current time to look in the eventlog and e-mail the HTML file after generation. 

    The following syntax can be used:

    get-content c:\script\servers.txt | c:\scripts\report-event.ps1 – report c:\script\eventlog.html –hours 48 –smtp mail.beerenss.nl –sendto eventlogs@beerens.nl –from eventlog@beerens.nl

    Explanation:

    get-content c:\script\servers.txt, text file containing the server names

    – report c:\script\eventlog.html, name of the HTML file

    | c:\scripts\report-event.ps1, call the actually script

    –hours 48, hours to report from the curren time

    –smtp mail.beerens.nl. SMTP server to sent the HTML rapport 

    –sendto ivo@beerens.nl, To address

    –from eventlog@beerens.nl . from address

     

    Schedule this script to run frequently to watch your eventlogs!

     

    Download the script here.

     

    Winners VI toolkit scripting contest

    The winners of the VI toolkit scripting contest are announced:

    - The first prize goes to LucD for his Guest Provisioning System script.

    - The Second prize goes to tzamora for his VMware Infrastructure Power Documenter script.

    - The Third prize goes to Dan Baskette with his PowerVDI script.

    The Healthcheck script that i created has not won :-(

    You can read the rest @ the VMware Powershell Blog

    For all VI toolkit contributions check this link