G-regL
6/21/2017 - 4:27 PM

MOD - Lints Functions - VMware - Hosts

MOD - Lints Functions - VMware - Hosts

#####################################################################################################################################
#                                                                                                                                   #
#                                                                                                                                   #
#                   VMware - VMHost                                                                                                 #
#                                                                                                                                   #
#                                                                                                                                   #
#####################################################################################################################################

# Set some new VI properties that we need
$null = New-VIProperty -Name "RuntimeName2" -ObjectType "ScsiLun" -Value {
	param($scsilun)
	$storDev = $scsilun.VMHost.ExtensionData.Config.StorageDevice
	$key = ($storDev.PlugStoreTopology.Device | where {$_.Lun -eq $scsilun.Key}).Key
	$stordev.PlugStoreTopology.Path | where {$_.Device -eq $key} | %{
		$device = $_
		$adapterKey = ($stordev.PlugStoreTopology.Adapter | where {$_.Key -eq $device.Adapter}).Adapter
		$adapter = ($stordev.HostBusAdapter | where {$_.Key -eq $adapterKey}).Device
		$adapter + ":C" + $device.ChannelNumber + ":T" + $device.TargetNumber + ":L" + $device.LunNumber
	}
} -Force -WarningAction Ignore

#Function Global:Lints-VMHost-Attach-Disk{
#   [CmdletBinding()]
#   param(
#       [Parameter(Mandatory=$true,
#       ValueFromPipeline=$True,
#       ValueFromPipelineByPropertyName=$true)]
#       [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$VMHosts,
#
#       [string]$CanonicalName
#   )
#
#   Process { 
#       foreach ($h in $hosts) {
#           $storSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem
#           $lun = $storsys.storagedeviceinfo.scsilun | ? CanonicalName -eq $CanonicalName
#           $lunUuid = $lun.Uuid
#           $lunDisplayName = $lun.DisplayName
#           Write-Host "Attaching LUN $CanonicalName ($lunDisplayName) on $h"
#           #$storSys.AttachScsiLun($lunUuid)
#       }
#   }
#}

function Global:Lints-VMHost-Detach-Disk{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$true)]
        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl]$VMHosts,

        [string]$CanonicalName
    )
    Begin {
        $VMHosts = $VMHosts | Sort
    }

    Process { 
        foreach ($h in $VMHosts) {
            $storSys = Get-View $h.Extensiondata.ConfigManager.StorageSystem
            $lun = $storsys.storagedeviceinfo.scsilun | ? CanonicalName -eq $CanonicalName
            if ($lun -and $lun.OperationalState -eq "ok") {
                $lunUuid = $lun.Uuid
                $lunDisplayName = $lun.DisplayName
                $lunID = [int](get-SCSILUN -CanonicalName $CanonicalName -VmHost $h | Select-String ":L(?<lunID>\d+)$" -inputObject {$_.RuntimeName2}).Matches[0].Groups['lunID'].Value
                Write-Host "Detaching LUN $CanonicalName (ID:$lunID DisplayName:$lunDisplayName) on $h"
                $storSys.DetachScsiLun($lunUuid)
            }
        }
    }
}

Function Global:Lints-VMHost-Get-CpuReady{
    Param($Hosts = "*", $Interval = "day")

    Switch ($Interval) {
        "day"   {$days = -1;  $mins = 5;   $divider = 3000}
        "week"  {$days = -7;  $mins = 30;  $divider = 18000}
        "month" {$days = -30; $mins = 120; $divider = 72000}
    }

    If ($global:DefaultVIServers.Count -gt 0) {
        $groups = Get-Stat -Entity (Get-VMHost $Hosts) -Stat cpu.ready.summation -Start (Get-Date).adddays($days) -Finish (Get-Date) -Interval $mins -Instance "" -ea silentlycontinue | Group entity

        $output=@()

        ForEach ($group in $groups) {
            $temp = "" | Select-Object Name, "Ready%"
            $temp.name = $group.name

            $temp."ready%" = “{0:n2}” -f (($group.group | measure-object value -ave).average/$divider)

            $output += $temp
        }
 
        $output | Format-Table -AutoSize

    } else {
        echo "Not connected to a vCenter Server. Use 'Connect-VIServer -Server <VCenterName>' to make a connection"
    }
}

