Merge remote-tracking branch 'vmware/master'

This commit is contained in:
Kyle Ruddy
2017-05-26 14:56:49 -04:00
47 changed files with 6906 additions and 541 deletions

0
.gitattributes vendored Normal file
View File

51
.gitignore vendored Normal file
View File

@@ -0,0 +1,51 @@
# PowerShell Studio Files
*.temppoint.*
*.psproj.psbuild
*.psbuild
#VS Code Files
*.vscode
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# =========================
# Operating System Files
# =========================
# OSX
# =========================
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

View File

@@ -0,0 +1,184 @@
#Created by Alan Renouf, published at https://communities.vmware.com/docs/DOC-18008
Function Get-DatastoreMountInfo {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$true)]
$Datastore
)
Process {
$AllInfo = @()
if (-not $Datastore) {
$Datastore = Get-Datastore
}
Foreach ($ds in $Datastore) {
if ($ds.ExtensionData.info.Vmfs) {
$hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].diskname
if ($ds.ExtensionData.Host) {
$attachedHosts = $ds.ExtensionData.Host
Foreach ($VMHost in $attachedHosts) {
$hostview = Get-View $VMHost.Key
$hostviewDSState = $VMHost.MountInfo.Mounted
$StorageSys = Get-View $HostView.ConfigManager.StorageSystem
$devices = $StorageSys.StorageDeviceInfo.ScsiLun
Foreach ($device in $devices) {
$Info = "" | Select Datastore, VMHost, Lun, Mounted, State
if ($device.canonicalName -eq $hostviewDSDiskName) {
$hostviewDSAttachState = ""
if ($device.operationalState[0] -eq "ok") {
$hostviewDSAttachState = "Attached"
} elseif ($device.operationalState[0] -eq "off") {
$hostviewDSAttachState = "Detached"
} else {
$hostviewDSAttachState = $device.operationalstate[0]
}
$Info.Datastore = $ds.Name
$Info.Lun = $hostviewDSDiskName
$Info.VMHost = $hostview.Name
$Info.Mounted = $HostViewDSState
$Info.State = $hostviewDSAttachState
$AllInfo += $Info
}
}
}
}
}
}
$AllInfo
}
}
Function Detach-Datastore {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$true)]
$Datastore
)
Process {
if (-not $Datastore) {
Write-Host "No Datastore defined as input"
Exit
}
Foreach ($ds in $Datastore) {
$hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname
if ($ds.ExtensionData.Host) {
$attachedHosts = $ds.ExtensionData.Host
Foreach ($VMHost in $attachedHosts) {
$hostview = Get-View $VMHost.Key
$StorageSys = Get-View $HostView.ConfigManager.StorageSystem
$devices = $StorageSys.StorageDeviceInfo.ScsiLun
Foreach ($device in $devices) {
if ($device.canonicalName -eq $hostviewDSDiskName) {
$LunUUID = $Device.Uuid
Write-Host "Detaching LUN $($Device.CanonicalName) from host $($hostview.Name)..."
$StorageSys.DetachScsiLun($LunUUID);
}
}
}
}
}
}
}
Function Unmount-Datastore {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$true)]
$Datastore
)
Process {
if (-not $Datastore) {
Write-Host "No Datastore defined as input"
Exit
}
Foreach ($ds in $Datastore) {
$hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname
if ($ds.ExtensionData.Host) {
$attachedHosts = $ds.ExtensionData.Host
Foreach ($VMHost in $attachedHosts) {
$hostview = Get-View $VMHost.Key
$StorageSys = Get-View $HostView.ConfigManager.StorageSystem
Write-Host "Unmounting VMFS Datastore $($DS.Name) from host $($hostview.Name)..."
$StorageSys.UnmountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid);
}
}
}
}
}
Function Mount-Datastore {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$true)]
$Datastore
)
Process {
if (-not $Datastore) {
Write-Host "No Datastore defined as input"
Exit
}
Foreach ($ds in $Datastore) {
$hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname
if ($ds.ExtensionData.Host) {
$attachedHosts = $ds.ExtensionData.Host
Foreach ($VMHost in $attachedHosts) {
$hostview = Get-View $VMHost.Key
$StorageSys = Get-View $HostView.ConfigManager.StorageSystem
Write-Host "Mounting VMFS Datastore $($DS.Name) on host $($hostview.Name)..."
$StorageSys.MountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid);
}
}
}
}
}
Function Attach-Datastore {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$true)]
$Datastore
)
Process {
if (-not $Datastore) {
Write-Host "No Datastore defined as input"
Exit
}
Foreach ($ds in $Datastore) {
$hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname
if ($ds.ExtensionData.Host) {
$attachedHosts = $ds.ExtensionData.Host
Foreach ($VMHost in $attachedHosts) {
$hostview = Get-View $VMHost.Key
$StorageSys = Get-View $HostView.ConfigManager.StorageSystem
$devices = $StorageSys.StorageDeviceInfo.ScsiLun
Foreach ($device in $devices) {
if ($device.canonicalName -eq $hostviewDSDiskName) {
$LunUUID = $Device.Uuid
Write-Host "Attaching LUN $($Device.CanonicalName) to host $($hostview.Name)..."
$StorageSys.AttachScsiLun($LunUUID);
}
}
}
}
}
}
}
#
#Get-Datastore | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize
#
#Get-Datastore IX2ISCSI01 | Unmount-Datastore
#
#Get-Datastore IX2ISCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize
#
#Get-Datastore IX2iSCSI01 | Mount-Datastore
#
#Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize
#
#Get-Datastore IX2iSCSI01 | Detach-Datastore
#
#Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize
#
#Get-Datastore IX2iSCSI01 | Attach-datastore
#
#Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize
#

View File

@@ -0,0 +1,93 @@
function Get-NICDetails {
<#
.NOTES
===========================================================================
Created by: Markus Kraus
Twitter: @VMarkus_K
Private Blog: mycloudrevolution.com
===========================================================================
Changelog:
2017.02 ver 1.0 Base Release
===========================================================================
External Code Sources:
-
===========================================================================
Tested Against Environment:
vSphere Version: ESXi 6.0 U2, ESXi 6.5
PowerCLI Version: PowerCLI 6.3 R1, PowerCLI 6.5 R1
PowerShell Version: 4.0, 5.0
OS Version: Windows 8.1, Server 2008 R2, Server 2012 R2
Keyword: ESXi, NIC, vmnic, Driver, Firmware
===========================================================================
.DESCRIPTION
Reports Firmware and Driver Details for your ESXi vmnics.
.Example
Get-NICDetails -Clustername *
.PARAMETER Clustername
Name or Wildcard of your vSphere Cluster Name to process.
#Requires PS -Version 4.0
#Requires -Modules VMware.VimAutomation.Core, @{ModuleName="VMware.VimAutomation.Core";ModuleVersion="6.3.0.0"}
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0)]
[ValidateNotNullorEmpty()]
[String] $Clustername
)
Begin {
$Validate = $True
if (($myCluster = Get-Cluster -Name $Clustername).count -lt 1) {
$Validate = $False
thow "No Cluster '$myCluster' found!"
}
}
Process {
$MyView = @()
if ($Validate -eq $True) {
foreach ($myVMhost in ($myCluster | Get-VMHost)) {
$esxcli2 = Get-ESXCLI -VMHost $myVMhost -V2
$niclist = $esxcli2.network.nic.list.invoke()
$nicdetails = @()
foreach ($nic in $niclist) {
$args = $esxcli2.network.nic.get.createargs()
$args.nicname = $nic.name
$nicdetail = $esxcli2.network.nic.get.Invoke($args)
$nicdetails += $nicdetail
}
ForEach ($nicdetail in $nicdetails){
$NICReport = [PSCustomObject] @{
Host = $myVMhost.Name
vmnic = $nicdetail.Name
LinkStatus = $nicdetail.LinkStatus
BusInfo = $nicdetail.driverinfo.BusInfo
Driver = $nicdetail.driverinfo.Driver
FirmwareVersion = $nicdetail.driverinfo.FirmwareVersion
DriverVersion = $nicdetail.driverinfo.Version
}
$MyView += $NICReport
}
}
$MyView
}
}
}

View File

@@ -0,0 +1,468 @@
Function New-PHAProvider {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to register a new Proactive HA Provider with vCenter Server
.PARAMETER ProviderName
Name of ProactiveHA Provider
.PARAMETER ComponentType
Name of a supported ComponentType that ProactiveHA supports (Fan, Memory, Network, Power or Storage)
.PARAMETER ComponentDescription
Description of the health check for the given component
.PARAMETER ComponentId
Unique identifier for the given component within a ProactiveHA Provider
.EXAMPLE
New-PHAProvider -ProviderName "virtuallyGhetto" -ComponentType Power -ComponentDescription "Simulated ProactiveHA Provider" -ComponentId "Power"
#>
param(
[Parameter(Mandatory=$true)][String]$ProviderName,
[Parameter(Mandatory=$true)][ValidateSet("Fan","Memory","Network","Power","Storage")][String]$ComponentType,
[Parameter(Mandatory=$true)][String]$ComponentDescription,
[Parameter(Mandatory=$true)][String]$ComponentId
)
Write-Host -ForegroundColor Red "`n******************** DISCLAIMER ********************"
Write-Host -ForegroundColor Red "**** THIS IS NOT INTENDED FOR PRODUCTION USE ****"
Write-Host -ForegroundColor Red "**** LEARNING PURPOSES ONLY ****"
Write-Host -ForegroundColor Red "******************** DISCLAIMER ********************`n"
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
$healthInfo = [VMware.Vim.HealthUpdateInfo] @{
ComponentType = $ComponentType
description = $ComponentDescription
Id = $ComponentId
}
try {
Write-Host "`nRegistering new Proactive HA Provider $ProviderName ..."
$providerId = $healthManager.RegisterHealthUpdateProvider($ProviderName,$healthInfo)
} catch {
Write-host -ForegroundColor Red $Error[0].Exception
}
}
Function Get-PHAProvider {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to return list of all Proactive HA Providers registered with vCenter Server
.EXAMPLE
Get-PHAProvider
#>
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
$healthProviderResults = @()
$hpIDs = $healthManager.QueryProviderList()
foreach ($hpID in $hpIDs) {
$hpName = $healthManager.QueryProviderName($hpID)
$hpConfig = $healthManager.QueryHealthUpdateInfos($hpID)
$hp = [pscustomobject] @{
ProviderName = $hpName
ProviderID = $hpID
ComponentType = $hpConfig.componentType
ComponentID = $hpConfig.id
Description = $hpConfig.description
}
$healthProviderResults+=$hp
}
$healthProviderResults
}
Function Remove-PHAProvider {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to remove a registered Proactive HA Provider from vCenter Server
.PARAMETER ProviderId
The ProactiveHA provider ID (retrieved from Get-PHAProvider) to unregister
.EXAMPLE
Remove-PHAProvider -ProviderID "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79"
#>
param(
[Parameter(Mandatory=$true)][String]$ProviderId
)
Write-Host -ForegroundColor Red "`n******************** DISCLAIMER ********************"
Write-Host -ForegroundColor Red "**** THIS IS NOT INTENDED FOR PRODUCTION USE ****"
Write-Host -ForegroundColor Red "**** LEARNING PURPOSES ONLY ****"
Write-Host -ForegroundColor Red "******************** DISCLAIMER ********************`n"
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
try {
Write-Host "`nUnregistering Proactive HA Provider $ProviderId ... "
$healthManager.UnregisterHealthUpdateProvider($providerId)
} catch {
if($Error[0].Exception.InnerException.MethodFault.getType().Name -eq "InvalidState") {
Write-host -ForegroundColor Red "The Proactive HA Provider is still in use, please disable it before unregistering"
} else {
Write-host -ForegroundColor Red $Error[0].Exception
}
}
}
Function Set-PHAConfig {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to enable/disable Proactive HA for vSphere Cluster
.PARAMETER Cluster
Name of the vSphere Cluster to enable Proactive HA
.PARAMETER ProviderId
Proactive HA Provider ID to enable in vSphere Cluster
.PARAMETER ClusterMode
Whether Proactive HA should be "Automated" or "Manual" for actions it will take
.PARAMETER ModerateRemediation
Type of operation (Maintenance Mode or Quaratine Mode) to perform when a Moderate issue is observed
.PARAMETER SevereRemediation
Type of operation (Maintenance Mode or Quaratine Mode) to perform when a Severe issue is observed
.EXAMPLE
Set-PHAConfig -Cluster VSAN-Cluster -Enabled -ClusterMode Automated -ModerateRemediation QuarantineMode -SevereRemediation QuarantineMode -ProviderID "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79"
.EXAMPLE
Set-PHAConfig -Cluster VSAN-Cluster -Disabled -ProviderID "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79"
#>
param(
[Parameter(Mandatory=$true)][String]$ProviderId,
[Parameter(Mandatory=$true)][String]$Cluster,
[Parameter(Mandatory=$false)][ValidateSet("Automated","Manual")]$ClusterMode="Manual",
[Parameter(Mandatory=$false)][ValidateSet("MaintenanceMode","QuarantineMode")]$ModerateRemediation="QuarantineMode",
[Parameter(Mandatory=$false)][ValidateSet("MaintenanceMode","QuarantineMode")]$SevereRemediation="QuarantineMode",
[Switch]$Enabled,
[Switch]$Disabled
)
$ClusterView = Get-View -ViewType ClusterComputeResource -Property Name,Host,ConfigurationEx -Filter @{"Name" = $Cluster}
if($ClusterView -eq $null) {
Write-Host -ForegroundColor Red "Unable to find vSphere Cluster $cluster ..."
break
}
$vmhosts = $ClusterView.host
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
if($Enabled) {
try {
$entities = @()
foreach ($vmhost in $vmhosts) {
if(-not $healthManager.HasMonitoredEntity($ProviderId,$vmhost)) {
$entities += $vmhost
}
}
Write-Host "Enabling Proactive HA monitoring for all ESXi hosts in cluster ..."
$healthManager.AddMonitoredEntities($ProviderId,$entities)
} catch {
Write-host -ForegroundColor Red $Error[0].Exception
}
try {
$healthProviders = @()
# Make sure not to remove existing ProactiveHA providers
if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) {
$currentHPs = $ClusterView.ConfigurationEx.infraUpdateHaConfig.providers
foreach ($currentHP in $currentHPs) {
$healthProviders+=$currentHP
}
if(-not ($healthProviders -contains $ProviderID)) {
$healthProviders+=$ProviderId
}
} else {
$healthProviders+=$ProviderId
}
$PHASpec = [VMware.Vim.ClusterInfraUpdateHaConfigInfo] @{
enabled = $true
behavior = $ClusterMode
moderateRemediation = $ModerateRemediation
severeRemediation = $SevereRemediation
providers = $healthProviders
}
$spec = [VMware.Vim.ClusterConfigSpecEx] @{
infraUpdateHaConfig = $PHASpec
}
Write-Host "Enabling Proactive HA Provider $ProviderId on $Cluster ..."
$task = $ClusterView.ReconfigureComputeResource_Task($spec,$True)
$task1 = Get-Task -Id ("Task-$($task.value)")
$task1 | Wait-Task | Out-Null
} catch {
Write-host -ForegroundColor Red $Error[0].Exception
}
}
if($Disabled) {
foreach ($vmhost in $vmhosts) {
if($vmhost.runtime.inQuarantineMode) {
Write-Host -ForegroundColor Red $vmhost.name " is currently still in Quaratine Mode, please remediate this before disabling Proactive HA"
break
}
}
try {
$healthProviders = @()
# Make sure not to remove existing ProactiveHA providers
if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) {
$currentHPs = $ClusterView.ConfigurationEx.infraUpdateHaConfig.providers
foreach ($currentHP in $currentHPs) {
if($currentHP -ne $ProviderId) {
$healthProviders+=$currentHP
}
}
}
$PHASpec = [VMware.Vim.ClusterInfraUpdateHaConfigInfo] @{
enabled = $true
behavior = $ClusterMode
moderateRemediation = $ModerateRemediation
severeRemediation = $SevereRemediation
providers = $healthProviders
}
$spec = [VMware.Vim.ClusterConfigSpecEx] @{
infraUpdateHaConfig = $PHASpec
}
Write-Host "Disabling Proactive HA Provider $ProviderId on $Cluster ..."
$task = $ClusterView.ReconfigureComputeResource_Task($spec,$True)
$task1 = Get-Task -Id ("Task-$($task.value)")
$task1 | Wait-Task | Out-Null
} catch {
Write-host -ForegroundColor Red $Error[0].Exception
}
$ClusterView.UpdateViewData()
try {
$entities = @()
foreach ($vmhost in $vmhosts) {
if($healthManager.HasMonitoredEntity($ProviderId,$vmhost)) {
$entities += $vmhost
}
}
Write-Host "Disabling Proactive HA monitoring for all ESXi hosts in cluster ..."
$healthManager.RemoveMonitoredEntities($ProviderId,$entities)
} catch {
Write-host -ForegroundColor Red $Error[0].Exception
}
}
}
Function Get-PHAConfig {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to retrieve Proactive HA configuration for a vSphere Cluster
.PARAMETER Cluster
Name of the vSphere Cluster to check Proactive HA configuration
.EXAMPLE
Get-PHAConfig -Cluster VSAN-Cluster
#>
param(
[Parameter(Mandatory=$true)][String]$Cluster
)
$ClusterView = Get-View -ViewType ClusterComputeResource -Property Name,ConfigurationEx -Filter @{"Name" = $Cluster}
if($ClusterView -eq $null) {
Write-Host -ForegroundColor Red "Unable to find vSphere Cluster $cluster ..."
break
}
if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) {
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
$phSettings = $ClusterView.ConfigurationEx.InfraUpdateHaConfig
$providers = $ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers
$healthProviders = @()
foreach ($provider in $providers) {
$providerName = $healthManager.QueryProviderName($provider)
$healthProviders+=$providerName
}
$pHAConfig = [pscustomobject] @{
Enabled = $phSettings.Enabled
ClusterMode = $phSettings.behavior
ModerateRemediation = $phSettings.ModerateRemediation
SevereRemediation = $phSettings.SevereRemediation
HealthProviders = $healthProviders
}
$pHAConfig
} else {
Write-Host "Proactive HA has not been configured on this vSphere Cluster"
}
}
Function Get-PHAHealth {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to retrieve the Proactive HA health info for all ESXi hosts in vSphere Cluster
.PARAMETER Cluster
Name of the vSphere Cluster to check Proactive HA health information
.EXAMPLE
Get-PHAHealth -Cluster VSAN-Cluster
#>
param(
[Parameter(Mandatory=$true)][String]$Cluster
)
$ClusterView = Get-View -ViewType ClusterComputeResource -Property Name,ConfigurationEx -Filter @{"Name" = $Cluster}
if($ClusterView -eq $null) {
Write-Host -ForegroundColor Red "Unable to find vSphere Cluster $cluster ..."
break
}
if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) {
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
$providers = $ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers
foreach ($provider in $providers) {
$providerName = $healthManager.QueryProviderName($provider)
$healthUpdates = $healthManager.QueryHealthUpdates($provider)
$healthResults = @()
Write-Host -NoNewline -ForegroundColor Magenta "Health summary for Proactive HA Provider $providerName`:`n"
foreach ($healthUpdate in $healthUpdates) {
$vmhost = Get-View $healthUpdate.Entity
$hr = [PSCustomObject] @{
Entity = $vmhost.name
Status = $healthUpdate.status
HealthComponentId = $healthUpdate.HealthUpdateInfoId
HealthUpdateId = $healthUpdate.Id
Remediation = $healthUpdate.Remediation
}
$healthResults+=$hr
}
$healthResults
}
} else {
Write-Host "Proactive HA has not been configured on this vSphere Cluster"
}
}
Function New-PHASimulation {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
Function to return VCHA Configuration
.PARAMETER ProviderId
The Proactive HA Provider ID that you like to simulate a health update from
.PARAMETER EsxiHost
The name of ESXi host to update the health on
.PARAMETER Component
The name of the matching component ID from Proactive HA Provider to simulate a health update from
.PARAMETER HealthStatus
The health value (green, yellow or red) for the given simulated health Update
.PARAMETER Remediation
The remediation message associated with simulated health update
.EXAMPLE
New-PHASimulation -EsxiHost vesxi65-4.primp-industries.com -Component Power -HealthStatus green -Remediation "" -ProviderId "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79"
.EXAMPLE
New-PHASimulation -EsxiHost vesxi65-4.primp-industries.com -Component Power -HealthStatus red -Remediation "Please replace my virtual PSU" -ProviderId "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79"
#>
param(
[Parameter(Mandatory=$true)][String]$ProviderId,
[Parameter(Mandatory=$true)][String]$EsxiHost,
[Parameter(Mandatory=$true)][String]$Component,
[Parameter(Mandatory=$true)][ValidateSet("green","red","yellow")][String]$HealthStatus,
[Parameter(Mandatory=$false)][String]$Remediation
)
Write-Host -ForegroundColor Red "`n******************** DISCLAIMER ********************"
Write-Host -ForegroundColor Red "**** THIS IS NOT INTENDED FOR PRODUCTION USE ****"
Write-Host -ForegroundColor Red "**** LEARNING PURPOSES ONLY ****"
Write-Host -ForegroundColor Red "******************** DISCLAIMER ********************`n"
$vmhost = Get-View -ViewType HostSystem -Property Name -Filter @{"name" = $EsxiHost}
if($vmhost -eq $null) {
Write-Host -ForegroundColor Red "`nUnable to find ESXi host $EsxiHost ..."
break
}
$healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager
# Randomly generating an ID for Health Update
# In general, you would want to generate a specific ID
# which can be referenced between ProactiveHA Provider
# and VMware logs for troubleshooting purposes
$HealthUpdateID = "vghetto-" + (Get-Random -Minimum 1 -Maximum 100000)
# All other Health Status can have a remediation message
# but for green, it must be an empty string or API call will fail
if($HealthStatus -eq "green") {
$Remediation = ""
}
$healthUpdate = [VMware.Vim.HealthUpdate] @{
Entity = $vmhost.moref
HealthUpdateInfoId = $Component
Id = $HealthUpdateId
Status = $HealthStatus
Remediation = $Remediation
}
try {
Write-Host "`nSimulating Proactive HA Health Update to ..."
Write-Host "`tHost: $EsxiHost "
Write-Host -NoNewline "`tStatus: "
Write-Host -ForegroundColor $HealthStatus "$HealthStatus"
Write-Host "`tRemediation Messsage: $Remediation"
$healthManager.PostHealthUpdates($providerId,$healthUpdate)
} catch {
Write-host -ForegroundColor Red $Error[0].Exception
}
}