Function Global:Lints-VMHost-Get-CpuRatio{
<#
.SYNOPSIS
   Given a VMhost or group of VMHosts this function will query how many logical processors the host has, and compare it to the number vCPUs assigned to guest currently running on that host.

.PARAMETER VMHosts
   Which VMHosts will this function be run against
   
.EXAMPLE
   get-cpuratio -vmhosts "host1","host2"

#>

    Param($vmhosts="*")

    If ($global:DefaultVIServers.Count -gt 0) {

        $vmhosts = Get-VMHost $vmhosts
        $vms = Get-VM
        $Output=@()

        ForEach ($vmhost in $vmhosts) {
            $vcpus = 0
            $ratio = $null
            $hostthreads = $vmhost.extensiondata.hardware.cpuinfo.numcputhreads
            $vms |Where-Object {$_.vmhost -like $vmhost} | ForEach {$vcpus += $_.numcpu}

            if ($vcpus -ne "0") {$ratio = "$("{0:N2}" -f ($vcpus/$hostthreads))" + ":1"}

            $temp= New-Object psobject
            $temp| Add-Member -MemberType Noteproperty "Hostname" -value $vmhost.name
            $temp| Add-Member -MemberType Noteproperty "PhysicalThreads" -Value $Hostthreads
            $temp| Add-Member -MemberType Noteproperty "vCPUs" -Value $vcpus
            $temp| Add-Member -MemberType Noteproperty "Ratio" -Value $ratio
            $Output += $temp

        }
        $Output | Sort-Object Hostname | Format-Table -AutoSize

    } else {
        echo "Not connected to a vCenter Server. Use 'Connect-VIServer -Server <VCenterName>' to make a connection"
    }
}

function Global:Lints-VMHost-Get-ObservedIPRange {
  # Credit: http://poshcode.org/
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$True,HelpMessage=”Physical NIC from Get-VMHostNetworkAdapter”)]
    [Object[]]$Nics
  )

  process {
    forEach ($Nic in $Nics) {
      if($Nic -notlike “vmk*”) {
        [VMware.VimAutomation.Client20.Host.NIC.PhysicalNicImpl]$NicImpl = $Nic
        $hostView = Get-VMHost -Id $NicImpl.VMHostId | Get-View -Property ConfigManager
        $ns = Get-View $hostView.ConfigManager.NetworkSystem
        $hints = $ns.QueryNetworkHint($NicImpl.Name)

        foreach ($hint in $hints) {
          if( ($hint.ConnectedSwitchPort)) {
            foreach ($subnet in $hint.subnet) {
              $observed = New-Object -TypeName PSObject
              $observed | Add-Member -MemberType NoteProperty -Name VMHostId -Value $NicImpl.VMHostId
              $observed | Add-Member -MemberType NoteProperty -Name VMHost -Value $NicImpl.VMHost
              $observed | Add-Member -MemberType NoteProperty -Name Device -Value $NicImpl.Name
              $observed | Add-Member -MemberType NoteProperty -Name IPSubnet -Value $subnet.IPSubnet
              $observed | Add-Member -MemberType NoteProperty -Name VlanId -Value $subnet.VlanId
              Write-Output $observed
            }
          }
        }
      }
    }
  }
}

Function Global:Lints-VMHost-Get-PowerProfile {
    [CmdletBinding()]
    Param(
        [parameter(
            Mandatory=$true,
            ValueFromPipeline=$true)]
        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl[]]$hosts
    ) 

    Process { 
        foreach ($h in $hosts) {
            Get-VMHost $h | Select Name,
            @{ N="CurrentPolicy"; E={$_.ExtensionData.config.PowerSystemInfo.CurrentPolicy.ShortName}},
            @{ N="CurrentPolicyKey"; E={$_.ExtensionData.config.PowerSystemInfo.CurrentPolicy.Key}},
            @{ N="AvailablePolicies"; E={$_.ExtensionData.config.PowerSystemCapability.AvailablePolicy.ShortName}}

        }
    }
}