716
Modules/VAMI/VAMI.psm1 Executable file
View File

@@ -0,0 +1,716 @@
Function Get-VAMISummary {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves some basic information from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return basic VAMI summary info
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMISummary
#>
$systemVersionAPI = Get-CisService -Name 'com.vmware.appliance.system.version'
$results = $systemVersionAPI.get() | select product, type, version, build, install_time
$systemUptimeAPI = Get-CisService -Name 'com.vmware.appliance.system.uptime'
$ts = [timespan]::fromseconds($systemUptimeAPI.get().toString())
$uptime = $ts.ToString("hh\:mm\:ss\,fff")
$summaryResult = [pscustomobject] @{
Product = $results.product;
Type = $results.type;
Version = $results.version;
Build = $results.build;
InstallTime = $results.install_time;
Uptime = $uptime
}
$summaryResult
}
Function Get-VAMIHealth {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves health information from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return VAMI health
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIHealth
#>
$healthOverall = (Get-CisService -Name 'com.vmware.appliance.health.system').get()
$healthLastCheck = (Get-CisService -Name 'com.vmware.appliance.health.system').lastcheck()
$healthCPU = (Get-CisService -Name 'com.vmware.appliance.health.load').get()
$healthMem = (Get-CisService -Name 'com.vmware.appliance.health.mem').get()
$healthSwap = (Get-CisService -Name 'com.vmware.appliance.health.swap').get()
$healthStorage = (Get-CisService -Name 'com.vmware.appliance.health.storage').get()
# DB health only applicable for Embedded/External VCSA Node
$vami = (Get-CisService -Name 'com.vmware.appliance.system.version').get()
if($vami.type -eq "vCenter Server with an embedded Platform Services Controller" -or $vami.type -eq "vCenter Server with an external Platform Services Controller") {
$healthVCDB = (Get-CisService -Name 'com.vmware.appliance.health.databasestorage').get()
} else {
$healthVCDB = "N/A"
}
$healthSoftwareUpdates = (Get-CisService -Name 'com.vmware.appliance.health.softwarepackages').get()
$healthResult = [pscustomobject] @{
HealthOverall = $healthOverall;
HealthLastCheck = $healthLastCheck;
HealthCPU = $healthCPU;
HealthMem = $healthMem;
HealthSwap = $healthSwap;
HealthStorage = $healthStorage;
HealthVCDB = $healthVCDB;
HealthSoftware = $healthSoftwareUpdates
}
$healthResult
}
Function Get-VAMIAccess {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves access information from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return VAMI access interfaces (Console,DCUI,Bash Shell & SSH)
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIAccess
#>
$consoleAccess = (Get-CisService -Name 'com.vmware.appliance.access.consolecli').get()
$dcuiAccess = (Get-CisService -Name 'com.vmware.appliance.access.dcui').get()
$shellAccess = (Get-CisService -Name 'com.vmware.appliance.access.shell').get()
$sshAccess = (Get-CisService -Name 'com.vmware.appliance.access.ssh').get()
$accessResult = New-Object PSObject -Property @{
Console = $consoleAccess;
DCUI = $dcuiAccess;
BashShell = $shellAccess.enabled;
SSH = $sshAccess
}
$accessResult
}
Function Get-VAMITime {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves the time and NTP info from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return current Time and NTP information
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMITime
#>
$systemTimeAPI = Get-CisService -Name 'com.vmware.appliance.system.time'
$timeResults = $systemTimeAPI.get()
$timeSync = (Get-CisService -Name 'com.vmware.appliance.techpreview.timesync').get()
$timeSyncMode = $timeSync.mode
$timeResult = [pscustomobject] @{
Timezone = $timeResults.timezone;
Date = $timeResults.date;
CurrentTime = $timeResults.time;
Mode = $timeSyncMode;
NTPServers = "N/A";
NTPStatus = "N/A";
}
if($timeSyncMode -eq "NTP") {
$ntpServers = (Get-CisService -Name 'com.vmware.appliance.techpreview.ntp').get()
$timeResult.NTPServers = $ntpServers.servers
$timeResult.NTPStatus = $ntpServers.status
}
$timeResult
}
Function Get-VAMINetwork {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves network information from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return networking information including details for each interface
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMINetwork
#>
$netResults = @()
$Hostname = (Get-CisService -Name 'com.vmware.appliance.networking.dns.hostname').get()
$dns = (Get-CisService -Name 'com.vmware.appliance.networking.dns.servers').get()
Write-Host "Hostname: " $hostname
Write-Host "DNS Servers: " $dns.servers
$interfaces = (Get-CisService -Name 'com.vmware.appliance.networking.interfaces').list()
foreach ($interface in $interfaces) {
$ipv4API = (Get-CisService -Name 'com.vmware.appliance.techpreview.networking.ipv4')
$spec = $ipv4API.Help.get.interfaces.CreateExample()
$spec+= $interface.name
$ipv4result = $ipv4API.get($spec)
$interfaceResult = [pscustomobject] @{
Inteface = $interface.name;
MAC = $interface.mac;
Status = $interface.status;
Mode = $ipv4result.mode;
IP = $ipv4result.address;
Prefix = $ipv4result.prefix;
Gateway = $ipv4result.default_gateway;
Updateable = $ipv4result.updateable
}
$netResults += $interfaceResult
}
$netResults
}
Function Get-VAMIDisks {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves VMDK disk number to partition mapping VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return VMDK disk number to OS partition mapping
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIDisks
#>
$storageAPI = Get-CisService -Name 'com.vmware.appliance.system.storage'
$disks = $storageAPI.list()
foreach ($disk in $disks | sort {[int]$_.disk.toString()}) {
$disk | Select Disk, Partition
}
}
Function Start-VAMIDiskResize {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function triggers an OS partition resize after adding additional disk capacity
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function triggers OS partition resize operation
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Start-VAMIDiskResize
#>
$storageAPI = Get-CisService -Name 'com.vmware.appliance.system.storage'
Write-Host "Initiated OS partition resize operation ..."
$storageAPI.resize()
}
Function Get-VAMIStatsList {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves list avialable monitoring metrics in VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return list of available monitoring metrics that can be queried
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIStatsList
#>
$monitoringAPI = Get-CisService -Name 'com.vmware.appliance.monitoring'
$ids = $monitoringAPI.list() | Select id | Sort-Object -Property id
foreach ($id in $ids) {
$id
}
}
Function Get-VAMIStorageUsed {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves the individaul OS partition storage utilization
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return individual OS partition storage utilization
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIStorageUsed
#>
$monitoringAPI = Get-CisService 'com.vmware.appliance.monitoring'
$querySpec = $monitoringAPI.help.query.item.CreateExample()
# List of IDs from Get-VAMIStatsList to query
$querySpec.Names = @(
"storage.used.filesystem.autodeploy",
"storage.used.filesystem.boot",
"storage.used.filesystem.coredump",
"storage.used.filesystem.imagebuilder",
"storage.used.filesystem.invsvc",
"storage.used.filesystem.log",
"storage.used.filesystem.netdump",
"storage.used.filesystem.root",
"storage.used.filesystem.updatemgr",
"storage.used.filesystem.vcdb_core_inventory",
"storage.used.filesystem.vcdb_seat",
"storage.used.filesystem.vcdb_transaction_log",
"storage.totalsize.filesystem.autodeploy",
"storage.totalsize.filesystem.boot",
"storage.totalsize.filesystem.coredump",
"storage.totalsize.filesystem.imagebuilder",
"storage.totalsize.filesystem.invsvc",
"storage.totalsize.filesystem.log",
"storage.totalsize.filesystem.netdump",
"storage.totalsize.filesystem.root",
"storage.totalsize.filesystem.updatemgr",
"storage.totalsize.filesystem.vcdb_core_inventory",
"storage.totalsize.filesystem.vcdb_seat",
"storage.totalsize.filesystem.vcdb_transaction_log"
)
# Tuple (Filesystem Name, Used, Total) to store results
$storageStats = @{
"autodeploy"=@{"name"="/storage/autodeploy";"used"=0;"total"=0};
"boot"=@{"name"="/boot";"used"=0;"total"=0};
"coredump"=@{"name"="/storage/core";"used"=0;"total"=0};
"imagebuilder"=@{"name"="/storage/imagebuilder";"used"=0;"total"=0};
"invsvc"=@{"name"="/storage/invsvc";"used"=0;"total"=0};
"log"=@{"name"="/storage/log";"used"=0;"total"=0};
"netdump"=@{"name"="/storage/netdump";"used"=0;"total"=0};
"root"=@{"name"="/";"used"=0;"total"=0};
"updatemgr"=@{"name"="/storage/updatemgr";"used"=0;"total"=0};
"vcdb_core_inventory"=@{"name"="/storage/db";"used"=0;"total"=0};
"vcdb_seat"=@{"name"="/storage/seat";"used"=0;"total"=0};
"vcdb_transaction_log"=@{"name"="/storage/dblog";"used"=0;"total"=0}
}
$querySpec.interval = "DAY1"
$querySpec.function = "MAX"
$querySpec.start_time = ((get-date).AddDays(-1))
$querySpec.end_time = (Get-Date)
$queryResults = $monitoringAPI.query($querySpec) | Select * -ExcludeProperty Help
foreach ($queryResult in $queryResults) {
# Update hash if its used storage results
if($queryResult.name -match "used") {
$key = (($queryResult.name).toString()).split(".")[-1]
$value = [Math]::Round([int]($queryResult.data[1]).toString()/1MB,2)
$storageStats[$key]["used"] = $value
# Update hash if its total storage results
} else {
$key = (($queryResult.name).toString()).split(".")[-1]
$value = [Math]::Round([int]($queryResult.data[1]).toString()/1MB,2)
$storageStats[$key]["total"] = $value
}
}
$storageResults = @()
foreach ($key in $storageStats.keys | Sort-Object -Property name) {
$statResult = [pscustomobject] @{
Filesystem = $storageStats[$key].name;
Used = $storageStats[$key].used;
Total = $storageStats[$key].total
}
$storageResults += $statResult
}
$storageResults
}
Function Get-VAMIService {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves list of services in VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return list of services and their description
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIService
.EXAMPLE
Get-VAMIService -Name rbd
#>
param(
[Parameter(
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)
]
[String]$Name
)
if($Name -ne "") {
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
try {
$serviceStatus = $vMonAPI.get($name,0)
$serviceString = [pscustomobject] @{
Name = $name;
State = $serviceStatus.state;
Health = "";
Startup = $serviceStatus.startup_type
}
if($serviceStatus.health -eq $null) { $serviceString.Health = "N/A"} else { $serviceString.Health = $serviceStatus.health }
$serviceString
} catch {
Write-Error $Error[0].exception.Message
}
} else {
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
$services = $vMonAPI.list_details()
$serviceResult = @()
foreach ($key in $services.keys | Sort-Object -Property Value) {
$serviceString = [pscustomobject] @{
Name = $key;
State = $services[$key].state;
Health = "N/A";
Startup = $services[$key].Startup_type
}
if($services[$key].health -eq $null) { $serviceString.Health = "N/A"} else { $serviceString.Health = $services[$key].health }
$serviceResult += $serviceString
}
$serviceResult
}
}
Function Start-VAMIService {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves list of services in VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return list of services and their description
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Start-VAMIService -Name rbd
#>
param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)
]
[String]$Name
)
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
try {
Write-Host "Starting $name service ..."
$vMonAPI.start($name)
} catch {
Write-Error $Error[0].exception.Message
}
}
Function Stop-VAMIService {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves list of services in VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return list of services and their description
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Stop-VAMIService -Name rbd
#>
param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)
]
[String]$Name
)
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
try {
Write-Host "Stopping $name service ..."
$vMonAPI.stop($name)
} catch {
Write-Error $Error[0].exception.Message
}
}
Function Get-VAMIBackupSize {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves the backup size of the VCSA from VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to return the current backup size of the VCSA (common and core data)
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIBackupSize
#>
$recoveryAPI = Get-CisService 'com.vmware.appliance.recovery.backup.parts'
$backupParts = $recoveryAPI.list() | select id
$estimateBackupSize = 0
$backupPartSizes = ""
foreach ($backupPart in $backupParts) {
$partId = $backupPart.id.value
$partSize = $recoveryAPI.get($partId)
$estimateBackupSize += $partSize
$backupPartSizes += $partId + " data is " + $partSize + " MB`n"
}
Write-Host "Estimated Backup Size: $estimateBackupSize MB"
Write-Host $backupPartSizes
}
Function Get-VAMIUser {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function retrieves VAMI local users using VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to retrieve VAMI local users
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIUser
#>
param(
[Parameter(
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)
]
[String]$Name
)
$userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user'
$userResults = @()
if($Name -ne "") {
try {
$user = $userAPI.get($name)
$userString = [pscustomobject] @{
User = $user.username
Name = $user.fullname
Email = $user.email
Status = $user.status
PasswordStatus = $user.passwordstatus
Role = $user.role
}
$userResults += $userString
} catch {
Write-Error $Error[0].exception.Message
}
} else {
$users = $userAPI.list()
foreach ($user in $users) {
$userString = [pscustomobject] @{
User = $user.username
Name = $user.fullname
Email = $user.email
Status = $user.status
PasswordStatus = $user.passwordstatus
Role = $user.role
}
$userResults += $userString
}
}
$userResults
}
Function New-VAMIUser {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function to create new VAMI local user using VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to create a new VAMI local user
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
New-VAMIUser -name lamw -fullname "William Lam" -role "operator" -email "lamw@virtuallyghetto.com" -password "VMware1!"
#>
param(
[Parameter(
Mandatory=$true)
]
[String]$name,
[Parameter(
Mandatory=$true)
]
[String]$fullname,
[Parameter(
Mandatory=$true)
]
[ValidateSet("admin","operator","superAdmin")][String]$role,
[Parameter(
Mandatory=$false)
]
[String]$email="",
[Parameter(
Mandatory=$true)
]
[String]$password
)
$userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user'
$createSpec = $userAPI.Help.add.config.CreateExample()
$createSpec.username = $name
$createSpec.fullname = $fullname
$createSpec.role = $role
$createSpec.email = $email
$createSpec.password = [VMware.VimAutomation.Cis.Core.Types.V1.Secret]$password
try {
Write-Host "Creating new user $name ..."
$userAPI.add($createSpec)
} catch {
Write-Error $Error[0].exception.Message
}
}
Function Remove-VAMIUser {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.SYNOPSIS
This function to remove VAMI local user using VAMI interface (5480)
for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA.
.DESCRIPTION
Function to remove VAMI local user
.EXAMPLE
Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1!
Get-VAMIAccess
#>
param(
[Parameter(
Mandatory=$true)
]
[String]$name,
[Parameter(
Mandatory=$false)
]
[boolean]$confirm=$false
)
if(!$confirm) {
$answer = Read-Host -Prompt "Do you want to delete user $name (Y or N)"
if($answer -eq "Y" -or $answer -eq "y") {
$userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user'
try {
Write-Host "Deleting user $name ..."
$userAPI.delete($name)
} catch {
Write-Error $Error[0].exception.Message
}
}
}
}

View File

@@ -0,0 +1,98 @@
{
"Type": "AUTOMATED",
"Data": {
"Name": "ICFarmJson",
"DisplayName": "FarmJsonTest",
"AccessGroup": "Root",
"Description": "created IC Farm from PS via JSON",
"Enabled": null,
"Deleting": false,
"Settings": {
"DisconnectedSessionTimeoutPolicy" : "NEVER",
"DisconnectedSessionTimeoutMinutes" : 1,
"EmptySessionTimeoutPolicy" : "AFTER",
"EmptySessionTimeoutMinutes" : 1,
"LogoffAfterTimeout" : false
},
"Desktop": null,
"DisplayProtocolSettings": {
"DefaultDisplayProtocol" : "PCOIP",
"AllowDisplayProtocolOverride" : false,
"EnableHTMLAccess" : false
},
"ServerErrorThreshold": null,
"MirageConfigurationOverrides": {
"OverrideGlobalSetting" : false,
"Enabled" : false,
"Url" : null
}
},
"AutomatedFarmSpec": {
"ProvisioningType": "INSTANT_CLONE_ENGINE",
"VirtualCenter": null,
"RdsServerNamingSpec": {
"NamingMethod": "PATTERN",
"PatternNamingSettings": {
"NamingPattern": "ICFarmVMPS",
"MaxNumberOfRDSServers": 1
}
},
"VirtualCenterProvisioningSettings": {
"EnableProvisioning": true,
"StopProvisioningOnError": true,
"MinReadyVMsOnVComposerMaintenance": 0,
"VirtualCenterProvisioningData": {
"ParentVm": "vm-rdsh-ic",
"Snapshot": "snap_5",
"Datacenter": null,
"VmFolder": "Instant_Clone_VMs",
"HostOrCluster": "vimal-cluster",
"ResourcePool": "vimal-cluster"
},
"VirtualCenterStorageSettings": {
"Datastores": [
{
"Datastore": "Datastore1",
"StorageOvercommit": "UNBOUNDED"
}
],
"UseVSan": false,
"ViewComposerStorageSettings": {
"UseSeparateDatastoresReplicaAndOSDisks": false,
"ReplicaDiskDatastore": null,
"UseNativeSnapshots": false,
"SpaceReclamationSettings": {
"ReclaimVmDiskSpace": false,
"ReclamationThresholdGB": null,
"BlackoutTimes": null
}
}
},
"VirtualCenterNetworkingSettings": {
"Nics": null
}
},
"VirtualCenterManagedCommonSettings": {
"TransparentPageSharingScope": "VM"
},
"CustomizationSettings": {
"CustomizationType": "CLONE_PREP",
"DomainAdministrator": null,
"AdContainer": "CN=Computers",
"ReusePreExistingAccounts": false,
"ClonePrepCustomizationSettings": {
"InstantCloneEngineDomainAdministrator": null,
"PowerOffScriptName": null,
"PowerOffScriptParameters": null,
"PostSynchronizationScriptName": null,
"PostSynchronizationScriptParameters": null
}
},
"RdsServerMaxSessionsData": {
"MaxSessionsType": "UNLIMITED",
"MaxSessions": null
}
},
"ManualFarmSpec": null,
"NetBiosName" : "ad-vimalg"
}

View File

@@ -1,17 +1,31 @@
{
"Type": "AUTOMATED",
"Data": {
"Name": "LCFarmTest",
"DisplayName": "Ankit LC Farm Test",
"Name": "LCFarmJson",
"DisplayName": "FarmJsonTest",
"AccessGroup": "Root",
"Description": "created LC Farm from PS",
"Description": "created LC Farm from PS via JSON",
"Enabled": null,
"Deleting": false,
"Settings": null,
"Settings": {
"DisconnectedSessionTimeoutPolicy" : "NEVER",
"DisconnectedSessionTimeoutMinutes" : 1,
"EmptySessionTimeoutPolicy" : "AFTER",
"EmptySessionTimeoutMinutes" : 1,
"LogoffAfterTimeout" : false
},
"Desktop": null,
"DisplayProtocolSettings": null,
"DisplayProtocolSettings": {
"DefaultDisplayProtocol" : "PCOIP",
"AllowDisplayProtocolOverride" : false,
"EnableHTMLAccess" : false
},
"ServerErrorThreshold": null,
"MirageConfigurationOverrides": null
"MirageConfigurationOverrides": {
"OverrideGlobalSetting" : false,
"Enabled" : false,
"Url" : null
}
},
"AutomatedFarmSpec": {
"ProvisioningType": "VIEW_COMPOSER",
@@ -19,7 +33,7 @@
"RdsServerNamingSpec": {
"NamingMethod": "PATTERN",
"PatternNamingSettings": {
"NamingPattern": "LCFarmVM_PS",
"NamingPattern": "LCFarmVMPS",
"MaxNumberOfRDSServers": 1
}
},
@@ -28,17 +42,17 @@
"StopProvisioningOnError": true,
"MinReadyVMsOnVComposerMaintenance": 0,
"VirtualCenterProvisioningData": {
"ParentVm": "Win_Server_2012_R2",
"Snapshot": "Snap_RDS",
"ParentVm": "RDSServer",
"Snapshot": "RDS_SNAP1",
"Datacenter": null,
"VmFolder": "AnkitPoolVM",
"HostOrCluster": "cls",
"ResourcePool": "cls"
"VmFolder": "Praveen",
"HostOrCluster": "CS-1",
"ResourcePool": "CS-1"
},
"VirtualCenterStorageSettings": {
"Datastores": [
{
"Datastore": "datastore1 (5)",
"Datastore": "Datastore1",
"StorageOvercommit": "UNBOUNDED"
}
],
@@ -67,7 +81,7 @@
"AdContainer": "CN=Computers",
"ReusePreExistingAccounts": false,
"SysprepCustomizationSettings": {
"CustomizationSpec": "RDSH_Cust2"
"CustomizationSpec": "PraveenCust"
}
},
"RdsServerMaxSessionsData": {
@@ -76,5 +90,5 @@
}
},
"ManualFarmSpec": null,
"NetBiosName" : "adankit"
"NetBiosName" : "adviewdev"
}

View File

@@ -7,17 +7,31 @@
"Description": "Manual PS Test",
"Enabled": null,
"Deleting": false,
"Settings": null,
"Settings": {
"DisconnectedSessionTimeoutPolicy" : "NEVER",
"DisconnectedSessionTimeoutMinutes" : 1,
"EmptySessionTimeoutPolicy" : "AFTER",
"EmptySessionTimeoutMinutes" : 1,
"LogoffAfterTimeout" : false
},
"Desktop": null,
"DisplayProtocolSettings": null,
"DisplayProtocolSettings": {
"DefaultDisplayProtocol" : "PCOIP",
"AllowDisplayProtocolOverride" : false,
"EnableHTMLAccess" : false
},
"ServerErrorThreshold": null,
"MirageConfigurationOverrides": null
"MirageConfigurationOverrides": {
"OverrideGlobalSetting" : false,
"Enabled" : false,
"Url" : null
}
},
"AutomatedFarmSpec": null,
"ManualFarmSpec": {
"RdsServers": [
{
"rdsServer": "WIN-ORKA1Q8B0P7"
"rdsServer": "RDSServer.adviewdev.eng.vmware.com"
}
]
}

View File

@@ -5,7 +5,44 @@
"AccessGroup": "Root",
"Description": "create full clone via JSON"
},
"DesktopSettings": null,
"DesktopSettings": {
"enabled": true,
"deleting": false,
"connectionServerRestrictions": null,
"logoffSettings": {
"powerPolicy": "TAKE_NO_POWER_ACTION",
"automaticLogoffPolicy": "NEVER",
"automaticLogoffMinutes": 120,
"allowUsersToResetMachines": false,
"allowMultipleSessionsPerUser": false,
"deleteOrRefreshMachineAfterLogoff": "NEVER",
"refreshOsDiskAfterLogoff": "NEVER",
"refreshPeriodDaysForReplicaOsDisk": 5,
"refreshThresholdPercentageForReplicaOsDisk": 10
},
"displayProtocolSettings": {
"supportedDisplayProtocols": ["PCOIP", "BLAST" ],
"defaultDisplayProtocol": "BLAST",
"allowUsersToChooseProtocol": true,
"pcoipDisplaySettings": {
"renderer3D": "DISABLED",
"enableGRIDvGPUs": false,
"vRamSizeMB": 96,
"maxNumberOfMonitors": 3,
"maxResolutionOfAnyOneMonitor": "WSXGA_PLUS"
},
"enableHTMLAccess": true
},
"flashSettings": {
"quality": "NO_CONTROL",
"throttling": "DISABLED"
},
"mirageConfigurationOverrides": {
"overrideGlobalSetting": false,
"enabled": false,
"url": false
}
},
"Type": "AUTOMATED",
"AutomatedDesktopSpec": {
"ProvisioningType": "VIRTUAL_CENTER",
@@ -69,7 +106,7 @@
"NoCustomizationSettings": {
"DoNotPowerOnVMsAfterCreation": false
},
"SysprepCustomizationSettings": null,
"SysprepCustomizationSettings": {"customizationSpec" : "praveencust"},
"QuickprepCustomizationSettings": null,
"CloneprepCustomizationSettings": null
}
@@ -77,6 +114,5 @@
"ManualDesktopSpec": null,
"RdsDesktopSpec": null,
"GlobalEntitlementData": null,
"NetBiosName" : "adviewdev",
"SysPrepName" : "praveencust"
"NetBiosName" : "adviewdev"
}

View File

@@ -5,7 +5,44 @@
"AccessGroup": "ROOT",
"Description": "create instant pool"
},
"DesktopSettings": null,
"DesktopSettings": {
"enabled": true,
"deleting": false,
"connectionServerRestrictions": null,
"logoffSettings": {
"powerPolicy": "ALWAYS_POWERED_ON",
"automaticLogoffPolicy": "NEVER",
"automaticLogoffMinutes": 120,
"allowUsersToResetMachines": false,
"allowMultipleSessionsPerUser": false,
"deleteOrRefreshMachineAfterLogoff": "DELETE",
"refreshOsDiskAfterLogoff": "NEVER",
"refreshPeriodDaysForReplicaOsDisk": 5,
"refreshThresholdPercentageForReplicaOsDisk": 10
},
"displayProtocolSettings": {
"supportedDisplayProtocols": ["PCOIP", "BLAST" ],
"defaultDisplayProtocol": "BLAST",
"allowUsersToChooseProtocol": true,
"pcoipDisplaySettings": {
"renderer3D": "DISABLED",
"enableGRIDvGPUs": false,
"vRamSizeMB": 96,
"maxNumberOfMonitors": 3,
"maxResolutionOfAnyOneMonitor": "WSXGA_PLUS"
},
"enableHTMLAccess": true
},
"flashSettings": {
"quality": "NO_CONTROL",
"throttling": "DISABLED"
},
"mirageConfigurationOverrides": {
"overrideGlobalSetting": false,
"enabled": false,
"url": false
}
},
"Type": "AUTOMATED",
"AutomatedDesktopSpec": {
"ProvisioningType": "INSTANT_CLONE_ENGINE",

View File

@@ -5,7 +5,44 @@
"AccessGroup": "Root",
"Description": "created linkedclone pool from ps"
},
"DesktopSettings": null,
"DesktopSettings": {
"enabled": true,
"deleting": false,
"connectionServerRestrictions": null,
"logoffSettings": {
"powerPolicy": "TAKE_NO_POWER_ACTION",
"automaticLogoffPolicy": "NEVER",
"automaticLogoffMinutes": 120,
"allowUsersToResetMachines": false,
"allowMultipleSessionsPerUser": false,
"deleteOrRefreshMachineAfterLogoff": "NEVER",
"refreshOsDiskAfterLogoff": "NEVER",
"refreshPeriodDaysForReplicaOsDisk": 5,
"refreshThresholdPercentageForReplicaOsDisk": 10
},
"displayProtocolSettings": {
"supportedDisplayProtocols": ["RDP","PCOIP", "BLAST" ],
"defaultDisplayProtocol": "PCOIP",
"allowUsersToChooseProtocol": true,
"pcoipDisplaySettings": {
"renderer3D": "DISABLED",
"enableGRIDvGPUs": false,
"vRamSizeMB": 96,
"maxNumberOfMonitors": 3,
"maxResolutionOfAnyOneMonitor": "WSXGA_PLUS"
},
"enableHTMLAccess": true
},
"flashSettings": {
"quality": "NO_CONTROL",
"throttling": "DISABLED"
},
"mirageConfigurationOverrides": {
"overrideGlobalSetting": false,
"enabled": false,
"url": null
}
},
"Type": "AUTOMATED",
"AutomatedDesktopSpec": {
"ProvisioningType": "VIEW_COMPOSER",
@@ -33,7 +70,7 @@
"Template": null,
"ParentVm": "Agent_pra",
"Snapshot": "kb-hotfix",
"Datacenter": null,
"Datacenter": "Dev-Dc",
"VmFolder": "Praveen",
"HostOrCluster": "CS-1",
"ResourcePool": "CS-1"
@@ -52,7 +89,8 @@
"UseNativeSnapshots": false,
"SpaceReclamationSettings": {
"ReclaimVmDiskSpace": false,
"ReclamationThresholdGB": null
"ReclamationThresholdGB": null,
"BlackoutTimes" : null
},
"PersistentDiskSettings": {
"RedirectWindowsProfile": false,
@@ -75,19 +113,31 @@
}
},
"VirtualCenterNetworkingSettings": {
"Nics": null
"Nics": [
{
"Nic": "nicName",
"NetworkLabelAssignmentSpecs": [
{
"Enabled" : false,
"networkLabel" : null,
"maxLabelType" : null,
"maxLabel" : null
}
]
}
]
}
},
"VirtualCenterManagedCommonSettings": {
"TransparentPageSharingScope": "VM"
},
"CustomizationSettings": {
"CustomizationType": "QUICK_PREP",
"DomainAdministrator": null,
"CustomizationType": "SYS_PREP",
"DomainAdministrator": "administrator",
"AdContainer": "CN=Computers",
"ReusePreExistingAccounts": false,
"NoCustomizationSettings": null,
"SysprepCustomizationSettings": null,
"SysprepCustomizationSettings": {"customizationSpec" : "praveencust"},
"QuickprepCustomizationSettings": {
"PowerOffScriptName": null,
"PowerOffScriptParameters": null,
@@ -99,7 +149,6 @@
},
"ManualDesktopSpec": null,
"RdsDesktopSpec": null,
"GlobalEntitlementData": null,
"NetBiosName" : "adviewdev",
"SysPrepName" : "praveencust"
"GlobalEntitlementData": null,
"NetBiosName" : "adviewdev"
}

View File

@@ -5,7 +5,44 @@
"AccessGroup": "ROOT",
"Description": "Manual pool creation"
},
"DesktopSettings": null,
"DesktopSettings": {
"enabled": true,
"deleting": false,
"connectionServerRestrictions": null,
"logoffSettings": {
"powerPolicy": "TAKE_NO_POWER_ACTION",
"automaticLogoffPolicy": "NEVER",
"automaticLogoffMinutes": 120,
"allowUsersToResetMachines": false,
"allowMultipleSessionsPerUser": false,
"deleteOrRefreshMachineAfterLogoff": "NEVER",
"refreshOsDiskAfterLogoff": "NEVER",
"refreshPeriodDaysForReplicaOsDisk": 5,
"refreshThresholdPercentageForReplicaOsDisk": 10
},
"displayProtocolSettings": {
"supportedDisplayProtocols": ["PCOIP", "BLAST" ],
"defaultDisplayProtocol": "BLAST",
"allowUsersToChooseProtocol": true,
"pcoipDisplaySettings": {
"renderer3D": "DISABLED",
"enableGRIDvGPUs": false,
"vRamSizeMB": 96,
"maxNumberOfMonitors": 3,
"maxResolutionOfAnyOneMonitor": "WSXGA_PLUS"
},
"enableHTMLAccess": true
},
"flashSettings": {
"quality": "NO_CONTROL",
"throttling": "DISABLED"
},
"mirageConfigurationOverrides": {
"overrideGlobalSetting": false,
"enabled": false,
"url": false
}
},
"Type": "MANUAL",
"AutomatedDesktopSpec": null,
"ManualDesktopSpec": {
@@ -16,7 +53,7 @@
"Source": "VIRTUAL_CENTER",
"Machines": [
{
"Machine" : "PowerCLI-VM"
"Machine" : "Praveen_Agent"
}
],
"VirtualCenter": null,
@@ -32,4 +69,5 @@
},
"RdsDesktopSpec": null,
"GlobalEntitlementData": null
}

View File

@@ -0,0 +1,27 @@
{
"Base": {
"Name" : "RdsJson",
"DisplayName": "TestRDSPS",
"AccessGroup": "Root",
"Description": "Testing PS"
},
"DesktopSettings": {
"enabled": true,
"deleting": false,
"connectionServerRestrictions": null,
"logoffSettings": null,
"displayProtocolSettings": null,
"flashSettings": {
"quality": "NO_CONTROL",
"throttling": "DISABLED"
},
"mirageConfigurationOverrides": null
},
"Type": "RDS",
"AutomatedDesktopSpec": null,
"ManualDesktopSpec": null,
"RdsDesktopSpec": {
"Farm": "test1"
},
"GlobalEntitlementData": null
}

View File

@@ -1,16 +0,0 @@
{
"Base": {
"Name" : "RdsJson",
"DisplayName": "TestRDSPS",
"AccessGroup": "Root",
"Description": "Testing PS"
},
"DesktopSettings": null,
"Type": "RDS",
"AutomatedDesktopSpec": null,
"ManualDesktopSpec": null,
"RdsDesktopSpec": {
"Farm": "Farm2"
},
"GlobalEntitlementData": null
}

View File

@@ -0,0 +1,20 @@
Prerequisites/Steps to use this module:
1. This module only works for Horizon product E.g. Horizon 7.0.2 and later.
2. Install the latest version of Powershell, PowerCLI(6.5) or (later version via psgallery).
3. Import HorizonView module by running: Import-Module VMware.VimAutomation.HorizonView.
4. Import "VMware.Hv.Helper" module by running: Import-Module -Name "location of this module" or Get-Module -ListAvailable 'VMware.Hv.Helper' | Import-Module.
5. Get-Command -Module "This module Name" to list all available functions or Get-Command -Module 'VMware.Hv.Helper'.
# Example script to connect view API service of Connection Server:
Import-Module VMware.VimAutomation.HorizonView
# Connection to view API service
$hvServer = Connect-HVServer -server <connection server IP/FQDN>
$hvServices = $hvserver.ExtensionData
$csList = $hvServices.ConnectionServer.ConnectionServer_List()
# Load this module
Get-Module -ListAvailable 'VMware.Hv.Helper' | Import-Module
Get-Command -Module 'VMware.Hv.Helper'
# Use advanced functions of this module
New-HVPool -spec 'path to InstantClone.json file'

View File

@@ -27,6 +27,10 @@
<TableColumnHeader>
<Width>16</Width>
<Label>User Assignment</Label>
</TableColumnHeader>
<TableColumnHeader>
<Width>8</Width>
<Label>Entitled</Label>
</TableColumnHeader>
<TableColumnHeader>
<Width>7</Width>
@@ -56,10 +60,23 @@
<TableColumnItem>
<ScriptBlock>$_.desktopSummaryData.userAssignment</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<TableColumnItem>
<ScriptBlock>
$filterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id)
$GlobalfilterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id)
Try {
$results += Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $filterContains
$results += Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $GlobalfilterContains
} Catch {
#Do nothing
}
$results.length
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>$_.desktopSummaryData.enabled</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<TableColumnItem>
<ScriptBlock>$_.desktopSummaryData.numSessions</ScriptBlock>
</TableColumnItem>
</TableColumnItems>
@@ -97,6 +114,20 @@
<ScriptBlock>$_.desktopSummaryData.userAssignment</ScriptBlock>
</ListItem>
<ListItem>
<Label>Entitled</Label>
<ScriptBlock>
$filterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id)
$GlobalfilterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id)
Try {
$results += Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $filterContains
$results += Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $GlobalfilterContains
} Catch {
#Do nothing
}
$results.length
</ScriptBlock>
</ListItem>
<ListItem>
<Label>Enabled</Label>
<ScriptBlock>$_.desktopSummaryData.enabled</ScriptBlock>
</ListItem>

View File

@@ -12,7 +12,7 @@
# RootModule = ''
# Version number of this module.
ModuleVersion = '1.0'
ModuleVersion = '1.1'
# ID used to uniquely identify this module
GUID = '6d3f7fb5-4e52-43d8-91e1-f65f72532a1d'

File diff suppressed because it is too large Load Diff

View File

@@ -274,7 +274,7 @@ Function Set-vMotionEncryptionConfig {
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$VM,
[Parameter(Mandatory=$True]
[Parameter(Mandatory=$True)]
[ValidateSet("disabled", "opportunistic", "required")]
[String]$Encryption
)

View File

@@ -0,0 +1,37 @@
<#
Script name: Test Connect-CISServer to VC.Tests.ps1
Created on: 04/20/2017
Author: Alan Renouf, @alanrenouf
Description: The purpose of this pester test is to ensure the PowerCLI modules are imported and a connection can be made to a vCenter for the CIS Service
Dependencies: Pester Module
Example run:
Invoke-Pester -Script @{ Path = '.\Test Connect-CISServer to VC.Tests.ps1'; Parameters = @{ VCNAME="VC01.local"; VCUSER="Administrator@vsphere.local"; VCPASS="Admin!23"} }
#>
$VCUSER = $Parameters.Get_Item("VCUSER")
$VCPASS = $Parameters.Get_Item("VCPASS")
$VCNAME = $Parameters.Get_Item("VCNAME")
Describe "Checking PowerCLI Cmdlets available" {
$cmdletname = "Connect-CISServer"
It "Checking $cmdletname is available" {
$command = Get-Command $cmdletname
$command | Select Name, Version
$command.Name| Should Be $cmdletname
}
}
Describe "Connect-CISServer Tests" {
$connection = Connect-CISServer $VCName -User $VCUser -password $VCPass
It "Connection is active" {
$Global:DefaultCISServers[0].isconnected | Should Be $true
}
It "Checking connected server name is $VCName" {
$Global:DefaultCISServers[0] | Select *
$Global:DefaultCISServers[0].name | Should Be $VCName
}
}

View File

@@ -0,0 +1,36 @@
<#
Script name: Test Connection to VC.ps1
Created on: 07/15/2016
Author: Alan Renouf, @alanrenouf
Description: The purpose of this pester test is to ensure the PowerCLI modules are imported and a connection can be made to a vCenter
Dependencies: Pester Module
Example run:
Invoke-Pester -Script @{ Path = '.\Test Connection to VC.Tests.ps1'; Parameters = @{ VCNAME="VC01.local"; VCUSER="Administrator@vsphere.local"; VCPASS="Admin!23"} }
#>
$VCUSER = $Parameters.Get_Item("VCUSER")
$VCPASS = $Parameters.Get_Item("VCPASS")
$VCNAME = $Parameters.Get_Item("VCNAME")
Describe "Checking PowerCLI Cmdlets available" {
$cmdletname = "Connect-VIServer"
It "Checking $cmdletname is available" {
$command = Get-Command $cmdletname
$command | Select Name, Version
$command.Name| Should Be $cmdletname
}
}
Describe "Connect-VIServer Tests" {
$connection = Connect-VIServer $VCName -User $VCUser -password $VCPass
It "Connection is active" {
$Global:DefaultVIServer[0].isconnected | Should Be $true
}
It "Checking connected server name is $VCName" {
$Global:DefaultVIServer[0].name | Should Be $VCName
}
}

View File

@@ -1,44 +0,0 @@
<#
Script name: Test Connection to VC.ps1
Created on: 07/15/2016
Author: Alan Renouf, @alanrenouf
Description: The purpose of this pester test is to ensure the PowerCLI modules are imported and a connection and disconnection can be made to a vCenter
Dependencies: Pester Module
Example run:
Invoke-Pester -Script @{ Path = '.\Test Connection to VC.ps1'; Parameters = @{ VCNAME="VC01.local"; VCUSER="Administrator@vsphere.local"; VCPASS="Admin!23"} }
#>
$VCUSER = $Parameters.Get_Item("VCUSER")
$VCPASS = $Parameters.Get_Item("VCPASS")
$VCNAME = $Parameters.Get_Item("VCNAME")
Describe "PowerCLI Tests" {
It "Importing PowerCLI Modules" {
Get-Module VMware* | Foreach {
Write-Host "Importing Module $($_.name) Version $($_.Version)"
$_ | Import-Module
Get-Module $_ | Should Be $true
}
}
}
Describe "Connect-VIServer Tests" {
$connection = Connect-VIServer $VCName -User $VCUser -password $VCPass
It "Connection is active" {
$Global:DefaultVIServer[0].isconnected | Should Be $true
}
It "Checking connected server name is $VCName" {
$Global:DefaultVIServer[0].name | Should Be $VCName
}
}
Describe "Disconnect-VIServer Tests" {
It "Disconnect from $VCName" {
Disconnect-VIServer $VCName -confirm:$false
$Global:DefaultVIServer | Should Be $null
}
}

View File

@@ -0,0 +1,49 @@
<#
Script name: Test Connect-CISService.Tests.ps1
Created on: 04/20/2017
Author: Alan Renouf, @alanrenouf
Description: The purpose of this pester test is to ensure the CIS Service cmdlet works correctly
Dependencies: Pester Module
Example run:
Invoke-Pester -Script @{ Path = '.\Test Get-CISService.ps1' }
#>
Describe "Checking PowerCLI Cmdlets available" {
$cmdletname = "Get-CISService"
It "Checking $cmdletname is available" {
$command = Get-Command $cmdletname
$command | Select Name, Version
$command.Name| Should Be $cmdletname
}
}
Describe "Get-CISService Tests for services" {
It "Checking CIS connection is active" {
$Global:DefaultCISServers[0].isconnected | Should Be $true
}
It "Checking Get-CISService returns services" {
Get-CISService | Should Be $true
}
# Checking some known services which have a Get Method
$servicestocheck = "com.vmware.appliance.system.version", "com.vmware.appliance.health.system"
Foreach ($service in $servicestocheck) {
It "Checking $service get method returns data" {
Get-CisService -Name $service | Should Be $true
(Get-CisService -Name $service).get() | Should Be $true
}
}
# Checking some known services which have a List Method
$servicestocheck = "com.vmware.vcenter.folder", "com.vmware.vcenter.vm"
Foreach ($service in $servicestocheck) {
It "Checking $service list method returns data" {
Get-CisService -Name $service | Should Be $true
(Get-CisService -Name $service).list() | Should Be $true
}
}
}

View File

@@ -0,0 +1,20 @@
<#
Script name: Test Disconnect-CISServer to VC.Tests.ps1
Created on: 04/20/2017
Author: Alan Renouf, @alanrenouf
Description: The purpose of this pester test is to ensure the Disconnect-CISServer cmdlet disconnects
Dependencies: Pester Module
Example run:
Invoke-Pester -Script @{ Path = '.\Test Disconnect-CISServer to VC.Tests.ps1'; Parameters = @{ VCNAME="VC01.local" } }
#>
$VCNAME = $Parameters.Get_Item("VCNAME")
Describe "Disconnect-CISServer Tests" {
It "Disconnect from $VCName" {
Disconnect-CISServer $VCName -confirm:$false
$Global:DefaultCISServers | Should Be $null
}
}

View File

@@ -0,0 +1,20 @@
<#
Script name: Test Disconnect-VIServer to VC.ps1
Created on: 04/20/2017
Author: Alan Renouf, @alanrenouf
Description: The purpose of this pester test is to ensure the Disconnect-VIServer cmdlet disconnects
Dependencies: Pester Module
Example run:
Invoke-Pester -Script @{ Path = '.\Test Disconnect-VISServer to VC.ps1'; Parameters = @{ VCNAME="VC01.local" } }
#>
$VCNAME = $Parameters.Get_Item("VCNAME")
Describe "Disconnect-VIServer Tests" {
It "Disconnect from $VCName" {
Disconnect-VIServer $VCName -confirm:$false
$Global:DefaultVIServer | Should Be $null
}
}

View File

@@ -0,0 +1,38 @@
<#
.NOTES
Script name: Horizon-UsageStats.ps1
Author: Ray Heffer, @rayheffer
Last Edited on: 04/18/2017
Dependencies: PowerCLI 6.5 R1 or later, Horizon 7.0.2 or later
.DESCRIPTION
This is a sample script that retrieves the Horizon usage statistics. This produces the same metrics as listed under View Configuration > Product Licensing and Usage. Service providers can use this script or incorporate it with their existing scripts to automate the reporting of Horizon usage.
Example Output:
NumConnections : 180
NumConnectionsHigh : 250
NumViewComposerConnections : 0
NumViewComposerConnectionsHigh : 0
NumTunneledSessions : 0
NumPSGSessions : 180
#>
# User Configuration
$hzUser = "Administrator"
$hzPass = "VMware1!"
$hzDomain = "vmw.lab"
$hzConn = "connect01.vmw.lab"
# Import the Horizon module
Import-Module VMware.VimAutomation.HorizonView
# Establish connection to Connection Server
$hvServer = Connect-HVServer -server $hzConn -User $hzUser -Password $hzPass -Domain $hzDomain
# Assign a variable to obtain the API Extension Data
$hvServices = $Global:DefaultHVServers.ExtensionData
# Retrieve Connection Server Health metrics
$hvHealth =$hvServices.ConnectionServerHealth.ConnectionServerHealth_List()
# Display ConnectionData (Usage stats)
$hvHealth.ConnectionData

27
Scripts/NVME Info.ps1 Normal file
View File

@@ -0,0 +1,27 @@
<#
.NOTES
===========================================================================
Created by: Alan Renouf
Organization: VMware
Blog: http://virtu-al.net
Twitter: @alanrenouf
===========================================================================
#>
Foreach ($vmhost in Get-VMHost) {
$esxcli = get-esxcli -V2 -vmhost $vmhost
Write-Host "Host: $($vmhost.name)" -ForegroundColor Green
$devices = $esxcli.nvme.device.list.Invoke()
Foreach ($device in $devices) {
$nvmedevice = $esxcli.nvme.device.get.CreateArgs()
$nvmedevice.adapter = $device.HBAName
$esxcli.nvme.device.get.invoke($nvmedevice) | Select-Object ModelNumber, FirmwareRevision
$features = $esxcli.nvme.device.feature.ChildElements | Select-object -ExpandProperty name
ForEach ($feature in $features){
Write-Host "Feature: $feature" -ForegroundColor Yellow
$currentfeature = $esxcli.nvme.device.feature.$feature.get.CreateArgs()
$currentfeature.adapter = $device.HBAName
$esxcli.nvme.device.feature.$feature.get.Invoke($currentfeature)
}
}
}

View File

@@ -0,0 +1,103 @@
<#
.SYNOPSIS
Set a given LUN ID to Perennially Reserved.
.DESCRIPTION
A description of the file.
.PARAMETER vCenter
Set vCenter server to connect to
.PARAMETER Username
Set username to use
.PARAMETER Password
Set password to be used
.PARAMETER VirtualMachine
Name of the virtual machine which has the RDM
.NOTES
===========================================================================
Created on: 20/03/2017 15:05
Created by: Alessio Rocchi <arocchi@vmware.com>
Organization: VMware
Filename: SetLunReservation.ps1
===========================================================================
#>
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
Position = 0)]
[ValidateNotNullOrEmpty()]
[String]$vCenter,
[Parameter(Mandatory = $false,
ValueFromPipeline = $true,
HelpMessage = 'Set vCenter Username')]
[AllowNull()]
[String]$Username,
[Parameter(Mandatory = $false,
ValueFromPipeline = $true,
HelpMessage = 'Set vCenterPassword')]
[AllowNull()]
[String]$Password,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[String]$VirtualMachine
)
Import-Module -Name VMware.VimAutomation.Core -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
try
{
if ([String]::IsNullOrEmpty($Username) -or [String]::IsNullOrEmpty($Password))
{
$vcCredential = Get-Credential
Connect-VIServer -Server $vCenter -Credential $vcCredential -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
}
else
{
Connect-VIServer -Server $vCenter -User $Username -Password $Password -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
}
}
catch
{
Write-Error("Error connecting to vCenter: {0}" -f $vCenter)
exit
}
$rDms = Get-HardDisk -DiskType rawPhysical -Vm (Get-VM -Name $VirtualMachine)
$clusterHosts = Get-Cluster -VM $VirtualMachine | Get-VMHost
$menu = @{ }
for ($i = 1; $i -le $rDms.count; $i++)
{
Write-Host("{0}) {1}[{2}]: {3}" -f ($i, $rDms[$i - 1].Name, $rDms[$i - 1].CapacityGB, $rDms[$i - 1].ScsiCanonicalName))
$menu.Add($i, ($rDms[$i - 1].ScsiCanonicalName))
}
[int]$ans = Read-Host 'Which Disk you want to configure?'
$selection = $menu.Item($ans)
write-host("Choosed Disk: {0}" -f $selection)
$current = 0
foreach ($vmHost in $clusterHosts)
{
Write-Progress -Activity "Processing Cluster." -CurrentOperation $vmHost.Name -PercentComplete (($counter / $clusterHosts.count) * 100)
$esxcli = Get-EsxCli -V2 -VMHost $vmHost
$deviceListArgs = $esxcli.storage.core.device.list.CreateArgs()
$deviceListArgs.device = $selection
$esxcli.storage.core.device.list.Invoke($deviceListArgs) | Select-Object Device, IsPerenniallyReserved
$deviceSetArgs = $esxcli.storage.core.device.setconfig.CreateArgs()
$deviceSetArgs.device = $selection
$deviceSetArgs.perenniallyreserved = $true
$esxcli.storage.core.device.setconfig.Invoke($deviceSetArgs)
$counter++
}
Disconnect-VIServer -WarningAction SilentlyContinue -Server $vCenter -Force -Confirm:$false

View File

@@ -0,0 +1,59 @@
Function Get-VSANSmartsData {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
This function retreives SMART drive data using new vSAN
Management 6.6 API. This can also be used outside of vSAN
to query existing SSD devices not being used for vSAN.
.PARAMETER Cluster
The name of a vSAN Cluster
.EXAMPLE
Get-VSANSmartsData -Cluster VSAN-Cluster
#>
param(
[Parameter(Mandatory=$false)][String]$Cluster
)
if($global:DefaultVIServer.ExtensionData.Content.About.ApiType -eq "VirtualCenter") {
if(!$cluster) {
Write-Host "Cluster property is required when connecting to vCenter Server"
break
}
$vchs = Get-VSANView -Id "VsanVcClusterHealthSystem-vsan-cluster-health-system"
$cluster_view = (Get-Cluster -Name $Cluster).ExtensionData.MoRef
$result = $vchs.VsanQueryVcClusterSmartStatsSummary($cluster_view)
} else {
$vhs = Get-VSANView -Id "HostVsanHealthSystem-ha-vsan-health-system"
$result = $vhs.VsanHostQuerySmartStats($null,$true)
}
$vmhost = $result.Hostname
$smartsData = $result.SmartStats
Write-Host "`nESXi Host: $vmhost`n"
foreach ($data in $smartsData) {
if($data.stats) {
$stats = $data.stats
Write-Host $data.disk
$smartsResults = @()
foreach ($stat in $stats) {
$statResult = [pscustomobject] @{
Parameter = $stat.Parameter;
Value =$stat.Value;
Threshold = $stat.Threshold;
Worst = $stat.Worst
}
$smartsResults+=$statResult
}
$smartsResults | Format-Table
}
}
}

26
Scripts/VSANVersion.ps1 Normal file
View File

@@ -0,0 +1,26 @@
Function Get-VSANVersion {
<#
.NOTES
===========================================================================
Created by: William Lam
Organization: VMware
Blog: www.virtuallyghetto.com
Twitter: @lamw
===========================================================================
.DESCRIPTION
This function retreives the vSAN software version for both VC/ESXi
.PARAMETER Cluster
The name of a vSAN Cluster
.EXAMPLE
Get-VSANVersion -Cluster VSAN-Cluster
#>
param(
[Parameter(Mandatory=$true)][String]$Cluster
)
$vchs = Get-VSANView -Id "VsanVcClusterHealthSystem-vsan-cluster-health-system"
$cluster_view = (Get-Cluster -Name $Cluster).ExtensionData.MoRef
$results = $vchs.VsanVcClusterQueryVerifyHealthSystemVersions($cluster_view)
Write-Host "`nVC Version:"$results.VcVersion
$results.HostResults | Select Hostname, Version
}

View File

@@ -0,0 +1,97 @@
<#
Script name: esxi-image-comparator.ps1
Last update: 24 May 2017
Author: Eric Gray, @eric_gray
Description: Compare contents (VIBs) of multiple VMware ESXi image profiles.
Dependencies: PowerCLI Image Builder (VMware.ImageBuilder,VMware.VimAutomation.Core)
#>
param(
[switch]$ShowAllVIBs=$false,
[switch]$HideDates=$false,
[switch]$Interactive=$false,
[switch]$Grid=$false,
[string]$ProfileInclude,
[string]$ProfileExclude
)
$profileList = Get-EsxImageProfile | sort -Property Name
if ($ProfileInclude) {
$profileList = $profileList | ? Name -Match $ProfileInclude
}
if ($ProfileExclude) {
$profileList = $profileList | ? Name -NotMatch $ProfileExclude
}
if ($profileList.Count -eq 0) {
Write-Host "No ESXi image profiles available in current session."
Write-Host "Use Add-EsxSoftwareDepot for each depot zip bundle you would like to compare."
exit 1
}
if ($Interactive) {
$keep = @()
Write-Host "Found the following profiles:" -ForegroundColor Yellow
$profileList | % { write-host $_.Name }
if ($profileList.Count -gt 7) {
Write-Host "Found $($profileList.Count) profiles!" -ForegroundColor Yellow
Write-Host "Note: List filtering is possible through -ProfileInclude / -ProfileExclude" -ForegroundColor DarkGreen
}
write-host "`nType 'y' next to each profile to compare..." -ForegroundColor Yellow
foreach ($profile in $profileList) {
$want = Read-Host -Prompt $profile.Name
if ($want.StartsWith("y") ) {
$keep += $profile
}
}
$profileList = $keep
}
# go thru each profile and build a hash of the vib name and hash of profile name + version
$diffResults = @{}
foreach ($profile in $profileList ) {
foreach ($vib in $profile.VibList) {
$vibValue = $vib.Version
if (! $HideDates) {
$vibValue += " "+ $vib.CreationDate.ToShortDateString()
}
$diffResults.($vib.name) += @{$profile.name = $vibValue}
}
}
# create an object that will neatly output as CSV or table
$outputTable=@()
foreach ($row in $diffResults.keys | sort) {
$vibRow = new-object PSObject
$vibRow | add-member -membertype NoteProperty -name "VIB" -Value $row
$valueCounter = @{}
foreach ($profileName in $profileList.name) {
#populate this hash to decide if all profiles have same version of VIB
$valueCounter.($diffResults.$row.$profileName) = 1
$vibRow | add-member -membertype NoteProperty -name $profileName -Value $diffResults.$row.$profileName
}
if ($valueCounter.Count -gt 1 -or $ShowAllVIBs) {
$outputTable += $vibRow
}
}
# useful for debugging
#$diffResults | ConvertTo-Json
#$outputTable|Export-Csv -Path .\image-diff-results.csv -NoTypeInformation
if ($Grid) {
$outputTable | Out-GridView -Title "VMware ESXi Image Profile Comparator"
} else {
$outputTable
}

View File

@@ -0,0 +1,108 @@
<#
Script name: esxi-image-creator.ps1
Last update: 24 May 2017
Author: Eric Gray, @eric_gray
Description: Create a VMware ESXi image profile based on
one or more depots and offline driver bundles.
Dependencies: PowerCLI Image Builder (VMware.ImageBuilder,VMware.VimAutomation.Core)
#>
param(
[switch]$NewestDate = $false,
[switch]$WriteZip = $false,
[switch]$WriteISO = $false,
[switch]$LeaveCurrentDepotsMounted = $false,
[string]$NewProfileName = "Custom Image $(Get-Date -Format "yyyyMMddhhmm")",
[ValidateNotNullOrEmpty()]
[ValidateSet('VMwareCertified','VMwareAccepted','PartnerSupported','CommunitySupported')]
[string]$Acceptance = "VMwareCertified",
[string[]]$Files = "*.zip"
)
#### Specify optional image fine-tuning here ####
# comma-separated list (array) of VIBs to exclude
$removeVibs = @("tools-light")
# force specific VIB version to be included, when more than one version is present
# e.g. "net-enic"="2.1.2.71-1OEM.550.0.0.1331820"
$overrideVibs = @{
# "net-enic"="2.1.2.71-1OEM.550.0.0.1331820",
}
#### end of optional fine-tuning ####
# may be desirable to manually mount an online depot in advance, such as for HPE
# e.g. Add-EsxSoftwareDepot http://vibsdepot.hpe.com/index-ecli-650.xml
if (! $LeaveCurrentDepotsMounted) {
Get-EsxSoftwareDepot | Remove-EsxSoftwareDepot
}
foreach ($depot in Get-ChildItem $Files) {
if ($depot.Name.EndsWith(".zip") ) {
Add-EsxSoftwareDepot $depot.FullName
} else {
Write-Host "Not a zip depot:" $depot.Name
}
}
if ((Get-EsxImageProfile).count -eq 0) {
write-host "No image profiles found in the selected files"
exit 1
}
# either use the native -Newest switch, or try to find latest VIBs by date (NewestDate)
if ($NewestDate) {
$pkgsAll = Get-EsxSoftwarePackage | sort -Property Name,CreationDate -Descending
$pkgsNewestDate=@()
foreach ($pkg in $pkgsAll) {
if ($pkgsNewestDate.GetEnumerator().name -notcontains $pkg.Name ) {
$pkgsNewestDate += $pkg
}
}
$pkgs = $pkgsNewestDate
} else {
$pkgs = Get-ESXSoftwarePackage -Newest
}
# rebuild the package array according to manual fine-tuning
if ($removeVibs) {
Write-Host "`nThe following VIBs will not be included in ${NewProfileName}:" -ForegroundColor Yellow
$removeVibs
$pkgs = $pkgs | ? name -NotIn $removeVibs
}
foreach ($override in $overrideVibs.keys) {
# check that the override exists, then remove existing and add override
$tmpOver = Get-EsxSoftwarePackage -Name $override -Version $overrideVibs.$override
if ($tmpOver) {
$pkgs = $pkgs | ? name -NotIn $tmpOver.name
$pkgs += $tmpOver
} else {
Write-host "Did not find:" $override $overrideVibs.$override -ForegroundColor Yellow
}
}
try {
New-EsxImageProfile -NewProfile $NewProfileName -SoftwarePackage $pkgs `
-Vendor Custom -AcceptanceLevel $Acceptance -Description "Made with esxi-image-creator.ps1" `
-ErrorAction Stop -ErrorVariable CreationError | Out-Null
}
catch {
Write-Host "Custom image profile $NewProfileName not created." -ForegroundColor Yellow
$CreationError
exit 1
}
Write-Host "`nFinished creating $NewProfileName" -ForegroundColor Yellow
if ($WriteZip) {
Write-Host "Creating zip bundle..." -ForegroundColor Green
Export-EsxImageProfile -ImageProfile $NewProfileName -ExportToBundle -FilePath .\${NewProfileName}.zip -Force
}
if ($WriteISO) {
Write-Host "Creating ISO image..." -ForegroundColor Green
Export-EsxImageProfile -ImageProfile $NewProfileName -ExportToIso -FilePath .\${NewProfileName}.iso -Force
}

6
Scripts/modules.sh Normal file
View File

@@ -0,0 +1,6 @@
#!/bin/bash
for file in $( ls /powershell/PowerCLI-Example-Scripts/Modules/ )
do
mkdir "/root/.local/share/powershell/Modules/${file%.*}/"
mv "/powershell/PowerCLI-Example-Scripts/Modules/$file" "/root/.local/share/powershell/Modules/${file%.*}/$file"
done

198
SetDatastoreTag.ps1 Executable file
View File

@@ -0,0 +1,198 @@
<#
.SYNOPSIS
A brief description of the file.
.DESCRIPTION
Given a list of Datastore Names, this script will assign a Tag to them
.PARAMETER csvFile
String representing the full path of the file
The file must be structured like this:
-----------------------------
Tag1,Tag2,Tag3,Tag4
IPv4-iSCSI-SiteA,Tag1,Tag3
IPv4-NFS-SiteA,Tag2,Tag4
...
-----------------------------
.NOTES
===========================================================================
Created on: 31/03/2017 11:16
Created by: Alessio Rocchi <arocchi@vmware.com>
Organization: VMware
Filename: SetDatastoreTag.ps1
===========================================================================
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[System.String]$csvFile,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[String]$vCenter,
[Parameter(ValueFromPipeline = $true,
Position = 2)]
[AllowNull()]
[String]$Username,
[Parameter(Position = 3)]
[AllowNull()]
[String]$Password
)
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
class vcConnector : System.IDisposable
{
[String]$Username
[String]$Password
[String]$vCenter
[PSObject]$server
static [vcConnector]$instance
vcConnector($Username, $Password, $vCenter)
{
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
$this.Username = $Username
$this.Password = $Password
$this.vCenter = $vCenter
$this.connect()
}
vcConnector($vcCredential, $vCenter)
{
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null
$this.vcCredential = $vcCredential
$this.vCenter = $vCenter
$this.connect()
}
[void] hidden connect()
{
try
{
if ([String]::IsNullOrEmpty($this.Username) -or [String]::IsNullOrEmpty($this.Password))
{
$vcCredential = Get-Credential
Connect-VIServer -Server $this.vCenter -Credential $this.vcCredential -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
}
else
{
Connect-VIServer -Server $this.vCenter -User $this.Username -Password $this.Password -WarningAction SilentlyContinue -ErrorAction Stop
}
Write-Debug("Connected to vCenter: {0}" -f $this.vCenter)
}
catch
{
Write-Error($Error[0].Exception.Message)
exit
}
}
[void] Dispose()
{
Write-Debug("Called Dispose Method of Instance: {0}" -f ($this))
Disconnect-VIServer -WarningAction SilentlyContinue -Server $this.vCenter -Force -Confirm:$false | Out-Null
}
static [vcConnector] GetInstance()
{
if ([vcConnector]::instance -eq $null)
{
[vcConnector]::instance = [vcConnector]::new()
}
return [vcConnector]::instance
}
}
class Content{
[System.Collections.Generic.List[System.String]]$availableTags
[System.Collections.Generic.List[System.String]]$elements
Content()
{
}
Content([String]$filePath)
{
if ((Test-Path -Path $filePath) -eq $false)
{
throw ("Cannot find file: {0}" -f ($filePath))
}
try
{
# Cast the Get-Content return type to Generic List of Strings in order to avoid fixed-size array
$this.elements = [System.Collections.Generic.List[System.String]](Get-Content -Path $filePath -ea SilentlyContinue -wa SilentlyContinue)
$this.availableTags = $this.elements[0].split(',')
# Delete the first element aka availableTags
$this.elements.RemoveAt(0)
}
catch
{
throw ("Error reading the file: {0}" -f ($filePath))
}
}
}
try
{
$vc = [vcConnector]::new($Username, $Password, $vCenter)
$csvContent = [Content]::new($csvFile)
Write-Host("Available Tags: {0}" -f ($csvContent.availableTags))
foreach ($element in $csvContent.elements)
{
[System.Collections.Generic.List[System.String]]$splittedList = $element.split(',')
# Get the Datastore Name
[System.String]$datastoreName = $splittedList[0]
# Removing Datastore Name
$splittedList.RemoveAt(0)
# Create a List of Tags which will be assigned to the Datastore
[System.Collections.Generic.List[PSObject]]$tagsToAssign = $splittedList | ForEach-Object { Get-Tag -Name $_ }
Write-Host("Tags to assign to Datastore: {0} are: {1}" -f ($datastoreName, $tagsToAssign))
# Get Datastore object by the given Datastore Name, first field of the the line
$datastore = Get-Datastore -Name $datastoreName -ea Stop
# Iterate the assigned Datastore Tags
foreach ($tag in ($datastore | Get-TagAssignment))
{
# Check if the current tag is one of the available ones.
if ($tag.Tag.Name -in $csvContent.availableTags)
{
# Remove the current assigned Tag
Write-Host("Removing Tag: {0}" -f ($tag))
Remove-TagAssignment -TagAssignment $tag -Confirm:$false
}
}
# Finally add the new set of tags to the Datastore
foreach ($tag in $tagsToAssign)
{
Write-Host("Trying to assign Tag: {0} to Datastore: {1}" -f ($tag.Name, $datastoreName))
# Assign the Tag
New-TagAssignment -Entity $datastore -Tag $tag
}
}
}
catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.VimException]
{
Write-Error("VIException: {0}" -f ($Error[0].Exception.Message))
exit
}
catch
{
Write-Error $Error[0].Exception.Message
exit
}
finally
{
# Let be assured that the vc connection will be disposed.
$vc.Dispose()
}