diff --git a/Modules/Get-VMmaxIOPS.psm1 b/Modules/Get-VMmaxIOPS.psm1 new file mode 100644 index 0000000..27af1ad --- /dev/null +++ b/Modules/Get-VMmaxIOPS.psm1 @@ -0,0 +1,114 @@ +function Get-VMmaxIOPS { +<# + .NOTES + =========================================================================== + Created by: Markus Kraus + Twitter: @VMarkus_K + Private Blog: mycloudrevolution.com + =========================================================================== + Changelog: + 2016.10 ver 1.0 Base Release + 2016.11 ver 1.1 Added vSphere 6.5 Support, New Counters, More Error Handling + =========================================================================== + External Code Sources: + http://www.lucd.info/2011/04/22/get-the-maximum-iops/ + https://communities.vmware.com/thread/485386 + =========================================================================== + Tested Against Environment: + vSphere Version: 5.5 U2, 6.5 + PowerCLI Version: PowerCLI 6.3 R1, 6.5 R1 + PowerShell Version: 4.0, 5.0 + OS Version: Windows 8.1, Windows Server 2012 R2 + =========================================================================== + Keywords vSphere, ESXi, VM, Storage + =========================================================================== + + .DESCRIPTION + This Function will Create a VM Disk IOPS Report + + .Example + Get-VM TST* | Get-VMmaxIOPS -Minutes 60 | FT -Autosize + + .Example + $SampleVMs = Get-VM "TST*" + Get-VMmaxIOPS -VMs $SampleVMs -Minutes 60 + + .PARAMETER VMs + Specify the VMs + + .PARAMETER Minutes + Specify the Minutes to report (10080 is one Week) + +#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=$True, Position=0)] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl[]] $VMs, + [Parameter(Mandatory=$false, Position=1, HelpMessage = "Specify the Minutes to report (10080 is one Week)")] + [ValidateNotNullorEmpty()] + [int] $Minutes = 30 +) +Begin { + # none + } +Process { + if ($_.PowerState -eq "PoweredOn") { + #region: Global Definitions + [int]$TimeRange = "-" + $Minutes + #endregion + + #region: Creating VM Stats + Write-Verbose "$(Get-Date -Format G) Create VM Stats..." + $VMMetrics = "virtualdisk.numberwriteaveraged.average","virtualdisk.numberreadaveraged.average" + $Start = (Get-Date).AddMinutes($TimeRange) + $stats = Get-Stat -Realtime -Stat $VMMetrics -Entity $VMs -Start $Start -Verbose:$False + Write-Verbose "$(Get-Date -Format G) Create VM Stats completed" + #endregion + + #region: Creating HD-Tab + Write-Verbose "$(Get-Date -Format G) Create HD Tab..." + $hdTab = @{} + foreach($hd in (Get-Harddisk -VM $VMs)){ + $controllerKey = $hd.Extensiondata.ControllerKey + $controller = $hd.Parent.Extensiondata.Config.Hardware.Device | where{$_.Key -eq $controllerKey} + $hdTab[$hd.Parent.Name + "/scsi" + $controller.BusNumber + ":" + $hd.Extensiondata.UnitNumber] = $hd.FileName.Split(']')[0].TrimStart('[') + } + Write-Verbose "$(Get-Date -Format G) Create HD Tab completed" + #endregion + + #region: Creating Reports + Write-Verbose "$(Get-Date -Format G) Create Report..." + $reportPerf = @() + $reportPerf = $stats | Group-Object -Property {$_.Entity.Name},Instance | %{ + New-Object PSObject -Property @{ + VM = $_.Values[0] + Disk = $_.Values[1] + IOPSWriteAvg = [math]::round( ($_.Group | ` + where{$_.MetricId -eq "virtualdisk.numberwriteaveraged.average"} | ` + Measure-Object -Property Value -Average).Average,2) + IOPSReadAvg = [math]::round( ($_.Group | ` + where{$_.MetricId -eq "virtualdisk.numberreadaveraged.average"} | ` + Measure-Object -Property Value -Average).Average,2) + Datastore = $hdTab[$_.Values[0] + "/"+ $_.Values[1]] + } + } + Write-Verbose "$(Get-Date -Format G) Create Report completed" + #endregion + + + } + Else { + Write-Error "VM $($_.Name) is Powered Off! Processing Skipped" + } + $reportPerf | Select-Object VM, Disk, Datastore, IOPSWriteAvg, IOPSReadAvg + } + +End { + # none + } + +} \ No newline at end of file diff --git a/Modules/Recommend-Sizing.psm1 b/Modules/Recommend-Sizing.psm1 index db01181..0075e43 100644 --- a/Modules/Recommend-Sizing.psm1 +++ b/Modules/Recommend-Sizing.psm1 @@ -8,14 +8,15 @@ function Recommend-Sizing { =========================================================================== Changelog: 2016.11 ver 1.0 Base Release - 2016.11 ver 1.1 Optional Stats Collection. + 2016.11 ver 1.1 Optional Stats Collection + 2016.11 ver 1.2 VM Stats from Realtime Data and new Counters =========================================================================== External Code Sources: http://www.lucd.info/2011/04/22/get-the-maximum-iops/ https://communities.vmware.com/thread/485386 =========================================================================== Tested Against Environment: - vSphere Version: 5.5 U2 + vSphere Version: 5.5 U2, 6.0 PowerCLI Version: PowerCLI 6.3 R1, PowerCLI 6.5 R1 PowerShell Version: 4.0, 5.0 OS Version: Windows 8.1, Server 2012 R2 @@ -24,7 +25,7 @@ function Recommend-Sizing { =========================================================================== .DESCRIPTION - This Function collects Basic vSphere Informations for a Hardware Sizing Recomamndation. Focus is in Compute Ressources. + This Function collects Basic vSphere Informations for a Hardware Sizing Recommandation. Focus is in Compute Ressources. .Example Recommend-Sizing -ClusterNames Cluster01, Cluster02 -Stats -StatsRange 60 -Verbose @@ -41,7 +42,7 @@ function Recommend-Sizing { .PARAMETER Stats Enables Stats Collection. - Warning: At the moment this is only tested and supported with vSphere 5.5! + Warning: At the moment this is only fully tested with vSphere 5.5 and vSphere 6.5! .PARAMETER StatsRange Time Range in Minutes for the Stats Collection. @@ -55,15 +56,15 @@ function Recommend-Sizing { param( [Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0)] [Array] $ClusterNames, - [Parameter(Mandatory=$False, ValueFromPipeline=$False, Position=2)] + [Parameter(Mandatory=$False, ValueFromPipeline=$False, Position=1, ParameterSetName = "Stats")] [switch] $Stats, - [Parameter(Mandatory=$False, ValueFromPipeline=$False, Position=2)] + [Parameter(Mandatory=$False, ValueFromPipeline=$False, Position=2, ParameterSetName = "Stats")] [int] $StatsRange = 1440 ) Begin { if ($Stats) { - Write-Warning "Stats Collection enabled.`nAt the moment this is only tested and supported with vSphere 5.5" + Write-Warning "Stats Collection requested.`nAt the moment this is only fully tested with vSphere 5.5 and vSphere 6.5" [int]$TimeRange = "-" + $StatsRange } @@ -121,30 +122,38 @@ Process { #endregion if ($Stats) { - #region: Creating Disk Metrics - Write-Verbose "$(Get-Date -Format G) Create $($Cluster.name) IOPS Metrics..." - $DiskMetrics = "virtualDisk.numberReadAveraged.average","virtualDisk.numberWriteAveraged.average" - $start = (Get-Date).AddMinutes($TimeRange) - $DiskStats = Get-Stat -Stat $DiskMetrics -Entity $ClusterVMsPoweredOn -Start $start -Verbose:$False - Write-Verbose "$(Get-Date -Format G) Create $($Cluster.name) IOPS Metrics completed" + #region: Creating VM Stats + Write-Verbose "$(Get-Date -Format G) Create $($Cluster.name) VM Stats..." + $VMMetrics = "disk.numberwrite.summation","disk.numberread.summation","cpu.usage.average", "mem.usage.average" + $Start = (Get-Date).AddMinutes($TimeRange) + $VMStats = Get-Stat -Realtime -Stat $VMMetrics -Entity $ClusterVMsPoweredOn -Start $Start -Verbose:$False + Write-Verbose "$(Get-Date -Format G) Create $($Cluster.name) VM Stats completed" #endregion - #region: Creating IOPS Reports - Write-Verbose "$(Get-Date -Format G) Process $($Cluster.name) IOPS Report..." - $reportDiskPerf = @() - $reportDiskPerf = $DiskStats | Group-Object -Property {$_.Entity.Name},Instance | %{ - New-Object PSObject -Property @{ - IOPSMax = ($_.Group | ` - Group-Object -Property Timestamp | ` - %{$_.Group[0].Value + $_.Group[1].Value} | ` - Measure-Object -Maximum).Maximum + #region: Creating VM Stats Report + Write-Verbose "$(Get-Date -Format G) Process $($Cluster.name) VM Stats Report..." + $ReportVMPerf = @() + $ReportVMPerf = $VMStats | Group-Object -Property {$_.Entity.Name},Instance | %{ + New-Object PSObject -Property @{ + IOPSWriteAvg = ($_.Group | ` + where{$_.MetricId -eq "disk.numberwrite.summation"} | ` + Measure-Object -Property Value -Average).Average + IOPSReadAvg = ($_.Group | ` + where{$_.MetricId -eq "disk.numberread.summation"} | ` + Measure-Object -Property Value -Average).Average + CPUUsageAvg = ($_.Group | ` + where{$_.MetricId -eq "cpu.usage.average"} | ` + Measure-Object -Property Value -Average).Average + MEMUsageAvg = ($_.Group | ` + where{$_.MetricId -eq "mem.usage.average"} | ` + Measure-Object -Property Value -Average).Average } } - Write-Verbose "$(Get-Date -Format G) Process $($Cluster.name) IOPS Report completed" + Write-Verbose "$(Get-Date -Format G) Process $($Cluster.name) VM Stats Report completed" #endregion } else { - Write-Verbose "$(Get-Date -Format G) Stats Cellocetion skipped..." + Write-Verbose "$(Get-Date -Format G) Stats Collection skipped..." } #region: Create VM Disk Space Report @@ -194,8 +203,10 @@ Process { SumVMDiskSpaceGB = [math]::round( ($reportDiskSpace | Measure-Object -Sum -Property CapacityGB).sum, 1 ) SumDatastoreSpaceGB = [math]::round( ($DatastoreReport | Measure-Object -Sum -Property CapacityGB).sum, 1 ) SumDatastoreUsedSpaceGB = [math]::round( ($DatastoreReport | Measure-Object -Sum -Property UsedSpaceGB).sum, 1 ) - SumMaxVMIOPS = [math]::round( ($reportDiskPerf | Measure-Object -Sum -Property IOPSMax).sum, 1 ) - AverageMaxVMIOPs = [math]::round( ($reportDiskPerf | Measure-Object -Average -Property IOPSMax).Average,1 ) + AverageVMIOPSWriteAvg = [math]::round( ($ReportVMPerf | Measure-Object -Average -Property IOPSWriteAvg).Average,1 ) + AverageVMIOPSReadAvg = [math]::round( ($ReportVMPerf | Measure-Object -Average -Property IOPSReadAvg).Average,1 ) + AverageVMCPUUsageAvg = "$([math]::round( ($ReportVMPerf | Measure-Object -Average -Property CPUUsageAvg).Average,1 )) %" + AverageVMMEMUsageAvg = "$([math]::round( ($ReportVMPerf | Measure-Object -Average -Property MEMUsageAvg).Average,1 )) %" } $MyView += $SizingReport Write-Verbose "$(Get-Date -Format G) Process Global Report completed" diff --git a/Modules/Set-CBT.psm1 b/Modules/Set-CBT.psm1 new file mode 100644 index 0000000..784aebb --- /dev/null +++ b/Modules/Set-CBT.psm1 @@ -0,0 +1,111 @@ +function Set-CBT { +<# + .NOTES + =========================================================================== + Created by: Markus Kraus + Twitter: @VMarkus_K + Private Blog: mycloudrevolution.com + =========================================================================== + Changelog: + 2016.11 ver 1.0 Base Release + =========================================================================== + External Code Sources: + http://wahlnetwork.com/2015/12/01/change-block-tracking-cbt-powercli/ + =========================================================================== + Tested Against Environment: + vSphere Version: 5.5 U2 + PowerCLI Version: PowerCLI 6.3 R1 + PowerShell Version: 4.0 + OS Version: Windows Server 2012 R2 + =========================================================================== + Keywords vSphere, ESXi, VM, Storage, CBT, Backup + =========================================================================== + + .DESCRIPTION + This Function enables or disables CBT. + + .Example + Get-VN TST* | Set-CBT -DisableCBT + + .Example + Get-VN TST* | Set-CBT -EnableCBT + + .PARAMETER DisableCBT + Disables CBT for any VMs found with it enabled + + .PARAMETER EnableCBT + Enables CBT for any VMs found with it disabled + +#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=$True, Position=0, HelpMessage = "VMs to process")] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl[]] $myVMs, + [Parameter(Mandatory = $False,ValueFromPipeline=$False, Position = 1, HelpMessage = "Enables CBT for any VMs found with it disabled", ParameterSetName = "EnableCBT")] + [ValidateNotNullorEmpty()] + [Switch]$EnableCBT, + [Parameter(Mandatory = $False,ValueFromPipeline=$False, Position = 1, HelpMessage = "Disables CBT for any VMs found with it enabled", ParameterSetName = "DisableCBT")] + [ValidateNotNullorEmpty()] + [Switch]$DisableCBT + ) +Process { + + $vmconfigspec = New-Object -TypeName VMware.Vim.VirtualMachineConfigSpec + Write-Verbose -Message "Walking through given VMs" + foreach($myVM in $myVMs) + { + if ($DisableCBT -and $myVM.ExtensionData.Config.ChangeTrackingEnabled -eq $true -and $myVM.ExtensionData.Snapshot -eq $null) + { + try + { + Write-Verbose -Message "Reconfiguring $($myVM.name) to disable CBT" -Verbose + $vmconfigspec.ChangeTrackingEnabled = $false + $myVM.ExtensionData.ReconfigVM($vmconfigspec) + + if ($myVM.PowerState -eq "PoweredOn" ) { + Write-Verbose -Message "Creating a snapshot on $($myVM.name) to clear CBT file" -Verbose + $SnapShot = New-Snapshot -VM $myVM -Name "CBT Cleanup" + + Write-Verbose -Message "Removing snapshot on $($myVM.name)" -Verbose + $SnapShot| Remove-Snapshot -Confirm:$false + } + + } + catch + { + throw $myVM + } + } + elseif ($EnableCBT -and $myVM.ExtensionData.Config.ChangeTrackingEnabled -eq $false -and $myVM.ExtensionData.Snapshot -eq $null) + { + Write-Verbose -Message "Reconfiguring $($myVM.name) to enable CBT" -Verbose + $vmconfigspec.ChangeTrackingEnabled = $true + $myVM.ExtensionData.ReconfigVM($vmconfigspec) + + if ($myVM.PowerState -eq "PoweredOn" ) { + Write-Verbose -Message "Creating a snapshot on $($myVM.name) to Create CBT file" -Verbose + $SnapShot = New-Snapshot -VM $myVM -Name "CBT Cleanup" + + Write-Verbose -Message "Removing snapshot on $($myVM.name)" -Verbose + $SnapShot | Remove-Snapshot -Confirm:$false + } + } + else + { + if ($myVM.ExtensionData.Snapshot -ne $null -and $EnableCBT) + { + Write-Warning -Message "Skipping $($myVM.name) - Snapshots found" + } + elseif ($myVM.ExtensionData.Snapshot -ne $null -and $DisableCBT) + { + Write-Warning -Message "Skipping $($myVM.name) - Snapshots found" + } + } + } + + } +} diff --git a/Modules/Start-UNMAP.psm1 b/Modules/Start-UNMAP.psm1 new file mode 100644 index 0000000..a8e9896 --- /dev/null +++ b/Modules/Start-UNMAP.psm1 @@ -0,0 +1,99 @@ +function Start-UNMAP { +<# + .SYNOPSIS + Process SCSI UNMAP on VMware Datastores + + .DESCRIPTION + This Function will process SCSI UNMAP on VMware Datastores via ESXCLI -V2 + + .Example + Start-UNMAP -ClusterName myCluster -DSWildcard *RAID5* + + .Example + Start-UNMAP -ClusterName myCluster -DSWildcard *RAID5* -Verbose -WhatIf + + .Notes + NAME: Start-UNMAP.psm1 + AUTHOR: Markus Kraus + LASTEDIT: 23.09.2016 + VERSION: 1.0 + KEYWORDS: VMware, vSphere, ESXi, SCSI, VAAI, UNMAP + + .Link + http://mycloudrevolution.com/ + + #Requires PS -Version 4.0 + #Requires -Modules VMware.VimAutomation.Core, @{ModuleName="VMware.VimAutomation.Core";ModuleVersion="6.3.0.0"} + #> + + [CmdletBinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true, Position=0)] + [String]$ClusterName, + [Parameter(Mandatory=$true, Position=1)] + [String]$DSWildcard + ) + Process { + $Validate = $true + #region: PowerCLI Session Timeout + Write-Verbose "Set Session Timeout ..." + $initialTimeout = (Get-PowerCLIConfiguration -Scope Session).WebOperationTimeoutSeconds + Set-PowerCLIConfiguration -Scope Session -WebOperationTimeoutSeconds -1 -Confirm:$False | Out-Null + #endregion + + #region: Get Cluster + $Cluster = Get-Cluster -Name $ClusterName -ErrorAction SilentlyContinue + Write-Verbose "vSphere Cluster: $Cluster" + if (!$Cluster){Write-Error "No Cluster found!"; $Validate = $false} + #endregion + + #region: Get Hosts + $ClusterHosts = $Cluster | Get-VMHost -ErrorAction SilentlyContinue | where {$_.ConnectionState -eq "Connected" -and $_.PowerState -eq "PoweredOn"} + Write-Verbose "vSphere Cluster Hosts: $ClusterHosts" + if (!$ClusterHosts){Write-Error "No Hosts found!"; $Validate = $false} + #endregion + + #region: Get Datastores + $ClusterDataStores = $Cluster | Get-Datastore -ErrorAction SilentlyContinue | where {$_.Name -like $DSWildcard -and $_.State -eq "Available" -and $_.Accessible -eq "True"} + Write-Verbose "vSphere Cluster Datastores: $ClusterDataStores" + if (!$ClusterDataStores){Write-Error "No Datastores found!"; $Validate = $false} + #endregion + + #region: Process Datastores + if ($Validate -eq $true) { + Write-Verbose "Starting Loop..." + foreach ($ClusterDataStore in $ClusterDataStores) { + Write-Verbose "vSphere Datastore to Process: $ClusterDataStore" + $myHost = $ClusterHosts[(Get-Random -Maximum ($ClusterHosts).count)] + Write-Verbose "vSphere Host to Process: $myHost" + $esxcli2 = $myHost | Get-ESXCLI -V2 + $arguments = $esxcli2.storage.vmfs.unmap.CreateArgs() + $arguments.volumelabel = $ClusterDataStore + $arguments.reclaimunit = "256" + if ($PSCmdlet.ShouldProcess( $ClusterDataStore,"Starting UNMAP on $myHost")) { + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + try { + Write-Output "Starting UNMAP for $ClusterDataStore on $myHost..." + $esxcli2.storage.vmfs.unmap.Invoke($arguments) + } + catch { + Write-Output "A Error occured: " "" $error[0] "" + } + $stopwatch.Stop() + Write-Output "UNMAP duration: $($stopwatch.Elapsed.Minutes)" + } + + } + } + else { + Write-Error "Validation Failed. Processing Loop Skipped!" + } + #endregion + + #region: Revert PowerCLI Session Timeout + Write-Verbose "Revert Session Timeout ..." + Set-PowerCLIConfiguration -Scope Session -WebOperationTimeoutSeconds $initialTimeout -Confirm:$False | Out-Null + #endregion + } + +} diff --git a/Modules/VCHA.psm1 b/Modules/VCHA.psm1 new file mode 100644 index 0000000..160f0e7 --- /dev/null +++ b/Modules/VCHA.psm1 @@ -0,0 +1,413 @@ +Function Get-VCHAConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: Nov 20, 2016 + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves the VCHA Configuration which provides you with + the current state, mode as well as the IP Addresses of the Active, + Passive & Witness Node. This is only available on VCSA 6.5 (vSphere 6.5 or greater) + .DESCRIPTION + Function to return VCHA Configuration + .EXAMPLE + Get-VCHAConfig +#> + $vcHAClusterConfig = Get-View failoverClusterConfigurator + $vcHAConfig = $vcHAClusterConfig.getVchaConfig() + + $vcHAState = $vcHAConfig.State + switch($vcHAState) { + configured { + $activeIp = $vcHAConfig.FailoverNodeInfo1.ClusterIpSettings.Ip.IpAddress + $passiveIp = $vcHAConfig.FailoverNodeInfo2.ClusterIpSettings.Ip.IpAddress + $witnessIp = $vcHAConfig.WitnessNodeInfo.IpSettings.Ip.IpAddress + + $vcHAClusterManager = Get-View failoverClusterManager + $vcHAMode = $vcHAClusterManager.getClusterMode() + + Write-Host "" + Write-Host -NoNewline -ForegroundColor Green "VCHA State: " + Write-Host -ForegroundColor White "$vcHAState" + Write-Host -NoNewline -ForegroundColor Green " VCHA Mode: " + Write-Host -ForegroundColor White "$vcHAMode" + Write-Host -NoNewline -ForegroundColor Green " ActiveIP: " + Write-Host -ForegroundColor White "$activeIp" + Write-Host -NoNewline -ForegroundColor Green " PassiveIP: " + Write-Host -ForegroundColor White "$passiveIp" + Write-Host -NoNewline -ForegroundColor Green " WitnessIP: " + Write-Host -ForegroundColor White "$witnessIp`n" + ;break + } + invalid { Write-Host -ForegroundColor Red "VCHA State is in invalid state ...";break} + notConfigured { Write-Host "VCHA is not configured";break} + prepared { Write-Host "VCHA is being prepared, please try again in a little bit ...";break} + } +} + +Function Get-VCHAClusterHealth { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: Nov 20, 2016 + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves the VCHA Cluster Health which provides more info + on each of the individual. This is only available on VCSA 6.5 (vSphere 6.5 or greater) + .DESCRIPTION + Function to return VCHA Cluster Health + .EXAMPLE + Get-VCHAClusterHealth +#> + $vcHAClusterConfig = Get-View failoverClusterConfigurator + $vcHAConfig = $vcHAClusterConfig.getVchaConfig() + $vcHAState = $vcHAConfig.State + + switch($vcHAState) { + invalid { Write-Host -ForegroundColor Red "VCHA State is in invalid state ...";break} + notConfigured { Write-Host "VCHA is not configured";break} + prepared { Write-Host "VCHA is being prepared ...";break} + configured { + $vcHAClusterManager = Get-View failoverClusterManager + $healthInfo = $vcHAClusterManager.GetVchaClusterHealth() + + $vcClusterState = $healthInfo.RuntimeInfo.ClusterState + $nodeState = $healthInfo.RuntimeInfo.NodeInfo + + Write-Host "" + Write-Host -NoNewline -ForegroundColor Green "VCHA Cluster State: " + Write-Host -ForegroundColor White "$vcClusterState" + Write-Host -NoNewline -ForegroundColor Green "VCHA Node Information: " + $nodeState | Select NodeIp, NodeRole, NodeState + ;break + } + } +} + +Function Set-VCHAClusterMode { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: Nov 20, 2016 + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function allows you to set the mode of the VCHA Cluster whether + that is Enabled, Disabled or in Maintenance Mode. This is only available on VCSA 6.5 (vSphere 6.5 or greater) + .DESCRIPTION + Function to set VCHA Cluster Mode + .EXAMPLE + Set-VCHAClusterMode -Enabled $true + .EXAMPLE + Set-VCHAClusterMode -Disabled $true + .EXAMPLE + Set-VCHAClusterMode -Maintenance $true +#> + param( + [Switch]$Enabled, + [Switch]$Disabled, + [Switch]$Maintenance + ) + + $vcHAClusterManager = Get-View failoverClusterManager + + if($Enabled) { + Write-Host "Setting VCHA Cluster to Enabled ..." + $task = $vcHAClusterManager.setClusterMode_Task("enabled") + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task + } elseIf($Maintenance) { + Write-Host "Setting VCHA Cluster to Maintenance ..." + $task = $vcHAClusterManager.setClusterMode_Task("maintenance") + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task + } elseIf($Disabled) { + Write-Host "`nSetting VCHA Cluster to Disabled ...`n" + $task = $vcHAClusterManager.setClusterMode_Task("disabled") + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task + } +} + +Function New-VCHABasicConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: Nov 20, 2016 + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function allows you create a new "Basic" VCHA Cluster, it does not + cover the "Advanced" use case. You will need to ensure that you have a + "Self Managed" vCenter Server before attempting this workflow. + This is only available on VCSA 6.5 (vSphere 6.5 or greater) + .DESCRIPTION + Function to create "Basic" VCHA Cluster + .PARAMETER VCSAVM + The name of the vCenter Server Appliance (VCSA) in which you wish to enable VCHA on (must be self-managed) + .PARAMETER HANetwork + The name of the Virtual Portgroup or Distributed Portgroup used for the HA Network + .PARAMETER ActiveHAIp + The IP Address for the Active VCSA node + .PARAMETER ActiveNetmask + The Netmask for the Active VCSA node + .PARAMETER PassiveHAIp + The IP Address for the Passive VCSA node + .PARAMETER PassiveNetmask + The Netmask for the Passive VCSA node + .PARAMETER WitnessHAIp + The IP Address for the Witness VCSA node + .PARAMETER WitnessNetmask + The Netmask for the Witness VCSA node + .PARAMETER PassiveDatastore + The name of the datastore to deploy the Passive node to + .PARAMETER WitnessDatastore + The name of the datastore to deploy the Witness node to + .PARAMETER VCUsername + The VCSA username (e.g. administrator@vghetto.local) + .PARAMETER VCPassword + The VCSA password + .EXAMPLE + New-VCHABasicConfig -VCSAVM "vcenter65-1" -HANetwork "DVPG-VCHA-Network" ` + -ActiveHAIp 192.168.1.70 ` + -ActiveNetmask 255.255.255.0 ` + -PassiveHAIp 192.168.1.71 ` + -PassiveNetmask 255.255.255.0 ` + -WitnessHAIp 192.168.1.72 ` + -WitnessNetmask 255.255.255.0 ` + -PassiveDatastore "vsanDatastore" ` + -WitnessDatastore "vsanDatastore" ` + -VCUsername "administrator@vghetto.local" ` + -VCPassword "VMware1!" +#> + param( + [Parameter( + Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true) + ] + [String]$VCSAVM, + [String]$HANetwork, + [String]$ActiveHAIp, + [String]$ActiveNetmask, + [String]$PassiveHAIp, + [String]$PassiveNetmask, + [String]$PassiveDatastore, + [String]$WitnessHAIp, + [String]$WitnessNetmask, + [String]$WitnessDatastore, + # Crappy Implementation but need to research more into using PSH Credential + [String]$VCUsername, + [String]$VCPassword + ) + + $VCSAVMView = Get-View -ViewType VirtualMachine -Filter @{"name"=$VCSAVM} + if($VCSAVMView -eq $null) { + Write-Host -ForegroundColor Red "Error: Unable to find Virtual Machine $VCSAVM" + return + } + + $HANetworkView = Get-View -ViewType Network -Filter @{"name"=$HANetwork} + if($HANetworkView -eq $null) { + Write-Host -ForegroundColor Red "Error: Unable to find Network $HANetwork" + return + } + + $PassiveDatastoreView = Get-View -ViewType Datastore -Filter @{"name"=$PassiveDatastore} + if($PassiveDatastoreView -eq $null) { + Write-Host -ForegroundColor Red "Error: Unable to find Passive Datastore $PassiveDatastore" + return + } + + $WitnessDatastoreView = Get-View -ViewType Datastore -Filter @{"name"=$WitnessDatastore} + if($WitnessDatastoreView -eq $null) { + Write-Host -ForegroundColor Red "Error: Unable to find Witness Datastore $WitnessDatastore" + return + } + + $vcIP = $VCSAVMView.Guest.IpAddress + if($vcIP -eq $null) { + Write-Host -ForegroundColor Red "Error: Unable to automatically retrieve the IP Address of $VCSAVM which is needed to use this function" + return + } + + # Retrieve Source VC SSL Thumbprint + $vcurl = "https://$vcIP" +add-type @" + using System.Net; + using System.Security.Cryptography.X509Certificates; + + public class IDontCarePolicy : ICertificatePolicy { + public IDontCarePolicy() {} + public bool CheckValidationResult( + ServicePoint sPoint, X509Certificate cert, + WebRequest wRequest, int certProb) { + return true; + } + } +"@ + [System.Net.ServicePointManager]::CertificatePolicy = new-object IDontCarePolicy + # Need to do simple GET connection for this method to work + Invoke-RestMethod -Uri $VCURL -Method Get | Out-Null + + $endpoint_request = [System.Net.Webrequest]::Create("$vcurl") + # Get Thumbprint + add colons for a valid Thumbprint + $vcSSLThumbprint = ($endpoint_request.ServicePoint.Certificate.GetCertHashString()) -replace '(..(?!$))','$1:' + + $vcHAClusterConfig = Get-View failoverClusterConfigurator + $spec = New-Object VMware.Vim.VchaClusterDeploymentSpec + + $activeNetworkConfig = New-Object VMware.Vim.ClusterNetworkConfigSpec + $activeNetworkConfig.NetworkPortGroup = $HANetworkView.MoRef + $ipSettings = New-Object Vmware.Vim.CustomizationIPSettings + $ipSettings.SubnetMask = $ActiveNetmask + $activeIpSpec = New-Object VMware.Vim.CustomizationFixedIp + $activeIpSpec.IpAddress = $ActiveHAIp + $ipSettings.Ip = $activeIpSpec + $activeNetworkConfig.IpSettings = $ipSettings + $spec.ActiveVcNetworkConfig = $activeNetworkConfig + + $activeVCConfig = New-Object Vmware.Vim.SourceNodeSpec + $activeVCConfig.ActiveVc = $VCSAVMView.MoRef + $serviceLocator = New-Object Vmware.Vim.ServiceLocator + $credential = New-Object VMware.Vim.ServiceLocatorNamePassword + $credential.username = $VCUsername + $credential.password = $VCPassword + $serviceLocator.Credential = $credential + $serviceLocator.InstanceUuid = $global:DefaultVIServer.InstanceUuid + $serviceLocator.Url = $vcurl + $serviceLocator.SslThumbprint = $vcSSLThumbprint + $activeVCConfig.ManagementVc = $serviceLocator + $spec.ActiveVcSpec = $activeVCConfig + + $passiveSpec = New-Object VMware.Vim.PassiveNodeDeploymentSpec + $passiveSpec.Folder = (Get-View (Get-Folder vm)).MoRef + $passiveIpSettings = New-object Vmware.Vim.CustomizationIPSettings + $passiveIpSettings.SubnetMask = $passiveNetmask + $passiveIpSpec = New-Object VMware.Vim.CustomizationFixedIp + $passiveIpSpec.IpAddress = $passiveHAIp + $passiveIpSettings.Ip = $passiveIpSpec + $passiveSpec.IpSettings = $passiveIpSettings + $passiveSpec.NodeName = $VCSAVMView.Name + "-Passive" + $passiveSpec.datastore = $PassiveDatastoreView.MoRef + $spec.PassiveDeploymentSpec = $passiveSpec + + $witnessSpec = New-Object VMware.Vim.NodeDeploymentSpec + $witnessSpec.Folder = (Get-View (Get-Folder vm)).MoRef + $witnessSpec.NodeName = $VCSAVMView.Name + "-Witness" + $witnessIpSettings = New-object Vmware.Vim.CustomizationIPSettings + $witnessIpSettings.SubnetMask = $witnessNetmask + $witnessIpSpec = New-Object VMware.Vim.CustomizationFixedIp + $witnessIpSpec.IpAddress = $witnessHAIp + $witnessIpSettings.Ip = $witnessIpSpec + $witnessSpec.IpSettings = $witnessIpSettings + $witnessSpec.datastore = $WitnessDatastoreView.MoRef + $spec.WitnessDeploymentSpec = $witnessSpec + + Write-Host "`nDeploying VCHA Cluster ...`n" + $task = $vcHAClusterConfig.deployVcha_Task($spec) + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task -Verbose +} + +Function Remove-VCHAConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: Nov 20, 2016 + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function allows you destroy a VCHA Cluster. In addition, you have + the option to specify whether you would like both the Passive & Witness + Virtual Machines be deleted after the VCHA Cluster has been destroyed. + This is only available on VCSA 6.5 (vSphere 6.5 or greater) + .DESCRIPTION + Function to destroy a VCHA Cluster Mode + .EXAMPLE + Remove-VCHAConfig + .EXAMPLE + Remove-VCHAConfig -Confirm:$false + .EXAMPLE + Remove-VCHAConfig -DeleteVM $true -Confirm:$false + .NOTES + Before you can destroy a VCHA Cluster, you must make sure it is first + disabled. Run the Set-VCHAClusterMode -Disabled $true to do so +#> + param( + [Boolean]$Confirm=$true, + [Switch]$DeleteVM=$false + ) + + $Verified = $false + if($Confirm -eq $true) { + Write-Host -ForegroundColor Yellow "`nDo you want to destroy VCHA Cluster?" + $answer = Read-Host -Prompt "Do you accept (Y or N)" + if($answer -eq "Y" -or $answer -eq "y") { + $Verified = $true + } + } else { + $Verified = $true + } + + if($Verified) { + $vcHAClusterManager = Get-View failoverClusterManager + $vcHAMode = $vcHAClusterManager.getClusterMode() + + if($vcHAMode -ne "disabled") { + Write-Host -ForegroundColor Yellow "To destroy VCHA Cluster, you must first set the VCHA Cluster Mode to `"Disabled`"" + Exit + } + + # Query BIOS UUID of the Passive/Witness to be able to delete + if($DeleteVM) { + $vcHAClusterConfig = Get-View failoverClusterConfigurator + $vcHAConfig = $vcHAClusterConfig.getVchaConfig() + $passiveBiosUUID = $vcHAConfig.FailoverNodeInfo2.biosUuid + $witnessBiosUUID = $vcHAConfig.WitnessNodeInfo.biosUuid + } + + $vcHAClusterConfig = Get-View failoverClusterConfigurator + + Write-Host "Destroying VCHA Cluster ..." + $task = $vcHAClusterConfig.destroyVcha_Task() + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task + + # After VCHA Cluster has been destroyed, we can now delete the VMs we had queried earlier + if($DeleteVM) { + if($passiveBiosUUID -ne $null -and $witnessBiosUUID -ne $null) { + $searchIndex = Get-View searchIndex + + $passiveVM = $searchIndex.FindByUuid($null,$passiveBiosUUID,$true,$null) + $witnessVM = $searchIndex.FindByUuid($null,$witnessBiosUUID,$true,$null) + + if($passiveVM -ne $null -and $witnessVM -ne $null) { + Write-Host "Powering off & deleting Passive VM ..." + Stop-VM -VM (Get-View $passiveVM).Name -Confirm:$false | Out-Null + Remove-VM (Get-View $passiveVM).Name -DeletePermanently -Confirm:$false + Write-Host "Powering off & deleting Witness VM ..." + Stop-VM -VM (Get-View $witnessVM).Name -Confirm:$false | Out-Null + Remove-VM (Get-View $witnessVM).Name -DeletePermanently -Confirm:$false + } + } + } + } +} diff --git a/Modules/VMware.VMEncryption/README.md b/Modules/VMware.VMEncryption/README.md new file mode 100644 index 0000000..9e38900 --- /dev/null +++ b/Modules/VMware.VMEncryption/README.md @@ -0,0 +1,7 @@ +Prerequisites/Steps to use this module: + +1. This module only works for vSphere products that support VM Encryption. E.g. vSphere 6.5 and later. +2. All the functions in this module only work for KMIP Servers. +3. Install the latest version of Powershell and PowerCLI(6.5). +4. Import this module by running: Import-Module -Name "location of this module" +5. Get-Command -Module "This module Name" to list all available functions. \ No newline at end of file diff --git a/Modules/VMware.VMEncryption/VMware.VMEncryption.psd1 b/Modules/VMware.VMEncryption/VMware.VMEncryption.psd1 new file mode 100644 index 0000000..d310632 Binary files /dev/null and b/Modules/VMware.VMEncryption/VMware.VMEncryption.psd1 differ diff --git a/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 b/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 new file mode 100644 index 0000000..149fd49 --- /dev/null +++ b/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 @@ -0,0 +1,2045 @@ +# Script Module : VMware.VMEncryption +# Version : 1.0 + +# Copyright © 2016 VMware, Inc. All Rights Reserved. + +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the "Software"), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do +# so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + + +New-VIProperty -Name AESNIStatus -ObjectType VMHost -Value { + Param ($VMHost) + $FeatureCap = $VMHost.ExtensionData.Config.FeatureCapability + foreach ($Feature in $FeatureCap) { + if ($Feature.FeatureName -eq "cpuid.AES") { + ($Feature.Value -eq "1") + } + } +} -BasedOnExtensionProperty 'Config.FeatureCapability' -Force | Out-Null + +New-VIProperty -Name CryptoSafeSupported -ObjectType VMHost -Value { + Param ($VMHost) + $VMHost.ExtensionData.Runtime.CryptoState -ne $null +} -BasedOnExtensionProperty 'Runtime.CryptoState' -Force + +New-VIProperty -Name CryptoSafe -ObjectType VMHost -Value { + Param ($VMHost) + $VMHost.ExtensionData.Runtime.CryptoState -eq "safe" +} -BasedOnExtensionProperty 'Runtime.CryptoState' -Force + +New-VIProperty -Name Encrypted -ObjectType VirtualMachine -Value { + Param ($VM) + $VM.ExtensionData.Config.KeyId -ne $null +} -BasedOnExtensionProperty 'Config.KeyId' -Force | Out-Null + +New-VIProperty -Name EncryptionKeyId -ObjectType VirtualMachine -Value { + Param ($VM) + if ($VM.Encrypted) { + $VM.ExtensionData.Config.KeyId + } +} -BasedOnExtensionProperty 'Config.KeyId' -Force | Out-Null + +New-VIProperty -Name Locked -ObjectType VirtualMachine -Value { + Param ($VM) + ($vm.extensiondata.Runtime.ConnectionState -eq "invalid") -and ($vm.extensiondata.Config.KeyId) +} -BasedOnExtensionProperty 'Runtime.ConnectionState','Config.KeyId' -Force | Out-Null + +New-VIProperty -Name Encrypted -ObjectType HardDisk -Value { + Param ($hardDisk) + $hardDisk.ExtensionData.Backing.KeyId -ne $null +} -BasedOnExtensionProperty 'Backing.KeyId' -Force | Out-Null + +New-VIProperty -Name EncryptionKeyId -ObjectType HardDisk -Value { + Param ($Disk) + if ($Disk.Encrypted) { + $Disk.ExtensionData.Backing.KeyId + } +} -BasedOnExtensionProperty 'Backing.KeyId' -Force | Out-Null + +Function Enable-VMHostCryptoSafe { + <# + .SYNOPSIS + This cmdlet enables the VMHost's CryptoSate to safe. + + .DESCRIPTION + This cmdlet enables the VMHost's CryptoSate to safe. + + .PARAMETER VMHost + Specifies the VMHost you want to enable. + + .PARAMETER KMSClusterId + Specifies the KMS cluster ID which you want to use to generate the encrytion key. + + .EXAMPLE + C:\PS>$VMHost = Get-VMHost -name $VMHostName + C:\PS>Enable-VMHostCryptoSafe -VMHost $VMHost + + Enables the specified VMHost's CryptoSate to safe. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost] $VMHost, + + [Parameter(Mandatory=$False)] + [String] $KMSClusterId + ) + + Process { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + if (!$VMHost.CryptoSafeSupported) { + Write-Error "The VMHost: $VMHost does not support CryptoSafe!`n" + return + } + + if ($VMHost.CryptoSafe) { + Write-Error "The VMHost: $VMHost CryptoSafe already enabled!`n" + return + } + + # Generate key from the specified KMS cluster + try { + $KeyResult = NewEncryptionKey -KMSClusterId $KMSClusterId + } catch { + Throw "Key generation failed, make sure the KMS Cluster exists!`n" + } + + $VMHostView = Get-View $VMHost + $VMHostView.ConfigureCryptoKey($KeyResult.KeyId) + } +} + +Function Set-VMHostCryptoKey { + <# + .SYNOPSIS + This cmdlet changes the VMHost CryptoKey. + + .DESCRIPTION + This cmdlet changes the VMHost CryptoKey if VMHost is already in Crypto safe state. + + .PARAMETER VMHost + Specifies the VMHost whose CryptoKey you want to update. + + .PARAMETER KMSClusterId + Specifies the KMS cluster ID which you want to use to generate the encryption key. + + .EXAMPLE + C:\PS>$VMHost = Get-VMHost -Name $VMHostName + C:\PS>Set-VMHostCryptoKey -VMHost $VMHost + + Changes the VMHost CryptoKey to a new CryptoKey. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost] $VMHost, + + [Parameter(Mandatory=$False)] + [String] $KMSClusterId + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + if (!$VMHost.CryptoSafeSupported) { + Write-Error "The VMHost: $VMHost does not support CryptoSafe!`n" + return + } + + if (!$VMHost.CryptoSafe) { + Write-Error "The VMHost: $VMHost has not enabled the CrytoSate to safe!" + return + } + + $VMHostView = Get-View $VMHost + $OldKey = $VMHostView.Runtime.CryptoKeyId + + # Generate key from the specified KMSCluster + try { + $KeyResult = NewEncryptionKey -KMSClusterId $KMSClusterId + } catch { + Throw "Key generation failed, make sure the KMS Cluster exists!`n" + } + + try { + $VMHostView.ConfigureCryptoKey($KeyResult.KeyId) + Write-Verbose "Change Crypto Key on VMHost: $VMHost succeeded!`n" + } catch { + Write-Error "Change Crypto Key on VMHost: $VMHost failed.$_!`n" + return + } + + # Remove the old host key + Write-Verbose "Removing the old hostKey: $($OldKey.KeyId) on $VMHost...`n" + $VMHostCM = Get-View $VMHostView.ConfigManager.CryptoManager + $VMHostCM.RemoveKeys($OldKey, $true) + } +} + +Function Enable-VMEncryption { + <# + .SYNOPSIS + This cmdlet encrypts the specified VM. + + .DESCRIPTION + This cmdlet encrypts the specified VM. + + .PARAMETER SkipHardDisks + If specified, skips the encryption of the hard disks of the specified VM. + + .PARAMETER VM + Specifies the VM you want to encrypt. + + .PARAMETER Policy + Specifies the encryption policy you want to use. + + .PARAMETER KMSClusterId + Specifies the KMS clusterId you want to use to generate new key for encryption. + + .EXAMPLE + C:\PS>Get-VM -Name win2012|Enable-VMEncryption + + Encrypts the whole VM with default encryption policy. + + .EXAMPLE + C:\PS>$SP = Get-SpbmStoragePolicy -name "EncryptionPol" + C:\PS>Get-VM -Name win2012 |Enable-VMEncryption -Policy $SP -SkipHardDisks + + Encrypts the VM Home with the encryption policy 'EncryptionPol' and skips hard disks encryption. + + .NOTES + This cmdlet assumes there already is KMS defined in vCenter Server. + If VM Home is already encrypted, the cmdlet quits. + If VM Home is not encrypted, encrypt VM Home if SkipHardDisks specified. Otherwise encrypt the VM Home and VM-attached disks. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$False,ValueFromPipeline=$False,ValueFromPipelinebyPropertyName=$False)] + [VMware.VimAutomation.Storage.Types.V1.Spbm.SpbmStoragePolicy] $Policy, + + [Parameter(Mandatory=$False,ValueFromPipeline=$False,ValueFromPipelinebyPropertyName=$False)] + [String] $KMSClusterId, + + [Parameter(Mandatory=$False)] + [switch]$SkipHardDisks=$False + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + # VM Home is already encrypted + if ($VM.Encrypted) { + $ErrMsg = "VM $VM is already encrypted, please use: "+ + "Enable-VMDiskEncryption if you want to "+ + "encrypt disks which not encrypted yet!`n" + Write-Error $ErrMsg + return + } + + Write-Verbose "Checking if the VMHost supports CryptoSafe...`n" + $VMhost = $VM|Get-VMHost + if (!$VMHost.CryptoSafeSupported) { + Write-Error "The VMHost: $VMHost does not support CryptoSafe.`n" + return + } + + Write-Verbose "Checking if $VM has no snapshots...`n" + if ($VM|Get-Snapshot) { + Write-Error "$VM has snapshots, please remove all snapshots and try again!`n" + return + } + + Write-Verbose "Checking if $VM powered off...`n" + if ($VM.PowerState -ne "PoweredOff") { + $ErrMsg = "The VM can only be encrypted when powered off, "+ + "but the current power state of $VM is $($VM.PowerState)!`n" + Write-Error $ErrMsg + return + } + + $PolicyToBeUsed = $null + $BuiltInEncPolicy = Get-SpbmStoragePolicy -Name "VM Encryption Policy" + + if ($Policy) { + # Known issue: If the provided policy is created/cloned from + # the default "VM Encryption Policy", + # Or When creating the policy you didn't select 'Custom', + # there will be null-valued Exception. + Write-Verbose "Checking if the provided policy: $Policy is an encryption policy`n" + if (($Policy.Name -ne "VM Encryption Policy") -and !$Policy.CommonRule.Capability.Category.Contains("ENCRYPTION")) { + Write-Error "The policy $Policy is not an encryption policy, exit!" + return + } + $PolicyToBeUsed = $Policy + } else { + Write-Verbose "No storage policy specified, try to use the built-in policy.`n" + if ($BuiltInEncPolicy) { + $PolicyToBeUsed = $BuiltInEncPolicy + } else { + Throw "The built-in policy does not exist, please use: New-SpbmStoragePolicy to create one first!`n" + } + } + + # Encrypt the VM disks if SkipHardDisk not specified + if (!$SkipHardDisks) { + $Disks = $VM|Get-HardDisk + } + + $VMView = Get-View $VM + $ProfileSpec = New-Object VMware.Vim.VirtualMachineDefinedProfileSpec + $ProfileSpec.ProfileId = $PolicyToBeUsed.Id + $VMCfgSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $VMCfgSpec.VmProfile = $ProfileSpec + + if ($KMSClusterId) { + # Generate a new key from KMS + try { + $KeyResult = NewEncryptionKey -KMSClusterId $KMSClusterId + } catch { + Throw "Key generation failed, make sure the specified KMS Cluster exists!`n" + } + + $CryptoKeyId = $KeyResult.KeyId + $CryptoSpec = New-Object VMware.Vim.CryptoSpecEncrypt + $CryptoSpec.CryptoKeyId = $CryptoKeyId + $VMCfgSpec.Crypto = $CryptoSpec + } + + $DeviceChanges = @() + foreach ($Disk in $Disks) { + Write-Verbose "Attaching policy: $PolicyToBeUsed to $Disk`n" + $DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec + $BackingSpec = New-Object VMware.Vim.VirtualDeviceConfigSpecBackingSpec + $DeviceChange.operation = "edit" + $DeviceChange.device = $Disk.extensiondata + $DeviceChange.Profile = $ProfileSpec + $BackingSpec.Crypto = $CryptoSpec + $DeviceChange.Backing = $BackingSpec + $DeviceChanges += $deviceChange + } + + if ($Devicechanges) { + $VMCfgSpec.deviceChange = $Devicechanges + } + + return $VMView.ReconfigVM_Task($VMCfgSpec) + } +} + +Function Enable-VMDiskEncryption { + <# + .SYNOPSIS + This cmdlet encrypts the specified hard disks. + + .DESCRIPTION + This cmdlet encrypts the specified hard disks. + + .PARAMETER VM + Specifies the VM whose hard disks you want to encrypt. + + .PARAMETER Policy + Specifies the encryption policy you want to use. + + .PARAMETER HardDisk + Specifies the hard disks you want to encrypt. + + .PARAMETER KMSClusterId + Specifies the KMS clusterId you want to use to generate new key for encryption. + + .EXAMPLE + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$VMDisks= $VM|Get-Harddisk|Select -last 2 + C:\PS>Enable-VMDiskEncryption -VM $VM -$HardDisk $VMDisks + + Encrypts the VM disks with the default encryption policy and use the VM encryption key. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.HardDisk[]] $HardDisk, + + [Parameter(Mandatory=$False)] + [VMware.VimAutomation.Storage.Types.V1.Spbm.SpbmStoragePolicy] $Policy, + + [Parameter(Mandatory=$False)] + [String] $KMSClusterId + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + Write-Verbose "Checking if $VM is encrypted..." + if (!$VM.Encrypted) { + Write-Error "$VM is not encrypted, please use:Enable-VMEncryption to encrypt the VM.`n" + return + } + + # Validate the hard disks + Write-Verbose "Checking the hard disks...`n" + ConfirmHardDiskIsValid -VM $VM -HardDisk $HardDisk + + Write-Verbose "Checking if $VM has no snapshots..." + if ($VM|Get-Snapshot) { + Write-Error "$VM has snapshots, please remove all snapshots!`n" + return + } + + Write-Verbose "Checking if $VM is powered off..." + if ($VM.powerstate -ne "PoweredOff") { + $ErrMsg = "The VM can only be ecrypted when powered off, "+ + "but the current power state of $VM is $($VM.PowerState)!`n" + Write-Error $ErrMsg + return + } + + $PolicyToBeUsed = $null + + if ($Policy) { + # Known issue: If the provided policy is created/cloned from + # the default "VM Encryption Policy", + # Or When creating the policy you didn't select 'Custom', + # there will be null-valued Exception. + Write-Verbose "Checking if the provided policy: $Policy is an encryption policy`n" + if (($Policy.Name -ne "VM Encryption Policy") -and !$Policy.CommonRule.Capability.Category.Contains("ENCRYPTION")) { + Throw "The policy $Policy is not an encryption policy, exit!" + } + $PolicyToBeUsed = $Policy + } else { + Write-Verbose "No storage policy specified, try to use the VM Home policy.`n" + $PolicyToBeUsed = (Get-SpbmEntityConfiguration -VM $VM).StoragePolicy + if (!$PolicyToBeUsed) { + Write-Warning "The VM Home policy is not available, try to use the built-in policy.`n" + $BuiltInEncPolicy = Get-SpbmStoragePolicy -Name "VM Encryption Policy" + if ($BuiltInEncPolicy) { + $PolicyToBeUsed = $BuiltInEncPolicy + } else { + Throw "The built-in policy does not exist, please use: New-SpbmStoragePolicy to create one first!`n" + } + } + } + + # Specify the key used to encrypt disk + if ($KMSClusterId) { + # Generate a new key from KMS + try { + $KeyResult = NewEncryptionKey -KMSClusterId $KMSClusterId + } catch { + Throw "Key generation failed, make sure the KMS Cluster exists!`n" + } + + $CryptoKeyId = $KeyResult.KeyId + $CryptoSpec = New-Object VMware.Vim.CryptoSpecEncrypt + $CryptoSpec.CryptoKeyId = $CryptoKeyId + } + + Write-Verbose "Encrypting the hard disks: $HardDisk...`n" + + $VMView = Get-View $VM + $VMCfgSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $ProfileSpec = New-Object VMware.Vim.VirtualMachineDefinedProfileSpec + $ProfileSpec.ProfileId = $PolicyToBeUsed.Id + + $DeviceChanges = @() + + foreach ($Disk in $HardDisk) { + Write-Verbose "Attaching policy: $PolicyToBeUsed to $Disk`n" + $DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec + $BackingSpec = New-Object VMware.Vim.VirtualDeviceConfigSpecBackingSpec + $DeviceChange.operation = "edit" + $DeviceChange.device = $Disk.extensiondata + $DeviceChange.Profile = $ProfileSpec + $BackingSpec.Crypto = $CryptoSpec + $DeviceChange.Backing = $BackingSpec + $DeviceChanges += $DeviceChange + } + + if ($DeviceChanges) { + $VMCfgSpec.deviceChange = $DeviceChanges + } + + return $VMView.ReconfigVM_Task($VMCfgSpec) + } +} + +Function Disable-VMEncryption { + <# + .SYNOPSIS + This cmdlet decrypts the specified VM. + + .DESCRIPTION + This cmdlet decrypts the specified VM. + + .PARAMETER VM + Specifies the VM you want to decrypt. + + .EXAMPLE + C:\PS>Get-VM -Name win2012 | Disable-VMEncryption + + Decrypts the VM Home and all encrypted disks. + + .EXAMPLE + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>Disable-VMEncryption -VM $VM + + Decrypts the whole VM, including the encrypted disks. + + .NOTES + If the VM is not encrypted, the cmdlet quits. + + .NOTES + Author : Carrie Yang. + Author email : yangm@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + Write-Verbose "Checking if $VM is encrypted..." + if (!$VM.Encrypted) { + Write-Error "$VM is not encrypted.`n" + return + } + + Write-Verbose "Checking if $VM has no snapshots..." + if ($VM|Get-Snapshot) { + Write-Error "$VM has snapshots, it can not be decrypted!`n" + return + } + + Write-Verbose "Checking if $VM is powered off..." + if ($VM.powerstate -ne "PoweredOff") { + $ErrMsg = "The VM can only be decrypted when powered off, "+ + "but the current power state of $VM is $($VM.PowerState)!`n" + Write-Error $ErrMsg + return + } + + $VMCfgSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $Profile = New-Object VMware.Vim.VirtualMachineEmptyProfileSpec + $DecryptCrypto = New-Object VMware.Vim.CryptoSpecDecrypt + $DisksToDecrypt = $VM|Get-HardDisk|Where {$_.Encrypted} + + $VMCfgSpec.VmProfile = $Profile + $VMCfgSpec.Crypto = $DecryptCrypto + + $DeviceChanges = @() + foreach ($Disk in $DisksToDecrypt) { + $DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec + $DeviceChange.operation = "edit" + $DeviceChange.device = $Disk.extensiondata + $DeviceChange.Profile = $Profile + $DeviceChange.Backing = New-Object VMware.Vim.VirtualDeviceConfigSpecBackingSpec + $DeviceChange.Backing.Crypto = $DecryptCrypto + $DeviceChanges += $DeviceChange + } + + if ($Devicechanges) { + $VMCfgSpec.deviceChange = $Devicechanges + } + + return (Get-View $VM).ReconfigVM_Task($VMCfgSpec) + } +} + +Function Disable-VMDiskEncryption { + <# + .SYNOPSIS + This cmdlet decrypts the specified hard disks in a given VM. + + .DESCRIPTION + This cmdlet decrypts the specified hard disks in a given VM. + + .PARAMETER VM + Specifies the VM which the hard disks belong to. + + .PARAMETER HardDisk + Specifies the hard disks you want to decrypt. + + .EXAMPLE + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$HardDisk = $VM|Get-HardDisk|select -last 1 + C:\PS>Disable-VMDiskEncryption -VM $VM -HardDisk $HardDisk + + Decrypts the last hard disk in the VM. + + .NOTES + If the VM is not encrypted, the cmdlet quits. + + .NOTES + Author : Carrie Yang. + Author email : yangm@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.HardDisk[]] $HardDisk + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + Write-Verbose "Checking if $VM is encrypted..." + if (!$VM.Encrypted) { + Write-Error "$VM is not encrypted.`n" + return + } + + # Validate the hard disks + Write-Verbose "Checking the hard disks...`n" + ConfirmHardDiskIsValid -VM $VM -HardDisk $HardDisk + + $DisksToDecrypt = $HardDisk |Where {$_.Encrypted} + + if ($DisksToDecrypt.Length -eq 0) { + Write-Error "The provided disks are not encrypted.`n" + return + } + + Write-Verbose "Checking if $VM has no snapshots..." + if ($VM|Get-Snapshot) { + Write-Error "$VM has snapshots, it can not be decrypted!`n" + return + } + + Write-Verbose "Checking if $VM is powered off..." + if ($VM.powerstate -ne "PoweredOff") { + $ErrMsg = "The VM can only be decrypted when powered off, "+ + "but the current power state of $VM is $($VM.PowerState)!`n" + Write-Error $ErrMsg + return + } + + $VMCfgSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $Profile = New-Object VMware.Vim.VirtualMachineEmptyProfileSpec + $DecryptCrypto = New-Object VMware.Vim.CryptoSpecDecrypt + + + $DeviceChanges = @() + foreach ($Disk in $DisksToDecrypt) { + $DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec + $DeviceChange.operation = "edit" + $DeviceChange.device = $Disk.extensiondata + $DeviceChange.Profile = $Profile + $DeviceChange.Backing = New-Object VMware.Vim.VirtualDeviceConfigSpecBackingSpec + $DeviceChange.Backing.Crypto = $DecryptCrypto + $DeviceChanges += $DeviceChange + } + + $VMCfgSpec.deviceChange = $DeviceChanges + + return (Get-View $VM).ReconfigVM_Task($VMCfgSpec) + } +} + +Function Set-VMEncryptionKey { + <# + .SYNOPSIS + This cmdlet sets the encryption key of VM or hard disks. + + .DESCRIPTION + This cmdlet sets the encryption key of VM or hard disks. + + .PARAMETER VM + Specifies the VM you want to rekey. + + .PARAMETER KMSClusterId + Specifies the KMS clusterId you want to use for getting a new key for rekey operation. + + .PARAMETER Deep + When it's specified, both the key encryption key (KEK) and + the internal data encryption key (DEK) will be updated. + This is implemented through a full copy; It's a slow operation that + must be performed while the virtual machine is powered off. + A shallow key change will only update the KEK and the operation can be performed + while the virtual machine is running. + + .PARAMETER SkipHardDisks + Skip updating the hard disk keys. + + .EXAMPLE + C:\PS>Get-VM -Name win2012 | Set-VMEncryptionKey + + Rekeys the VM win2012 VM Home and all its disks. + + .EXAMPLE + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$VM|Set-VMEncryptionKey -SkipHardDisks + + Rekeys the VM Home only. + + .EXAMPLE + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$VM|Set-VMEncryptionKey -Deep + + Rekeys the VM Home and all its disks with Deep option. + + .EXAMPLE + C:\PS>$KMSCluster = Get-KMSCluster | select -last 1 + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$VM|Set-VMEncryptionKey -KMSClusterId $KMSCluster.Id -Deep + + Deep rekeys the VM Home and all its disks using a new key. + The key is generted from the KMS whose clusterId is $KMSCluster.Id. + + .NOTES + This cmdlet assumes there is already a KMS in vCenter Server. If VM is not encrypted, the cmdlet quits. + You should use Enable-VMEncryption cmdlet to encrypt the VM first. + + .NOTES + Author : Carrie Yang. + Author email : yangm@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$False)] + [String] $KMSClusterId, + + [Parameter(Mandatory=$False)] + [switch]$Deep = $FALSE, + + [Parameter(Mandatory=$False)] + [switch]$SkipHardDisks = $False + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + Write-Verbose "Checking if $VM is encrypted...`n" + if (!$VM.Encrypted) { + Write-Error "$VM is not encrypted." + return + } + + Write-Verbose "Checking if $VM has no snapshots...`n" + if ($VM|Get-Snapshot) { + Write-Error "$VM has snapshot, please remove all snapshots and try again!`n" + return + } + + if ($Deep) { + Write-Verbose "Checking if $VM powered off...`n" + if ($VM.powerstate -ne "PoweredOff") { + $ErrMsg = "The VM can only be recrypted when powered off, "+ + "but the current power state of $VM is $($VM.PowerState)!`n" + Write-Error $ErrMsg + return + } + } + + $VMCfgSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $ProfileSpec = New-Object VMware.Vim.VirtualMachineDefinedProfileSpec + $CryptoSpec = New-Object VMware.Vim.CryptoSpecShallowRecrypt + + if ($Deep) { + $CryptoSpec = New-Object VMware.Vim.CryptoSpecDeepRecrypt + $VMPolicy = (Get-SpbmEntityConfiguration -VM $VM).StoragePolicy + $ProfileSpec.ProfileId = $VMPolicy.Id + $VMCfgSpec.VmProfile = $ProfileSpec + } + + # Generate a key from KMS + try { + $KeyResult = NewEncryptionKey -KMSClusterId $KMSClusterId + } catch { + Throw "Key generation failed, make sure the KMS Cluster exists!`n" + } + $CryptoSpec.NewKeyId = $KeyResult.KeyId + $VMCfgSpec.Crypto = $CryptoSpec + + if (!$SkipHardDisks) { + $DisksToRecrypt = $VM|Get-HardDisk|Where {$_.Encrypted} + + $DeviceChanges = @() + foreach ($disk in $DisksToRecrypt) { + $DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec + $DeviceChange.operation = "edit" + $DeviceChange.device = $Disk.extensiondata + if ($Deep) { + $DiskProfileSpec = New-Object VMware.Vim.VirtualMachineDefinedProfileSpec + $DiskProfileSpec.ProfileId = ($Disk|Get-SpbmEntityConfiguration).StoragePolicy.Id + $DeviceChange.Profile = $DiskProfileSpec + } + $DeviceChange.Backing = New-Object VMware.Vim.VirtualDeviceConfigSpecBackingSpec + $DeviceChange.Backing.Crypto = $CryptoSpec + $DeviceChanges += $DeviceChange + } + + if ($DeviceChanges.Length -gt 0) { + $VMCfgSpec.deviceChange = $DeviceChanges + } + } + + return (Get-View $VM).ReconfigVM_Task($VMCfgSpec) + } +} + +Function Set-VMDiskEncryptionKey { + <# + .SYNOPSIS + This cmdlet sets the encryption key of the hard disks in the VM. + + .DESCRIPTION + This cmdlet sets the encryption key of the hard disks in the VM. + + .PARAMETER VM + Specifies the VM from which you want to rekey its disks. + + .PARAMETER HardDisk + Specifies the hard disks you want to rekey. + + .PARAMETER KMSClusterId + Specifies the KMS clusterId you want to use for getting a new key for rekey operation. + + .PARAMETER Deep + When it's specified, both the key encryption key (KEK) and + the internal data encryption key (DEK) will be updated. + This is implemented through a full copy; It's a slow operation that + must be performed while the virtual machine is powered off. + A shallow key change will only update the KEK and the operation can be performed + while the virtual machine is running. + + .EXAMPLE + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$HardDisk = $VM|Get-HardDisk|select -last 2 + C:\PS>Set-VMDiskEncryptionKey -VM $VM -HardDisk $HardDisk + + Rekeys the last 2 hard disks in the VM. + + .EXAMPLE + C:\PS>$VM=Get-VM -Name win2012 + C:\PS>$HardDisk = get-vm $vm|Get-HardDisk|Select -last 2 + C:\PS>Set-VMDiskEncryptionKey -VM $VM -HardDisk $HardDisk -Deep + + Deep rekeys the last 2 hard disks in the VM. + + .EXAMPLE + C:\PS>$KMSCluster = Get-KMSCluster | select -last 1 + C:\PS>$VM = Get-VM -Name win2012 + C:\PS>$HardDisk = get-vm $vm|Get-HardDisk + C:\PS>$HardDisk|$Set-VMEncryptionKey -VM $VM -KMSClusterId $KMSCluster.Id -Deep + + Deep rekeys all the disks of the $VM using a new key. + The key is generted from the KMS whose clusterId is $KMSCluster.Id. + + .NOTES + This cmdlet assumes there is already a KMS in vCenter Server. + If VM is not encrypted, the cmdlet quits. + You should use Enable-VMEncryption cmdlet to encrypt the VM first. + + .NOTES + Author : Carrie Yang. + Author email : yangm@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.HardDisk[]] $HardDisk, + + [Parameter(Mandatory=$False)] + [String] $KMSClusterId, + + [Parameter(Mandatory=$False)] + [switch]$Deep = $FALSE + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + } + + Process { + Write-Verbose "Checking if $VM is encrypted...`n" + if (!$VM.Encrypted) { + Write-Error "$VM is not encrypted." + return + } + + # Valid the hard disks + Write-Verbose "Checking the hard disks...`n" + ConfirmHardDiskIsValid -VM $VM -HardDisk $HardDisk + + Write-Verbose "Checking if $VM has no snapshots...`n" + if ($VM|Get-Snapshot) { + Write-Error "$VM has snapshot, please remove all snapshots and try again!`n" + return + } + + if ($Deep) { + Write-Verbose "Checking if $VM powered off...`n" + if ($VM.powerstate -ne "PoweredOff") { + $ErrMsg = "Deep rekey could be done only when VM powered off,"+ + "but current VM power state is: $($VM.powerstate)!`n" + Write-Error $ErrMsg + return + } + } + + $VMCfgSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $CryptoSpec = New-Object VMware.Vim.CryptoSpecShallowRecrypt + if ($Deep) { + $CryptoSpec = New-Object VMware.Vim.CryptoSpecDeepRecrypt + } + + # Generate a key from KMS + try { + $KeyResult = NewEncryptionKey -KMSClusterId $KMSClusterId + } catch { + Throw "Key generation failed, make sure the KMS Cluster exists!`n" + } + $CryptoSpec.NewKeyId = $KeyResult.KeyId + + $DeviceChanges = @() + foreach ($disk in $HardDisk) { + $DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec + $DeviceChange.operation = "edit" + $DeviceChange.device = $Disk.extensiondata + if ($Deep) { + $ProfileSpec = New-Object VMware.Vim.VirtualMachineDefinedProfileSpec + $ProfileSpec.ProfileId = ($Disk|Get-SpbmEntityConfiguration).StoragePolicy.Id + $DeviceChange.Profile = $ProfileSpec + } + $DeviceChange.Backing = New-Object VMware.Vim.VirtualDeviceConfigSpecBackingSpec + $DeviceChange.Backing.Crypto = $CryptoSpec + $DeviceChanges += $DeviceChange + } + + $VMCfgSpec.deviceChange = $DeviceChanges + + return (Get-View $VM).ReconfigVM_Task($VMCfgSpec) + } +} + +Function Get-VMEncryptionInfo { + <# + .SYNOPSIS + This cmdlet gets the encryption information of VM and its disks. + + .DESCRIPTION + This cmdlet gets the encryption information of VM and its disks. + + .PARAMETER VM + Specifies the VM for which you want to retrieve the encryption information. + + .PARAMETER HardDisk + Specifies the hard disks for which you want to retrieve the encryption information. + + .EXAMPLE + C:\PS>Get-VM|Get-VMEncryptionInfo + + Retrieves all VM's encryption information. + + .EXAMPLE + C:\PS>Get-VMEncryptionInfo -VM $vm -HardDisk $HardDisks + + Retrieves only disks' encryption information. + + .NOTES + If $HardDisk is specified, then only the encryption information of the disks specified in $HardDisk is obtained. + Otherwise, all disks' encryption information of the specified VM is returned. + + .NOTES + Author : Carrie Yang. + Author email : yangm@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.HardDisk[]] $HardDisk + ) + + Process { + $DisksInfo = @() + + if ($HardDisk) { + # Validate the hard disks + Write-Verbose "Checking the hard disks...`n" + ConfirmHardDiskIsValid -VM $VM -HardDisk $HardDisk + } + + foreach ($DK in $HardDisk) { + $DKInfo = @{} + $DKInfo.index = $DK.ExtensionData.Key + $DKInfo.label = $DK.ExtensionData.DeviceInfo.Label + $diskSize = $DK.ExtensionData.CapacityInKB + $formattedSize = "{0:N0}" -f $diskSize + $DKInfo.summary = "$formattedSize KB" + $DKInfo.profile = ($DK|Get-SpbmEntityConfiguration).StoragePolicy + $DKInfo.fileName = $DK.Filename + $DKInfo.uuid = $DK.ExtensionData.Backing.Uuid + $DKInfo.keyId = $DK.ExtensionData.Backing.KeyId + $DKInfo.iofilter = $DK.ExtensionData.Iofilter + $DisksInfo += $DKInfo + } + + $VMInfo = @{} + $VMInfo.name = $VM.Name + $VMInfo.connectState = $VM.ExtensionData.Runtime.ConnectionState + $VMInfo.profile = ($VM | Get-SpbmEntityConfiguration).StoragePolicy + $VMInfo.keyId = $VM.ExtensionData.Config.KeyId + $VMInfo.disks = $DisksInfo + + return $VMInfo + } +} + +Function Get-EntityByCryptoKey { + <# + .SYNOPSIS + This cmdlet gets all the related objects in which it has the key associated. + + .DESCRIPTION + This cmdlet gets all the related objects in which it has the key associated. + + .PARAMETER KeyId + Specifies the KeyId string. + + .PARAMETER KMSClusterId + Specifies the KMSClusterId string. + + .PARAMETER SearchVMHosts + Specifies whether to search the VMHosts. + + .PARAMETER SearchVMs + Specifies whether to search the VMs. + + .PARAMETER SearchDisks + Specifies whether to search the HardDisks. + + .EXAMPLE + C:\PS>Get-EntityByCryptoKeyId -SearchVMHosts -KeyId 'keyId' + + Gets the VMHosts whose CryptoKeyId's KeyId matches exactly the 'keyId'. + + .EXAMPLE + C:\PS>Get-EntityByCryptoKeyId -SearchVMs -KMSClusterId 'clusterId' + + Gets the VMs whose CryptoKeyId's ProfileId.Id matches exactly the 'clusterId'. + + .EXAMPLE + C:\PS>Get-EntityByCryptoKey -SearchVMHosts -SearchVMs -KMSClusterId 'clusterId' + + Gets VMHosts and VMs whose CryptoKeyId's ProviderId.Id matches the 'clusterId'. + + .NOTES + At least one of the KeyId and KMSClusterId parameters is required. + If the SearchVMHosts, SearchVMs and SearchDisks all not specified, the cmdlet return $null. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [String] $keyId, + + [Parameter(Mandatory=$false,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [String] $KMSClusterId, + + [Parameter(Mandatory=$False)] + [switch] $SearchVMHosts, + + [Parameter(Mandatory=$False)] + [switch] $SearchVMs, + + [Parameter(Mandatory=$False)] + [switch] $SearchDisks + ) + + if (!$KeyId -and !$KMSClusterId) { + Throw "One of the keyId or KMSClusterId must be specified!`n" + } + + # The returned Items + $Entities = @{} + + # Find VMHosts + $CryptoSafeVMHosts = Get-VMHost|Where {$_.CryptoSafe} + + # Quit if no VMHosts found. + if (!$CryptoSafeVMHosts) { + Throw "No VMHosts enabled the CrytoState to Safe!`n" + } + + if ($SearchVMHosts) { + Write-Verbose "Starting to search VMHosts...`n" + $VMHostList = $CryptoSafeVMHosts| Where {$_.ExtensionData.Runtime.CryptoKeyId|MatchKeys -KeyId $KeyId -KMSClusterId $KMSClusterId} + $Entities.VMHostList = $VMHostList + } + + # Find the VMs which encrypted: Look for both VMHome and Disks + $VMs = Get-VM|Where {$_.Encrypted} + if ($SearchVMs) { + Write-Verbose "Starting to search VMs...`n" + $VMList = @() + $Disks = $VMs|Get-HardDisk|Where {$_.Encrypted} + $VMDiskList = $Disks|Where {$_.EncryptionKeyId|MatchKeys -KeyId $keyId -KMSClusterId $KMSClusterId} + + $VMList += $VMs|Where {$_.EncryptionKeyId|MatchKeys -KeyId $keyId -KMSClusterId $KMSClusterId} + $VMList += $VMDiskList.Parent + $VMList = $VMList|sort|Get-Unique + $Entities.VMList = $VMList + } + + # Find the Disks + if ($SearchDisks) { + Write-Verbose "Starting to search Disks...`n" + if ($SearchVMs) { + $DiskList = $VMDiskList + } else { + $Disks = $VMs|Get-HardDisk|Where {$_.Encrypted} + $DiskList = $Disks|Where {$_.EncryptionKeyId|MatchKeys -KeyId $keyId -KMSClusterId $KMSClusterId} + } + + $Entities.DiskList = $DiskList + } + + return $Entities +} + +Function New-KMServer { + <# + .SYNOPSIS + This cmdlet adds a Key Management Server. + + .DESCRIPTION + This cmdlet adds a Key Management Server to vCenter Server and verifies it. + + .PARAMETER KMServer + Specifies the Key Management Server IP address or FQDN. + + .PARAMETER KMSClusterId + Specifies the ID of the KMS cluster. KMSs with the same cluster ID are in one cluster and provide the same keys for redundancy. + + .PARAMETER UserName + Specifies user name to authenticate to the KMS. + + .PARAMETER Password + Specifies password to authenticate to the KMS. + + .PARAMETER Name + Specifies the name of the KMS. + + .PARAMETER Port + Specifies the port of the KMS. + + .PARAMETER ProxyServer + Specifies the address of the proxy server. + + .PARAMETER ProxyPort + Specifies the port of the proxy server. + + .PARAMETER Protocol + Specifies the KMS library protocol handler, for example KMS1. + + .EXAMPLE + C:\PS>New-KMServer -KMServer 1.1.1.1 -KMSClusterId clsName -UserName "YourKMSUserName" -Password '***' -Name "KMS1" + + Adds the Key Management Server 1.1.1.1 into vCenter with the cluster name 'clsname' and KMS name 'KMS1'. + + .NOTES + This cmdlet only supports PyKMIP Server. For other KMS vendors, modify the script accordingly. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True)] + [String]$KMServer, + + [Parameter(Mandatory=$True,ValueFromPipeline=$True)] + [String]$KMSClusterId, + + [Parameter(Mandatory=$False)] + [String] $UserName, + + [Parameter(Mandatory=$True,ValueFromPipeline=$True)] + [String] $Name, + + [Parameter(Mandatory=$False)] + [String] $Password, + + [Parameter(Mandatory=$False)] + [Int] $Port=5696, + + [Parameter(Mandatory=$False)] + [String] $ProxyServer, + + [Parameter(Mandatory=$False)] + [Int] $ProxyPort, + + [Parameter(Mandatory=$False)] + [String] $Protocol + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + } + + Process { + if ([string]::IsNullOrWhiteSpace($KMSClusterId)) { + Write-Error "The KMSClusterId parameter is mandatory, please specify a valid value!`n" + return + } + + if ([string]::IsNullOrWhiteSpace($KMServer)) { + Write-Error "The KMServer parameter is mandatory, please specify a valid value!`n" + return + } + + if ([string]::IsNullOrWhiteSpace($Name)) { + Write-Error "The KMSName parameter is mandatory. Please specify a valid value!`n" + return + } + + Write-Verbose "Starting to add Key Management Server: $KMServer......`n" + # Construct KMServerInfo and Spec + $KMServerInfo = New-Object VMware.Vim.KmipServerInfo + $KMServerSpec = New-Object VMware.Vim.KmipServerSpec + $KMServerInfo.Address = $KMServer + $KMServerInfo.Name = $Name + + if ($UserName) { + $KMServerInfo.UserName = $UserName + } + + if ($KMSPassword) { + $KMServerSpec.Password = $Password + } + + if ($Port) { + $KMServerInfo.Port = $Port + } + + if ($ProxyServer) { + $KMServerInfo.ProxyAddress = $ProxyServer + } + + if ($ProxyPort) { + $KMServerInfo.ProxyPort = $ProxyPort + } + + if ($Protocol) { + $KMServerInfo.Protocol = $Protocol + } + + $ProviderID = New-Object VMware.Vim.KeyProviderId + $ProviderID.Id = $KMSClusterId + $KMServerSpec.ClusterId = $ProviderID + $KMServerSpec.Info = $KMServerInfo + + Write-Verbose "Registering $KMServer to vCenter Server....`n" + + try { + $CM.RegisterKmipServer($KMServerSpec) + } catch { + Write-Error "Exception: $_ !" + return + } + + Write-Verbose "Establishing trust between vCenter Server and the Key Management Server: $KMServer`n" + try { + $KMServerCert = $CM.RetrieveKmipServerCert($providerID,$KMServerInfo) + $CM.UploadKmipServerCert($providerID,$KMServerCert.Certificate) + } catch { + Write-Error "Error occurred while retrieveing and uploading certification!`n" + return + } + + $CM.updateviewdata() + if (!(Get-DefaultKMSCluster) -and + ($CM.KmipServers|foreach {$_.servers}|foreach {$_.Address}) -contains $KMServer) { + Write-Verbose "No default Key Management Server yet. Marking $KMServer as default!`n" + Set-DefaultKMSCluster -KMSClusterId $ProviderID.Id + } + + Write-Verbose "Verifying KMS registration.....`n" + $CM.updateviewdata() + $KMServers = $CM.Kmipservers|where {($_.servers|foreach {$_.Address}) -contains $KMServer} + if ($KMServers) { + Write-Verbose "Key Management Server registered successfully!`n" + $KMServers + } else { + Write-Error "Key Management Server registration failed!`n" + } + } +} + +Function Remove-KMServer { + <# + .SYNOPSIS + This cmdlet removes a Key Management Server. + + .DESCRIPTION + This cmdlet removes a Key Management Server from vCenter Server. + + .PARAMETER Name + Specifies the name or alias of the Key Management Server. + + .PARAMETER KMSClusterId + Specifies the KMS cluster ID string to be used as Key Management Server cluster. + + .EXAMPLE + C:\PS>Remove-KMServer -KMSClusterId "ClusterIdString" -KMSName "KMServerName" + + Removes the KMS from vCenter Server which has the KMS name and KMS cluster ID. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True)] + [String]$KMSClusterId, + + [Parameter(Mandatory=$True)] + [String]$Name + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + } + + Process { + if ([string]::IsNullOrWhiteSpace($Name) -Or + [string]::IsNullOrWhiteSpace($KMSClusterId)) { + $ErrMsg = "The KMSName and KMSClusterId parameters are mandatory "+ + "and should not be null or empty!`n" + Write-Error $ErrMsg + return + } + + $KMServers = $CM.KmipServers + if (!$KMServers) { + Write-Error "There are no Key Managerment Servers in vCenter Server!`n" + return + } + + if ($KMServers|Where { ($_.ClusterId.Id -eq $KMSClusterId) -and ($_.Servers|Where {$_.Name -eq $Name})}) { + #Start to remove the specified Km Server + try { + $ProviderID = New-Object VMware.Vim.KeyProviderId + $ProviderID.Id = $KMSClusterId + $CM.RemoveKmipServer($providerID, $Name) + } catch { + Write-Error "Exception: $_!`n" + return + } + } else { + $KMSNotFounErrMsg = "Cannot find the KMS with Name:$Name and KMS ClusterId:$KMSClusterId,"+ + "please make sure you specified correct parameters!`n" + Write-Error $KMSNotFounErrMsg + return + } + } +} + +Function Get-KMSCluster { + <# + .SYNOPSIS + This cmdlet retrieves all KMS clusters. + + .DESCRIPTION + This cmdlet retrieves all KMS clusters. + + .EXAMPLE + C:\PS>Get-KMSCluster + + Retrieves all KMS clusters. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + + # Get all KMS Clusters + return $CM.KmipServers.ClusterId +} + +Function Get-KMSClusterInfo { + <# + .SYNOPSIS + This cmdlet retrieves the KMS cluster information. + + .DESCRIPTION + This cmdlet retrieves the KMS cluster Information by providing the KMS cluster ID string. + + .PARAMETER KMSClusterId + Specifies the KMS cluster ID. + + .EXAMPLE + C:\PS>Get-KMSClusterInfo + + Retrieves all KMS cluster information. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [String] $KMSClusterId + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + } + + Process { + # Get all Km Clusters if no KMSClusterId specified + if (!$KMSClusterId) { + return $CM.KmipServers + } + return $CM.KmipServers|where {$_.ClusterId.Id -eq $KMSClusterId} + } +} + +Function Get-KMServerInfo { + <# + .SYNOPSIS + This cmdlet retireves the Key Management Servers' information. + + .DESCRIPTION + This cmdlet retireves the Key Management Servers' information by providing the KMS cluster ID string. + + .PARAMETER KMSClusterId + Specifies the KMS cluster ID. + + .EXAMPLE + C:\PS>Get-KMServerInfo + + Retrieves information about all Key Management Servers. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [String] $KMSClusterId + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + } + + Process { + # Get all KMS Info if no clusterId specified + if ($KMSClusterId) { + $FindCluster = (Get-KMSCluster).Contains($KMSClusterId) + if (!$FindCluster) { + Write-Error "Cannot find the specified KMS ClusterId in vCenter Server!" + return + } + + $ClsInfo = Get-KMSClusterInfo -KMSClusterId $KMSClusterId + + return $ClsInfo.Servers + } + + return $CM.KmipServers.Servers + } +} + +Function Get-KMServerStatus { + <# + .SYNOPSIS + This cmdlet retrieves the KMS status. + + .DESCRIPTION + This cmdlet retrieves the KMS status by providing the KMS cluster ID String + + .PARAMETER KMSClusterId + Specifies the KMS cluster ID from which to retrieve the servers' status. + + .EXAMPLE + C:\PS>Get-KMServerStatus -KMSClusterId 'ClusterIdString' + + Retrieves the specified KMS cluster 'ClusterIdString' server status. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [String] $KMSClusterId + ) + + Begin { + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + } + + Process { + $ClusterInfo = @() + if ($KMSClusterId) { + # Quit if the ClusterID cannot be found + $FindCluster = (Get-KMSCluster).Contains($KMSClusterId) + if (!$FindCluster) { + Write-Error "Cannot find the specified KMS ClusterId in vCenter Server!" + return + } + + $ClsInfo = New-Object VMware.Vim.KmipClusterInfo + $ProviderId = New-Object VMware.Vim.KeyProviderId + $ProviderId.Id = $KMSClusterId + $ClsInfo.ClusterId = $providerId + $ClsInfo.Servers = (Get-KMSClusterInfo -KMSClusterId $KMSClusterId).Servers + $ClusterInfo += $ClsInfo + $KMSClsStatus = $CM.RetrieveKmipServersStatus($ClusterInfo) + } else { + $ClusterInfo = Get-KMSClusterInfo + $KMSClsStatus = $CM.RetrieveKmipServersStatus($ClusterInfo) + } + + if ($KMSClsStatus) { + return $KMSClsStatus + } else { + Write-Error "Failed to get the KMS status`n" + return $null + } + } +} + +Function Get-DefaultKMSCluster { + <# + .SYNOPSIS + This cmdlet retrieves the default KMS cluster. + + .DESCRIPTION + This cmdlet retrieves the default KMS cluster. + + .EXAMPLE + C:\PS>Get-DefaultKMSCluster + + Retrieves the default KMS cluster. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + + return ($CM.KmipServers|where {$_.UseAsDefault}).ClusterId.Id +} + +Function Set-DefaultKMSCluster { + <# + .SYNOPSIS + This cmdlet sets the provided KMS cluster as the default KMS cluster. + + .DESCRIPTION + This cmdlet sets the provided KMS cluster as the default KMS cluster. + + .PARAMETER KMSClusterId + Specifies KMS cluster ID which will be used to mark as default KMS cluster. + + .EXAMPLE + C:\PS>Set-DefaultKMSCluster -KMSClusterId 'ClusterIdString' + + Sets the KMS cluster whose cluster ID is 'ClusterIdString' as the default KMS cluster. + + .NOTES + Author : Baoyin Qiao. + Author email : bqiao@vmware.com + Version : 1.0 + + ==========Tested Against Environment========== + VMware vSphere Hypervisor(ESXi) Version : 6.5 + VMware vCenter Server Version : 6.5 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 3.0 + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True)] + [String] $KMSClusterId + ) + + # Confirm the connected VIServer is vCenter Server + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + $ProviderId = New-Object VMware.Vim.KeyProviderId + $ProviderId.Id = $KMSClusterId + + $CM.MarkDefault($ProviderId) +} + +Function ConfirmIsVCenter{ + <# + .SYNOPSIS + This function confirms the connected VI server is vCenter Server. + + .DESCRIPTION + This function confirms the connected VI server is vCenter Server. + + .EXAMPLE + C:\PS>ConfirmIsVCenter + + Throws exception if the connected VIServer is not vCenter Server. + #> + + $SI = Get-View Serviceinstance + $VIType = $SI.Content.About.ApiType + + if ($VIType -ne "VirtualCenter") { + Throw "Operation requires vCenter Server!" + } +} + +Function ConfirmHardDiskIsValid { + <# + .SYNOPSIS + This function confirms the hard disks is valid. + + .DESCRIPTION + This function confirms the hard disks is valid. + + .PARAMETER VM + Specifies the VM which you want to used to validate against. + + .PARAMETER HardDisk + Specifies the hard disks which you want to use to validate. + + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine] $VM, + + [Parameter(Mandatory=$True)] + [VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.HardDisk[]] $HardDisk + ) + + $NonVMHardDisks = $HardDisk|Where {$_.Parent -ne $VM} + + if ($NonVMHardDisks.Length -ge 1) { + Throw "Some of the provided hard disks: $($NonVMHardDisks.FileName) do not belong to VM: $VM`n" + } +} + +Function MatchKeys { + <# + .SYNOPSIS + This function checks whether the given keys matched or not. + + .DESCRIPTION + This function checks whether the given keys matched or not with the provided KeyId or KMSClusterId. + + .PARAMETER KeyToMatch + Specifies the CryptoKey to match for. + + .PARAMETER KeyId + Specifies the keyId should be matched. + + .PARAMETER KMSClusterId + Specifies the KMSClusterId should be matched. + + .NOTES + Returns the true/false depends on the match result. + One of keyId or KMSClusterId parameter must be specified. + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True)] + [VMware.Vim.CryptoKeyId] $KeyToMatch, + + [Parameter(Mandatory=$false)] + [String] $KeyId, + + [Parameter(Mandatory=$false)] + [String] $KMSClusterId + ) + + Process { + if (!$KeyId -and !$KMSClusterId) { + Throw "One of the keyId or KMSClusterId must be specified!`n" + } + + $Match = $True + if ($KeyId -and ($KeyId -ne $KeyToMatch.KeyId)) { + $Match = $false + } + + if ($KMSClusterId) { + if (!$KeyToMatch.ProviderId) { + $Match = $false + } + + if ($KMSClusterId -ne $KeyToMatch.ProviderId.Id) { + $Match = $false + } + } + return $Match + } +} + +Function NewEncryptionKey { + <# + .SYNOPSIS + This function generates new encryption key from KMS. + + .DESCRIPTION + This function generates new encryption from KMS, if no KMSClusterId specified the default KMS will be used. + + .PARAMETER KMSClusterId + Specifies the KMS cluster id. + + .EXAMPLE + C:\PS>NewEncryptionKey -KMSClusterId 'ClusterIdString' + + Generates a new encryption key from the specified KMS which cluster id is 'ClusterIdString'. + #> + + Param ( + [Parameter(Mandatory=$False)] + [String]$KMSClusterId + ) + + # Confirm the connected VIServer is vCenter + ConfirmIsVCenter + + # Get the cryptoManager of vCenter Server + $CM = GetCryptoManager + $ProviderId = New-Object VMware.Vim.KeyProviderId + + Write-Verbose "Generate a CryptoKey.`n" + if ($KMSClusterId) { + $ProviderId.Id = $KMSClusterId + } else { + $ProviderId = $null + } + + $KeyResult = $CM.GenerateKey($ProviderId) + if (!$keyResult.Success) { + Throw "Key generation failed, make sure the KMS Cluster exists!`n" + } + return $KeyResult +} + +Function GetCryptoManager { + <# + .SYNOPSIS + This function retrieves the cryptoManager according to the given type. + + .DESCRIPTION + This function retrieves the cryptoManager according to the given type. + + .PARAMETER Type + Specifies the type of CryptoManager instance to get, the default value is KMS. + + .EXAMPLE + C:\PS>GetCryptoManager -Type "CryptoManagerKmip" + + Retrieves the 'CryptoManagerKmip' type CryptoManager. + #> + + Param ( + [Parameter(Mandatory=$false)] + [String] $Type + ) + + Process { + $SI = Get-View Serviceinstance + $CM = Get-View $SI.Content.CryptoManager + $cryptoMgrType = $CM.GetType().Name + + if (!$Type) { + # As the type is not cared, so return the CM directly + return $CM + } + if ($cryptoMgrType -eq $Type) { + return $CM + } + + Throw "Failed to get CryptoManager instance of the required type {$Type}!" + } +} + +Export-ModuleMember *-* diff --git a/Modules/apply-hardening.psm1 b/Modules/apply-hardening.psm1 new file mode 100644 index 0000000..94b1279 --- /dev/null +++ b/Modules/apply-hardening.psm1 @@ -0,0 +1,93 @@ +function Apply-Hardening { +<# + .NOTES + =========================================================================== + Created by: Markus Kraus + Twitter: @VMarkus_K + Private Blog: mycloudrevolution.com + =========================================================================== + Changelog: + 2016.11 ver 2.0 Base Release + =========================================================================== + External Code Sources: + + =========================================================================== + Tested Against Environment: + vSphere Version: 5.5 U2 + PowerCLI Version: PowerCLI 6.3 R1, PowerCLI 6.5 R1 + PowerShell Version: 4.0, 5.0 + OS Version: Windows 8.1, Server 2012 R2 + Keyword: VM, Hardening, Security + =========================================================================== + + .DESCRIPTION + Applys a set of Hardening options to your VMs + + .Example + Get-VM TST* | Apply-Hardening + + .Example + $SampleVMs = Get-VM "TST*" + Apply-Hardening -VMs $SampleVMs + + .PARAMETER VMs + Specify the VMs + + +#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=$True, + Position=0)] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl[]] + $VMs +) + +Process { +#region: Create Options + $ExtraOptions = @{ + "isolation.tools.diskShrink.disable"="true"; + "isolation.tools.diskWiper.disable"="true"; + "isolation.tools.copy.disable"="true"; + "isolation.tools.paste.disable"="true"; + "isolation.tools.dnd.disable"="true"; + "isolation.tools.setGUIOptions.enable"="false"; + "log.keepOld"="10"; + "log.rotateSize"="100000" + "RemoteDisplay.maxConnections"="2"; + "RemoteDisplay.vnc.enabled"="false"; + + } + if ($DebugPreference -eq "Inquire") { + Write-Output "VM Hardening Options:" + $ExtraOptions | Format-Table -AutoSize + } + + $VMConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + + Foreach ($Option in $ExtraOptions.GetEnumerator()) { + $OptionValue = New-Object VMware.Vim.optionvalue + $OptionValue.Key = $Option.Key + $OptionValue.Value = $Option.Value + $VMConfigSpec.extraconfig += $OptionValue + } +#endregion + +#region: Apply Options + ForEach ($VM in $VMs){ + $VMv = Get-VM $VM | Get-View + $state = $VMv.Summary.Runtime.PowerState + Write-Output "...Starting Reconfiguring VM: $VM " + $TaskConf = ($VMv).ReconfigVM_Task($VMConfigSpec) + if ($state -eq "poweredOn") { + Write-Output "...Migrating VM: $VM " + $TaskMig = $VMv.MigrateVM_Task($null, $_.Runtime.Host, 'highPriority', $null) + } + } + } +#endregion +} \ No newline at end of file diff --git a/Scripts/DatastoreSIOCStatistics.ps1 b/Scripts/DatastoreSIOCStatistics.ps1 new file mode 100644 index 0000000..0121b07 --- /dev/null +++ b/Scripts/DatastoreSIOCStatistics.ps1 @@ -0,0 +1,108 @@ +function Get-DatastoreSIOCStatCollection { +<# +.SYNOPSIS + Gathers information on the status of SIOC statistics collection for a datastore +.DESCRIPTION + Will provide the status on a datastore's SIOC statistics collection +.NOTES + Author: Kyle Ruddy, @kmruddy, thatcouldbeaproblem.com +.PARAMETER Datastore + Datastore to be ran against +.EXAMPLE + Get-DatastoreSIOCStatCollection -Datastore ExampleDatastore + Retreives the status of SIOC statistics collection for the provided datastore +#> +[CmdletBinding()] + param( + [Parameter(Mandatory=$true,Position=0,ValueFromPipelineByPropertyName=$true)] + $Datastore + ) + + Process { + + #Collect information about the desired datastore/s and verify existance + $ds = Get-Datastore $datastore -warningaction silentlycontinue -erroraction silentlycontinue + if (!$ds) {Write-Warning -Message "No Datastore found"} + else { + + $report = @() + + #Loops through each datastore provided and feeds back information about the SIOC Statistics Collection status + foreach ($item in $ds) { + + $tempitem = "" | select Name,SIOCStatCollection + $tempitem.Name = $item.Name + $tempitem.SIOCStatCollection = $item.ExtensionData.IormConfiguration.statsCollectionEnabled + $report += $tempitem + + } + + #Returns the output to the user + return $report + + } + + } + +} + + +function Set-DatastoreSIOCStatCollection { +<# +.SYNOPSIS + Configures the status of SIOC statistics collection for a datastore +.DESCRIPTION + Will modify the status on a datastore's SIOC statistics collection +.NOTES + Author: Kyle Ruddy, @kmruddy, thatcouldbeaproblem.com +.PARAMETER Datastore + Datastore to be ran against +.EXAMPLE + Set-DatastoreSIOCStatCollection -Datastore ExampleDatastore -Enable + Enables SIOC statistics collection for the provided datastore +#> +[CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory=$true,Position=0,ValueFromPipelineByPropertyName=$true)] + $Datastore, + [Switch]$Enable, + [Switch]$Disable + ) + + Process { + + #Collect information about the desired datastore/s and verify existance + $ds = Get-Datastore $datastore -warningaction silentlycontinue -erroraction silentlycontinue + if (!$ds) {Write-Warning -Message "No Datastore found"} + else { + + $report = @() + + #Loops through each datastore provided and modifies the SIOC Statistics Collection status + foreach ($dsobj in $ds) { + + $_this = Get-View -id 'StorageResourceManager-StorageResourceManager' + $spec = New-Object vmware.vim.storageiormconfigspec + + if ($Enable) { + + $spec.statsCollectionEnabled = $true + + } elseif ($Disable) { + + $spec.statsCollectionEnabled = $false + + } + + $_this.ConfigureDatastoreIORM_Task($dsobj.ExtensionData.MoRef,$spec) | out-null + start-sleep -s 1 + $report += Get-View -Id $dsobj.ExtensionData.MoRef -Property Name,Iormconfiguration.statsCollectionEnabled | select Name,@{N='SIOCStatCollection';E={$_.Iormconfiguration.statsCollectionEnabled}} + + } + + #Returns the output to the user + return $report + } + } + +} diff --git a/Scripts/Home Lab/Home Lab Delete settings.ps1 b/Scripts/Home Lab/Home Lab Delete settings.ps1 new file mode 100644 index 0000000..1846756 --- /dev/null +++ b/Scripts/Home Lab/Home Lab Delete settings.ps1 @@ -0,0 +1,28 @@ +$ESXIP = "192.168.1.201" +$ESXUser = "root" +$ESXPWD = "VMware1!" + +Connect-viserver $esxip -user $ESXUser -pass $ESXPWD + +#Leaving confirm off just in case someone happens to be connected to more than one vCenter/Host! +Get-VM | Stop-VM +Get-VM | Remove-VM + +$ESXCLI = Get-EsxCli -v2 -VMHost (get-VMHost) +$esxcli.vsan.cluster.leave.invoke() + +$VSANDisks = $esxcli.storage.core.device.list.invoke() | Where {$_.isremovable -eq "false"} | Sort size +$Performance = $VSANDisks[0] +$Capacity = $VSANDisks[1] + +$removal = $esxcli.vsan.storage.remove.CreateArgs() +$removal.ssd = $performance.Device +$esxcli.vsan.storage.remove.Invoke($removal) + +$capacitytag = $esxcli.vsan.storage.tag.remove.CreateArgs() +$capacitytag.disk = $Capacity.Device +$capacitytag.tag = "capacityFlash" +$esxcli.vsan.storage.tag.remove.Invoke($capacitytag) + +Set-VMHostSysLogServer $null +Remove-VMHostNtpServer (Get-VMHostNtpServer) -Confirm:$false \ No newline at end of file diff --git a/Scripts/Home Lab/Home Lab Deployment.ps1 b/Scripts/Home Lab/Home Lab Deployment.ps1 new file mode 100644 index 0000000..9cd1658 --- /dev/null +++ b/Scripts/Home Lab/Home Lab Deployment.ps1 @@ -0,0 +1,215 @@ +# ESX Start Host deployment Settings +$ESXIP = "192.168.1.201" +$ESXUser = "root" +$ESXPWD = "VMware1!" + +# VCSA Configuration +$VCSACDDrive = "D:\" +$SSODomainName = "corp.local" +$VCNAME = "VC01" +$VCUser = "Administrator@$SSODomainName" +$VCPass = "VMware1!" +$VCIP = "192.168.1.200" +$VCDNS = "192.168.1.1" +$VCGW = "192.168.1.1" +$VCNetPrefix = "24" +$VCSADeploymentSize = "tiny" + +# vCenter Configuration +$SSOSiteName = "Site01" +$datacenter = "DC01" +$cluster = "Cluster01" +$ntpserver = "pool.ntp.org" + +# VSAN Configuration +$VSANPolicy = '(("hostFailuresToTolerate" i1) ("forceProvisioning" i1))' +$VMKNetforVSAN = "Management Network" + +# General Settings +$verboseLogFile = "$ENV:Temp\vsphere65-NUC-lab-deployment.log" + +# End of configuration +Function My-Logger { + param( + [Parameter(Mandatory=$true)] + [String]$message + ) + + $timeStamp = Get-Date -Format "MM-dd-yyyy_hh:mm:ss" + + Write-Host -NoNewline -ForegroundColor White "[$timestamp]" + Write-Host -ForegroundColor Green " $message" + $logMessage = "[$timeStamp] $message" + $logMessage | Out-File -Append -LiteralPath $verboseLogFile +} + +$StartTime = Get-Date + +Write-Host "Writing Log files to $verboselogfile" -ForegroundColor Yellow +Write-Host "" + +If (-not (Test-Path "$($VCSACDDrive)vcsa-cli-installer\win32\vcsa-deploy.exe")){ + Write-Host "VCSA media not found at $($VCSACDDrive) please mount it and try again" + return +} +My-Logger "Connecting to ESXi Host: $ESXIP ..." +$connection = Connect-viserver $ESXIP -user $ESXUser -Password $ESXPWD -WarningAction SilentlyContinue + +My-Logger "Enabling SSH Service for future troubleshooting ..." +Start-VMHostService -HostService (Get-VMHost | Get-VMHostService | Where { $_.Key -eq "TSM-SSH"} ) | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Configuring NTP server to $ntpserver and retarting service ..." +Get-VMHost | Add-VMHostNtpServer $ntpserver | Out-File -Append -LiteralPath $verboseLogFile +Get-VMHost | Get-VMHostFirewallException | where {$_.Name -eq "NTP client"} | Set-VMHostFirewallException -Enabled:$true | Out-File -Append -LiteralPath $verboseLogFile +Get-VMHost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService | Out-File -Append -LiteralPath $verboseLogFile +Get-VMhost | Get-VmHostService | Where-Object {$_.key -eq "ntpd"} | Set-VMHostService -policy "automatic" | Out-File -Append -LiteralPath $verboseLogFile + +#Configure VSAN Bootstrap (http://www.virtuallyghetto.com/2013/09/how-to-bootstrap-vcenter-server-onto_9.html) +My-Logger "Setting the VSAN Policy for ForceProvisiong ..." +$esxcli = get-esxcli -V2 +$VSANPolicyDefaults = $esxcli.vsan.policy.setdefault.CreateArgs() +$VSANPolicyDefaults.policy = $VSANPolicy +$VSANPolicyDefaults.policyclass = "vdisk" +$esxcli.vsan.policy.setdefault.Invoke($VSANPolicyDefaults) | Out-File -Append -LiteralPath $verboseLogFile +$VSANPolicyDefaults.policyclass = "vmnamespace" +$esxcli.vsan.policy.setdefault.Invoke($VSANPolicyDefaults) | Out-File -Append -LiteralPath $verboseLogFile + +# Create new VSAN Cluster +My-Logger "Creating a new VSAN Cluster ..." +$esxcli.vsan.cluster.new.Invoke() | Out-File -Append -LiteralPath $verboseLogFile +$VSANDisks = $esxcli.storage.core.device.list.invoke() | Where {$_.isremovable -eq "false"} | Sort size +"Found the following disks to use for VSAN:" | Out-File -Append -LiteralPath $verboseLogFile +$VSANDisks | FT | Out-File -Append -LiteralPath $verboseLogFile +$Performance = $VSANDisks[0] +"Using $($Performance.Model) for Performance disk" | Out-File -Append -LiteralPath $verboseLogFile +$Capacity = $VSANDisks[1] +"Using $($Capacity.Model) for Capacity disk" | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Tagging $($Capacity.Model) as Capacity ..." +$capacitytag = $esxcli.vsan.storage.tag.add.CreateArgs() +$capacitytag.disk = $Capacity.Device +$capacitytag.tag = "capacityFlash" +$esxcli.vsan.storage.tag.add.Invoke($capacitytag) | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Create VSAN Diskgroup to back VSAN Cluster ..." +$addvsanstorage = $esxcli.vsan.storage.add.CreateArgs() +$addvsanstorage.ssd = $Performance.Device +$addvsanstorage.disks = $Capacity.device +$esxcli.vsan.storage.add.Invoke($addvsanstorage) | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Deploying VCSA using Script CLI + JSON ..." +$config = (get-content –raw “$($VCSACDDrive)vcsa-cli-installer\templates\install\embedded_vCSA_on_ESXi.json” ) | convertfrom-json +$config.'new.vcsa'.esxi.hostname = $ESXIP +$config.'new.vcsa'.esxi.username = $ESXUser +$config.'new.vcsa'.esxi.password = $ESXPWD +$config.'new.vcsa'.esxi.datastore = "vsanDatastore" +$config.'new.vcsa'.network.ip = $VCIP +$config.'new.vcsa'.network.'dns.servers'[0] = $VCDNS +$config.'new.vcsa'.network.gateway = $VCGW +$config.'new.vcsa'.network.'system.name' = $VCIP #Change to $VCName if you have DNS setup +$config.'new.vcsa'.network.prefix = $VCNetPrefix +$config.'new.vcsa'.os.password = $VCPass +$config.'new.vcsa'.appliance.'deployment.option' = $VCSADeploymentSize +$config.'new.vcsa'.sso.password = $VCPass +$config.'new.vcsa'.sso.'site-name' = $SSOSiteName +$config.'new.vcsa'.sso.'domain-name' = $SSODomainName +$config | convertto-json | set-content –path “$($ENV:Temp)\jsontemplate.json” +invoke-expression “$($VCSACDDrive)vcsa-cli-installer\win32\vcsa-deploy.exe install --no-esx-ssl-verify --accept-eula --acknowledge-ceip $($ENV:Temp)\jsontemplate.json” | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Enable VSAN Traffic on VMKernel Network ..." +$VMKernel = Get-VMHost $ESXIP | Get-VMHostNetworkAdapter -VMKernel | Where {$_.PortGroupName -eq $VMKNetforVSAN } +$IsVSANEnabled = $VMKernel | Where { $_.VsanTrafficEnabled} +If (-not $IsVSANEnabled) { + My-Logger "Enabling VSAN Kernel on $VMKernel ..." + $VMKernel | Set-VMHostNetworkAdapter -VsanTrafficEnabled $true -Confirm:$false | Out-File -Append -LiteralPath $verboseLogFile +} Else { + My-Logger "VSAN Kernel already enabled on $VmKernel ..." +} + +My-Logger "Disconnecting from ESXi Host: $ESXIP ..." +Disconnect-VIServer $ESXIP -Force -Confirm:$false -WarningAction SilentlyContinue + +My-Logger "Connecting to vCenter: $VCIP ..." +$connection = Connect-VIServer -Server $VCIP -User $VCUser -Password $vcpass -WarningAction SilentlyContinue + +My-Logger "Creating Datacenter: $datacenter ..." +New-Datacenter -Name $datacenter -Location (Get-Folder -Type Datacenter) | Out-File -Append -LiteralPath $verboseLogFile +My-Logger "Creating Cluster: $cluster ..." +New-Cluster -Name $cluster -Location (Get-Datacenter -Name $datacenter) -DrsEnabled -VsanEnabled | Out-File -Append -LiteralPath $verboseLogFile +My-Logger "Adding ESXi Host $ESXIP to vCenter ..." +Add-VMHost -Location (Get-Cluster -Name $cluster) -User $ESXUser -Password $ESXPWD -Name $ESXIP -Force | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Setting the VCSA NTP server to: $NTPServer ..." +Connect-CISServer -Server $VCIP -User $VCUser -Password $VCPass +(Get-CISService com.vmware.appliance.techpreview.ntp.server).set(@($NTPServer)) | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Configuring Host syslog to VC ..." +Get-VMHost | Set-VMHostSysLogServer -SysLogServer $VCIP | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Acknowledging Alarms on the cluster ..." +$alarmMgr = Get-View AlarmManager +Get-Cluster | where {$_.ExtensionData.TriggeredAlarmState} | %{ + $cluster = $_ + $Cluster.ExtensionData.TriggeredAlarmState | %{ + $alarmMgr.AcknowledgeAlarm($_.Alarm,$vm.ExtensionData.MoRef) | Out-File -Append -LiteralPath $verboseLogFile + } +} + +My-Logger "Creating @lamw Content Library with Nested ESXi Images ..." + +# Get a Datastore to create the content library on +$datastoreID = (Get-Datastore "vsanDatastore").extensiondata.moref.value + +# Get the Service that works with Subscribed content libraries +$ContentCatalog = Get-CisService com.vmware.content.subscribed_library + +# Create a Subscribed content library on an existing datastore +$createSpec = $ContentCatalog.help.create.create_spec.CreateExample() +$createSpec.subscription_info.authentication_method = "NONE" +$createSpec.subscription_info.ssl_thumbprint = "69:d9:9e:e9:0b:4b:68:24:09:2b:ce:14:d7:4a:f9:8c:bd:c6:5a:e9" +$createSpec.subscription_info.automatic_sync_enabled = $true +$createSpec.subscription_info.subscription_url = "https://s3-us-west-1.amazonaws.com/vghetto-content-library/lib.json" +$createSpec.subscription_info.on_demand = $false +$createSpec.subscription_info.password = $null +$createSpec.server_guid = $null +$createspec.name = "virtuallyGhetto CL" +$createSpec.description = "@lamw CL: http://www.virtuallyghetto.com/2015/04/subscribe-to-vghetto-nested-esxi-template-content-library-in-vsphere-6-0.html" +$createSpec.type = "SUBSCRIBED" +$createSpec.publish_info = $null +$datastoreID = [VMware.VimAutomation.Cis.Core.Types.V1.ID]$datastoreID +$StorageSpec = New-Object PSObject -Property @{ + datastore_id = $datastoreID + type = "DATASTORE" + } +$CreateSpec.storage_backings.Add($StorageSpec) +$UniqueID = [guid]::NewGuid().tostring() +$ContentCatalog.create($UniqueID, $createspec) | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Changing the default VSAN VM Storage Policy to FTT=0 & Force Provisioning to Yes ..." +$VSANPolicy = Get-SpbmStoragePolicy "Virtual SAN Default Storage Policy" +$Ruleset = New-SpbmRuleSet -Name “Rule-set 1” -AllOfRules @((New-SpbmRule -Capability VSAN.forceProvisioning $True), (New-SpbmRule -Capability VSAN.hostFailuresToTolerate 0)) +$VSANPolicy | Set-SpbmStoragePolicy -RuleSet $Ruleset | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Enabling VM Autostart for the VCSA VM ..." +$VCVM = Get-VM +$vmstartpolicy = Get-VMStartPolicy -VM $VCVM +Set-VMHostStartPolicy (Get-VMHost $ESXIP | Get-VMHostStartPolicy) -Enabled:$true | Out-File -Append -LiteralPath $verboseLogFile +Set-VMStartPolicy -StartPolicy $vmstartpolicy -StartAction PowerOn -StartDelay 0 | Out-File -Append -LiteralPath $verboseLogFile + +My-Logger "Enabling SSH on VCSA for easier troubleshooting ..." +$vcsassh = Get-CIsService com.vmware.appliance.access.ssh +$vcsassh.set($true) + +$EndTime = Get-Date +$duration = [math]::Round((New-TimeSpan -Start $StartTime -End $EndTime).TotalMinutes,2) + +My-Logger "================================" +My-Logger "vSphere Lab Deployment Complete!" +My-Logger "StartTime: $StartTime" +My-Logger " EndTime: $EndTime" +My-Logger " Duration: $duration minutes" +Write-Host "" +My-Logger "Access the vSphere Web Client at https://$VCIP/vsphere-client/" +My-Logger "Access the HTML5 vSphere Web Client at https://$VCIP/ui/" +My-Logger "Browse the vSphere REST APIs using the API Explorer here: https://$VCIP/apiexplorer/" +My-Logger "================================" diff --git a/Scripts/New-ClusterHostGroup.ps1 b/Scripts/New-ClusterHostGroup.ps1 new file mode 100644 index 0000000..c5cb9e7 --- /dev/null +++ b/Scripts/New-ClusterHostGroup.ps1 @@ -0,0 +1,43 @@ +<# + .NOTES + =========================================================================== + Script name: New-ClusterHostGroup.ps1 + Created on: 2016-10-25 + Author: Peter D. Jorgensen (@pjorg, pjorg.com) + Dependencies: None known + ===Tested Against Environment==== + vSphere Version: 5.5, 6.0 + PowerCLI Version: PowerCLI 6.5R1 + PowerShell Version: 5.0 + OS Version: Windows 10, Windows 7 + =========================================================================== + .DESCRIPTION + Creates a DRS Host Group in a vSphere cluster. + .Example + $ProdCluster = Get-Cluster *prod* + $OddHosts = $ProdCluster | Get-VMHost | ?{ $_.Name -match 'esxi-\d*[13579]+.\lab\.local' } + .\New-ClusterHostGroup.ps1 -Name 'OddProdHosts' -Cluster $ProdCluster -VMHost $OddHosts +#> +[CmdletBinding()] +Param( + [Parameter(Mandatory=$True,Position=1)] + [String]$Name, + [Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=2)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.Cluster]$Cluster, + [Parameter(Mandatory=$False,Position=3)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VMHost[]]$VMHost +) + +$NewGroup = New-Object VMware.Vim.ClusterHostGroup -Property @{ + 'Name'=$Name + 'Host'=$VMHost.Id +} + +$spec = New-Object VMware.Vim.ClusterConfigSpecEx -Property @{ + 'GroupSpec'=(New-Object VMware.Vim.ClusterGroupSpec -Property @{ + 'Info'=$NewGroup + }) +} + +$ClusterToReconfig = Get-View -VIObject $Cluster -Property Name +$ClusterToReconfig.ReconfigureComputeResource($spec, $true) \ No newline at end of file diff --git a/Scripts/New-ClusterVmGroup.ps1 b/Scripts/New-ClusterVmGroup.ps1 new file mode 100644 index 0000000..b194a64 --- /dev/null +++ b/Scripts/New-ClusterVmGroup.ps1 @@ -0,0 +1,43 @@ +<# + .NOTES + =========================================================================== + Script name: New-ClusterVmGroup.ps1 + Created on: 2016-10-25 + Author: Peter D. Jorgensen (@pjorg, pjorg.com) + Dependencies: None known + ===Tested Against Environment==== + vSphere Version: 5.5, 6.0 + PowerCLI Version: PowerCLI 6.5R1 + PowerShell Version: 5.0 + OS Version: Windows 10, Windows 7 + =========================================================================== + .DESCRIPTION + Creates a DRS VM Group in a vSphere cluster. + .Example + $ProdCluster = Get-Cluster *prod* + $EvenVMs = $ProdCluster | Get-VM | ?{ $_.Name -match 'MyVM-\d*[02468]+' } + .\New-ClusterVmGroup.ps1 -Name 'EvenVMs' -Cluster $ProdCluster -VM $EvenVMs +#> +[CmdletBinding()] +Param( + [Parameter(Mandatory=$True,Position=1)] + [String]$Name, + [Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=2)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.Cluster]$Cluster, + [Parameter(Mandatory=$False,Position=3)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine[]]$VM +) + +$NewGroup = New-Object VMware.Vim.ClusterVmGroup -Property @{ + 'Name'=$Name + 'VM'=$VM.Id +} + +$spec = New-Object VMware.Vim.ClusterConfigSpecEx -Property @{ + 'GroupSpec'=(New-Object VMware.Vim.ClusterGroupSpec -Property @{ + 'Info'=$NewGroup + }) +} + +$ClusterToReconfig = Get-View -VIObject $Cluster -Property Name +$ClusterToReconfig.ReconfigureComputeResource($spec, $true) \ No newline at end of file diff --git a/Scripts/New-ClusterVmHostRule.ps1 b/Scripts/New-ClusterVmHostRule.ps1 new file mode 100644 index 0000000..217cbeb --- /dev/null +++ b/Scripts/New-ClusterVmHostRule.ps1 @@ -0,0 +1,48 @@ +<# + .NOTES + =========================================================================== + Script name: New-ClusterVmHostRule.ps1 + Created on: 2016-10-25 + Author: Peter D. Jorgensen (@pjorg, pjorg.com) + Dependencies: None known + ===Tested Against Environment==== + vSphere Version: 5.5, 6.0 + PowerCLI Version: PowerCLI 6.5R1 + PowerShell Version: 5.0 + OS Version: Windows 10, Windows 7 + =========================================================================== + .DESCRIPTION + Creates a VM to Host affinity rule in a vSphere cluster. + .Example + $ProdCluster = Get-Cluster *prod* + .\New-ClusterVmHostRule.ps1 -Name 'Even VMs to Odd Hosts' -AffineHostGroupName 'OddHosts' -VMGroupName 'EvenVMs' -Enabled:$true -Cluster $ProdCluster +#> +[CmdletBinding()] +Param( + [Parameter(Mandatory=$True,Position=1)] + [String]$Name, + [Parameter(Mandatory=$True,Position=2)] + [String]$AffineHostGroupName, + [Parameter(Mandatory=$True,Position=3)] + [String]$VMGroupName, + [Parameter(Mandatory=$False,Position=4)] + [Switch]$Enabled=$True, + [Parameter(Mandatory=$True,ValueFromPipeline=$True,Position=5)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.Cluster]$Cluster +) + +$NewRule = New-Object VMware.Vim.ClusterVmHostRuleInfo -Property @{ + 'AffineHostGroupName'=$AffineHostGroupName + 'VmGroupName'=$VMGroupName + 'Enabled'=$Enabled + 'Name'=$Name +} + +$spec = New-Object VMware.Vim.ClusterConfigSpecEx -Property @{ + 'RulesSpec'=(New-Object VMware.Vim.ClusterRuleSpec -Property @{ + 'Info'=$NewRule + }) +} + +$ClusterToReconfig = Get-View -VIObject $Cluster -Property Name +$ClusterToReconfig.ReconfigureComputeResource($spec, $true) \ No newline at end of file diff --git a/Scripts/Start-VMHostSsh.ps1 b/Scripts/Start-VMHostSsh.ps1 new file mode 100644 index 0000000..9a0a84f --- /dev/null +++ b/Scripts/Start-VMHostSsh.ps1 @@ -0,0 +1,31 @@ +<# + .NOTES + =========================================================================== + Script name: Start-VMHostSsh.ps1 + Created on: 2016-07-01 + Author: Peter D. Jorgensen (@pjorg, pjorg.com) + Dependencies: None known + ===Tested Against Environment==== + vSphere Version: 5.5, 6.0 + PowerCLI Version: PowerCLI 6.5R1 + PowerShell Version: 5.0 + OS Version: Windows 10, Windows 7 + =========================================================================== + .DESCRIPTION + Starts the TSM-SSH service on VMHosts. + .Example + .\Start-VMHostSsh -VMHost (Get-VMHost -Name 'esxi-001.lab.local') + .Example + $OddHosts = Get-VMHost | ?{ $_.Name -match 'esxi-\d*[13579]+.\lab\.local' } + .\Start-VMHost -VMHost $OddHosts +#> +[CmdletBinding()] +Param( + [Parameter(ValueFromPipeline=$True,Mandatory=$True,Position=0)] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl[]]$VMHost +) + +Process { + $svcSys = Get-View $VMHost.ExtensionData.ConfigManager.ServiceSystem + $svcSys.StartService('TSM-SSH') +} diff --git a/Scripts/Stop-VMHostSsh.ps1 b/Scripts/Stop-VMHostSsh.ps1 new file mode 100644 index 0000000..57541aa --- /dev/null +++ b/Scripts/Stop-VMHostSsh.ps1 @@ -0,0 +1,31 @@ +<# + .NOTES + =========================================================================== + Script name: Stop-VMHostSsh.ps1 + Created on: 2016-07-01 + Author: Peter D. Jorgensen (@pjorg, pjorg.com) + Dependencies: None known + ===Tested Against Environment==== + vSphere Version: 5.5, 6.0 + PowerCLI Version: PowerCLI 6.5R1 + PowerShell Version: 5.0 + OS Version: Windows 10, Windows 7 + =========================================================================== + .DESCRIPTION + Stops the TSM-SSH service on VMHosts. + .Example + .\Stop-VMHostSsh -VMHost (Get-VMHost -Name 'esxi-001.lab.local') + .Example + $EvenHosts = Get-VMHost | ?{ $_.Name -match 'esxi-\d*[02468]+.\lab\.local' } + .\Stop-VMHost -VMHost $EvenHosts +#> +[CmdletBinding()] +Param( + [Parameter(ValueFromPipeline=$True,Mandatory=$True,Position=0)] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl[]]$VMHost +) + +Process { + $svcSys = Get-View $VMHost.ExtensionData.ConfigManager.ServiceSystem + $svcSys.StopService('TSM-SSH') +} diff --git a/Scripts/vTool_2016aug.ps1 b/Scripts/vTool_2016aug.ps1 new file mode 100644 index 0000000..f831d7a --- /dev/null +++ b/Scripts/vTool_2016aug.ps1 @@ -0,0 +1,4215 @@ +<# +.SYNOPSIS + A handy multi purpose tool to get those things done quickly +.DESCRIPTION + This is an onging VMware tool to help those with an VMware environment to automate certain repetative tasks +.NOTES + File Name : vTool.ps1 + Author : gajendra d ambi + updated : August 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +##Start of the script## +Clear-Host #Clear the screen. + +#start of function +function PcliPshell +{ +<# +.SYNOPSIS + Integrate powercli into powershell +.DESCRIPTION + This will add pssnapins/modules of vmware powercli into powershell. You will get + powercli core, vds and vum scriptlets/snapsins/modules in powershell which will enable you + to create, run powercli scripts into powershell ISE since powercli itself lacks an IDE. +.NOTES + File Name : PcliPshell.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/MrAmbiG/vmware +#> +#Start of script# +Import-Module VMware.VimAutomation.Core -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.Vds -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.Cis.Core -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.Storage -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.vROps -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.HA -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.License -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.Cloud -ErrorAction SilentlyContinue +Import-Module VMware.VimAutomation.PCloud -ErrorAction SilentlyContinue +Import-Module VMware.VumAutomation -ErrorAction SilentlyContinue +#End of Script# +}#End of function + +#------------------------------Start of Collection of Functions of automation------------------------------# + +#Start of function +function GetPlink +{ +<# +.SYNOPSIS + Gets the plink +.DESCRIPTION + This will make sure plink is either downloaded from the internet if it is not present and if it cannot download + then it will pause the script till you copy it manually. +.NOTES + File Name : GetPlink.ps1 + Author : gajendra d ambi + Date : Audust 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: + github.com/mrambig + [source] http://www.virtu-al.net/2013/01/07/ssh-powershell-tricks-with-plink-exe/ + +#> +$PlinkLocation = $PSScriptRoot + "\Plink.exe" +$presence = Test-Path $PlinkLocation +if (-not $presence) + { + Write-Host "Missing Plink.exe, trying to download...(10 seconds)" -BackgroundColor White -ForegroundColor Black + Invoke-RestMethod "http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe" -TimeoutSec 10 -OutFile "plink.exe" + if (-not $presence) + { + do + { + Write-Host "Unable to download plink.exe, please download and add it to the same folder as this script" -BackgroundColor Yellow -ForegroundColor Black + Read-host "Hit Enter/Return once plink is present" + $presence = Test-Path $PlinkLocation + } while (-not $presence) + } + } + +if ($presence) { Write-Host "Detected Plink.exe" -BackgroundColor White -ForegroundColor Black } +} #End of function + +#start of function +function FaultToleranceOff +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : FaultToleranceOff.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -FaultToleranceLoggingEnabled $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +Function HostPerf +{ +<# +.SYNOPSIS + Set esxi host performance level +.DESCRIPTION + This will change the host's performance level to the following. +.NOTES + File Name : VssPmOn.ps1 + Author : gajendra d ambi + Date : August 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "choose a number from below +1. High performance +2. Balanced +3. LowPower +" -BackgroundColor White -ForegroundColor Black +$option = Read-Host "?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) +{$vmhost.Name +(Get-View (Get-VMHost $vmhost | Get-View).ConfigManager.PowerSystem).ConfigurePowerPolicy($option) +} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#Start of function +function NicStatusPg +{ +<# +.SYNOPSIS + Change nic teaming of nics. +.DESCRIPTION + This will change the nic status on portgroups +.NOTES + File Name : NicStatusPg.ps1 + Author : gajendra d ambi + Date : July 2016 + Prerequisite : PowerShell v4+, powercli 6.3+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/MrAmbiG/vmware +#> +#Start of Script +$cluster = Read-Host "cluster[type * to include all clusters]?" +$pg = Read-Host "standard portgroup?" +$nic = Read-Host "vmnic (ex:vmnic5)?" + +Write-host " +1 . MakeNicActive +2 . MakeNicStandby +3 . MakeNicUnused +" -BackgroundColor white -ForegroundColor black +Write-Host choose from 1 to 3 from above -BackgroundColor Yellow -ForegroundColor Black +$option = Read-Host " " + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$vmhosts = get-cluster $cluster | get-vmhost | sort + +$vmhosts = get-cluster $cluster | get-vmhost | sort +foreach ($vmhost in $vmhosts) +{ +$vmnic = get-vmhost $vmhost | Get-VMHostNetworkAdapter -Physical -Name $nic + if ($option -eq 1) + {#MakeNicActive + get-vmhost $vmhost | get-virtualportgroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive $vmnic -Confirm:$false + } + if ($option -eq 2) + {#MakeNicStandby + get-vmhost $vmhost | get-virtualportgroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicStandby $vmnic -Confirm:$false + } + if ($option -eq 3) + {#MakeNicUnused + get-vmhost $vmhost | get-virtualportgroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicUnused $vmnic -Confirm:$false + } +} +} #end of function + +#start of function +function NicStatusVss +{ +<# +.SYNOPSIS + Change nic teaming of nics. +.DESCRIPTION + This will change the nic status on vSwitchs +.NOTES + File Name : NicStatusVss.ps1 + Author : gajendra d ambi + Date : July 2016 + Prerequisite : PowerShell v4+, powercli 6.3+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/MrAmbiG/vmware +#> + +#Start of Script +$cluster = Read-Host "cluster[type * to include all clusters]?" +$vss = Read-Host "vSphere standard Switch?" +$nic = Read-Host "vmnic (ex:vmnic5)?" + +Write-host " +1 . Add Nic +2 . Remove Nic +3 . MakeNicActive +4 . MakeNicStandby +5 . MakeNicUnused +" -BackgroundColor white -ForegroundColor black +Write-Host choose from 1 to 5 from above -BackgroundColor Yellow -ForegroundColor Black +$option = Read-Host " " + + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$vmhosts = get-cluster $cluster | get-vmhost | sort +foreach ($vmhost in $vmhosts) +{ +$vmnic = get-vmhost $vmhost | Get-VMHostNetworkAdapter -Physical -Name $nic + if ($option -eq 1 ) + { + #add vmnic + get-vmhost $vmhost | get-virtualswitch -Name $vss | Add-VirtualSwitchPhysicalNetworkAdapter -VMHostPhysicalNic $vmnic -confirm:$false + get-vmhost $vmhost | get-virtualswitch -Name $vss | Get-NicTeamingPolicy + } + + if ($option -eq 2 ) + { + #remove vmnic + get-vmhost $vmhost | Get-VMHostNetworkAdapter -Physical -Name $nic | Remove-VirtualSwitchPhysicalNetworkAdapter -confirm:$false + get-vmhost $vmhost | get-virtualswitch -Name $vss | Get-NicTeamingPolicy + } + + if ($option -eq 3 ) + { + #Make active + Get-VMHost $vmhost | get-virtualswitch -Name $vss | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicActive $vmnic -confirm:$false + } + + if ($option -eq 4 ) + { + #make standby + Get-VMHost $vmhost | get-virtualswitch -Name $vss | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicStandby $vmnic -confirm:$false + } + + if ($option -eq 5 ) + { + #make unused + Get-VMHost $vmhost | get-virtualswitch -Name $vss | Get-NicTeamingPolicy | Set-NicTeamingPolicy -MakeNicUnused $vmnic -confirm:$false + } +} +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function WinSSH +{ +<# +.SYNOPSIS + Run SSH commands from windows +.DESCRIPTION + This will run commands to be run on VMware/vCenter hosts. + This needs plink to be in the same folder as this script. + This will open create a text file, you paste the commands which are to be run on the SSH target. +.NOTES + File Name : WinSSH.ps1 + Author : gajendra d ambi + Date : June 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/MrAmbiG/vmware + http://www.virtu-al.net/2013/01/07/ssh-powershell-tricks-with-plink-exe/ +#> +#Start of Script +GetPlink #custom function gets plink.exe #https://github.com/MrAmbiG/vmware/blob/master/vTool/vToolMenus/MainMenu/vCenterMenu/HostMenu/GetPlink.ps1 + +#server's credentials +$user = Read-Host "Host's username?" +$pass = Read-Host "Host's password?" +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$VMHosts = get-cluster $cluster | Get-VMHost | sort + +#copy plink to c:\ for now +Copy-Item $PSScriptRoot\plink.exe C:\ + +$name = "commands" +$commands = "$PSScriptRoot\$name.txt" #create text file +ni -ItemType file $commands -Force +ac $commands "#Paste your each command in a new line which you want to run on each host" +Start-Process $commands + +Read-Host "Hit Return/Enter once you are done copying the commands to the pop up text" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() #timer start +$stopWatch.Start() + +$lines = gc $commands + +Copy-Item $PSScriptRoot\plink.exe C:\ #copy plink to c:\ for now + +ForEach ($VMHost in $VMHosts) + { + Write-Host $vmhost.Name -ForegroundColor Black -BackgroundColor White + Get-VMHost $VMHost | Get-VMHostService | where {$_.Key -eq "TSM-SSH"} | Start-VMHostService -confirm:$false #start ssh + echo y | C:\plink.exe -ssh $user@$VMHost -pw $pass "exit" #store ssh keys + foreach ($line in $lines) + { + C:\plink.exe -ssh -v -noagent $VMHost -l $user -pw $pass "$line" + } + Get-VMHost $VMHost | Get-VMHostService | where {$_.Key -eq "TSM-SSH"} | Stop-VMHostService -confirm:$false #stop ssh + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function DrsVmGroup +{ +<# +.SYNOPSIS + Create DrsVmGroup DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS DrsVmGroup rules between VMs where VMs will be made to stay on the same host by the DRS. +.NOTES + File Name : DrsVmGroup.ps1 + Author : gajendra d ambi + Date : February 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "Name of the Cluster?" +$VMs = Read-Host "Type the Name of the VM/VMs (separated only by a comma and no spaces)" +$VMs = $VMs.split(',') +$vmgroup = Read-Host "Type the Name of the VM group" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VM $VMs | New-DrsVmGroup -Name $vmgroup -Cluster $cluster + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function shAddNic +{ +<# +.SYNOPSIS + Create New VMware Standard Switch on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to all the 10 hosts and + Then it will add physical nics to the standard switch. +.NOTES + File Name : shAddNic.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$vss = Read-Host "name of the vSphere standard Switch?" +$newnic = Read-Host "Name of the Nic (ex:vmnic5)?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) { + $vmnic = get-vmhost $vmhost | Get-VMHostNetworkAdapter -Physical -Name $newnic + get-vmhost $vmhost | get-virtualswitch -Name $vss | Add-VirtualSwitchPhysicalNetworkAdapter -VMHostPhysicalNic $vmnic -confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function l3vmotion +{ +<# +.SYNOPSIS + Configure l3 vmotion. +.DESCRIPTION + It will + create the l3 vmotion portgroup + add vmk to the portgroup + assign vlan to the portgroup + add ip, subnet mask to the portgroup + enable netstack l3 vmotion for the portgroup + 1. update the default gateway manually for now +.NOTES + File Name : l3vmotion.ps1 + Author : gajendra d ambi + Date : June 2016 + Prerequisite : PowerShell v4+, powercli 6.3+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/MrAmbiG/vmware + https://communities.vmware.com/thread/519794?start=0&tstart=0 (inok) +#> +#Start of Script +Write-Host " +Don't forget to add gateway after it's completion +" -BackgroundColor White -ForegroundColor Black + +$cluster = Read-Host "Name of the cluster?" +$vss = Read-Host "Name of the vSwitch?" +$pg = Read-Host "name of the portgroup?" +$vlan = Read-Host "vlan?" +$ip = Read-Host "What is the 1st vmkernel ip address?" +$mask = Read-Host "subnet mask?" +$vmk = Read-Host "vmk number? ex: vmk7?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$a = $ip.Split('.')[0..2] +#first 3 octets of the ip address +$b = [string]::Join(".",$a) + +#last octet of the ip address +$c = $ip.Split('.')[3] +$c = [int]$c + +$vmhosts = get-cluster $cluster | get-vmhost | sort +foreach ($vmhost in $vmhosts) + { + Get-VMHost $vmhost | Get-VirtualSwitch -Name $vss | New-VirtualPortGroup $pg -VLanId $vlan -Confirm:$false #creating new VM portgroup + $esxcli = get-vmhost $vmhost | get-esxcli + $esxcli.network.ip.netstack.add($false, "vmotion") #enabling and adding vmotion tcp/ip stack (netstack) + $esxcli.network.ip.interface.add($null, $null, "$vmk", $null, "1500", "vmotion", "$pg") + $esxcli.network.ip.interface.ipv4.set("$vmk", "$b.$(($c++))", "$mask", $null, "static") #update ip informaiton to the vmk + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +##start of function +function shGetShHosts +{ +<# +.SYNOPSIS + Connect to standalone hosts +.DESCRIPTION + This will get the 1st host's ip address and increment it to a number specified by the user and connect to all of them. +.NOTES + File Name : shGetShHosts.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# + +$1sthost = Read-Host "1st host's ip address?" +$max = Read-Host "total number of esxi hosts that you want to configure?" +$user = Read-Host "ESXi username?" +$pass = Read-Host "ESXi password?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +#generate the range of ip addresses of hosts +$fixed = $1sthost.Split('.')[0..2] +$last = [int]($1sthost.Split('.')[3]) +$maxhosts = $max - 1 +$hosts = +$last..($last + $maxhosts) | %{ + [string]::Join('.',$fixed) + "." + $_ +} + +#connect to all hosts +connect-viserver $hosts -User $user -Password $pass + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +}#End of function + +#start of function +function shShootVmPg +{ +<# +.SYNOPSIS + Create New VMware Standard Switch on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to all the 10 hosts and + Then it will Remove VM portgroup. +.NOTES + File Name : shShootVmPg.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$pg = Read-Host "Name of the portgroup?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VMHost | Get-VirtualPortGroup -Name $pg | Remove-VirtualPortGroup -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +function ShootVmkPg +{ +<# +.SYNOPSIS + Remove vmkernel portgroup +.DESCRIPTION + This will remove the virtual machine portgroup of all the hosts of a cluster/clusters. +.NOTES + File Name : ShootVmkPg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) + { + $vmk = Get-VMHostNetworkAdapter -VMHost $vmhost | where PortgroupName -eq $pg + Write-Host "removing vmkernel from the $pg on $vmhost" + Remove-VMHostNetworkAdapter -Nic $vmk -confirm:$false + + Write-Host "removing $pg on $vmhost" + get-vmhost $vmhost | get-virtualportgroup -Name $pg | Remove-VirtualPortGroup -Confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +function shRenamePg +{ +<# +.SYNOPSIS + Create New VMware Standard Switch on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to them all the 10 hosts. + Then it will rename the esxi host's portgroup. +.NOTES + File Name : shRenamePg.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$oldpg = Read-Host "Old Name of the portgroup?" +$newpg = Read-Host "New Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VMHost | Get-VirtualPortGroup -Name $oldpg | Set-VirtualPortGroup -Name $newpg -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function shNewVss +{ +<# +.SYNOPSIS + Create New VMware Standard Switch on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to all of the 10 hosts. + Then it will create a new vswitch based on your input. +.NOTES + File Name : shNewVss.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$vss = Read-Host "name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +get-vmhost | New-VirtualSwitch -Name $vss -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +##start of function +function shNewVMPg +{ +<# +.SYNOPSIS + Create New VMware Standard Swiportgroup on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to all of the 10 hosts and + Then it will create a new virtual machine portgroup based on your input. +.NOTES + File Name : shNewVMPg.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$vss = Read-Host "name of the vSwitch?" +$pg = Read-Host "name of the portgroup?" +$vlan = Read-Host "vlan?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +get-vmhost | Get-VirtualSwitch -Name $vss | New-VirtualPortGroup -Name $pg -VLanId $vlan -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +function shNewVMkernelPg +{ +<# +.SYNOPSIS + Create New VMware Standard Swiportgroup on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to all of the 10 hosts and + Then it will create a new vmkernel portgroup based on your input. +.NOTES + File Name : shNewVMkernelPg.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$vss = Read-Host "name of the vSwitch?" +$pg = Read-Host "name of the portgroup?" +$vlan = Read-Host "vlan?" + +$ip = Read-Host "What is the 1st vmkernel ip address?" +$mask = Read-Host "subnet mask?" +$vmk = Read-Host "vmk number? ex: vmk7?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +get-vmhost | Get-VirtualSwitch -Name $vss | New-VirtualPortGroup -Name $pg -VLanId $vlan -Confirm:$false + +$a = $ip.Split('.')[0..2] +#first 3 octets of the ip address +$b = [string]::Join(".",$a) + +#last octet of the ip address +$c = $ip.Split('.')[3] +$c = [int]$c + + foreach ($vmhost in (get-vmhost | sort)){ + $esxcli = get-vmhost $vmhost | Get-EsxCli + $esxcli.network.ip.interface.add($null, $null, "$vmk", $null, "1500", $null, "$pg") #add vmkernel to the portgroup + $esxcli.network.ip.interface.ipv4.set("$vmk", "$b.$(($c++))", "$mask", $null, "static") #update ip informaiton to the vmkernel + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + }#End of Script# +}#End of function + +#start of function +function shShootVmkPg +{ +<# +.SYNOPSIS + Create New VMware Standard Switch on all hosts +.DESCRIPTION + This will need the 1st host's ip address and the number of subsequent hosts that you want to configure(which should be in series of the ip address). + Lets say you have 10 esxi hosts and the 1st host's ip is 1.1.1.1 then you have to provide the 1st host's ip address and the number of hosts + as an input to this script which will do +1 to the last octet of the 1st host's ip address and connect to all the 10 hosts and + Then it will Remove vmkernel portgroup. +.NOTES + File Name : ShootVmkPg.ps1 + Author : gajendra d ambi + Date : April 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$pg = Read-Host "Name of the portgroup?" + foreach ($vmhost in (get-vmhost | sort)) + { + $vmk = Get-VMHostNetworkAdapter -VMHost $vmhost | where PortgroupName -eq $pg + Write-Host "removing vmkernel from the $pg on $vmhost" + Remove-VMHostNetworkAdapter -Nic $vmk -confirm:$false + + Write-Host "removing $pg on $vmhost" + get-vmhost $vmhost | get-virtualportgroup -Name $pg | Remove-VirtualPortGroup -Confirm:$false + }#End of Script# +}#End of function + +#start of function +function PgSync +{ +<# +.SYNOPSIS + Sync portgroups properties with vSwitch +.DESCRIPTION + This will make the portgroup to sync itself with the vswitch's settings. this will make the portgroup inherit the following from the vSwitch + LoadBalancingPolicy + NetworkFailoverDetectionPolicy + NotifySwitches + FailoverOrder +.NOTES + File Name : PowerMgmt.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +get-cluster $cluster | Get-VMHost | sort | Get-virtualswitch -Standard | Get-VirtualPortGroup -Name $pg | get-nicteamingpolicy | Set-NicTeamingPolicy -InheritLoadBalancingPolicy $true -InheritNetworkFailoverDetectionPolicy $true -InheritNotifySwitches $true -InheritFailback $true -InheritFailoverOrder $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function AddHosts +{ +<# +.SYNOPSIS + Add hosts to cluster. +.DESCRIPTION + This will add hosts to the specified clusters. The function will create a csv file which can be opened in excel. + populate the values under their respective headers in the excel. save it. close it. Hit return/enter to proceed. + Then the script will use the values from csv file and add hosts to the cluster(s). +.NOTES + File Name : AddHosts.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script + +Write-Host " +A CSV file will be opened (open in excel/spreadsheet) +populate the values, +save & close the file, +Hit Enter to proceed +" -ForegroundColor Blue -BackgroundColor White +$csv = "$PSScriptRoot/addhosts.csv" +get-process | Select-Object cluster,hostname,username,password | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation +Start-Process $csv +Read-Host "Hit Enter/Return to proceed" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$csv = Import-Csv $csv + foreach ($line in $csv) + { + $cluster = $($line.cluster) + $vmhost = $($line.hostname) + $user = $($line.username) + $pass = $($line.password) + Add-VMHost $vmhost -Location (get-cluster -Name $cluster) -User $user -Password $pass -Force -Confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +} #End of function + +#start of function +Function ConfigHA +{ +<# +.SYNOPSIS + Configure HA on the cluster. +.DESCRIPTION + This will configure Ha on a specified cluster. It will + enable HA + disable admission control if the number of hosts is less than or equal to 3 + set the vm monitoring policy. +.NOTES + File Name : ConfigHA.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script + +$cluster = Read-Host "name of the cluster?" +$HARestartPriority = Read-Host " +choose one of the following as your VM (HA) Restart Priority +0. ClusterRestartPriority +1. Disabled +2. Low +3. Medium (Recommended) +4. High +" -ForegroundColor Blue -BackgroundColor White + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +get-cluster $cluster | Set-Cluster -HAEnabled:$true + +if ($HARestartPriority -eq 0 ) { get-cluster $cluster | set-cluster -HARestartPriority ClusterRestartPriority -Confirm:$false } +if ($HARestartPriority -eq 1 ) { get-cluster $cluster | set-cluster -HARestartPriority Disabled -Confirm:$false } +if ($HARestartPriority -eq 2 ) { get-cluster $cluster | set-cluster -HARestartPriority Low -Confirm:$false } +if ($HARestartPriority -eq 3 ) { get-cluster $cluster | set-cluster -HARestartPriority Medium -Confirm:$false } +if ($HARestartPriority -eq 4 ) { get-cluster $cluster | set-cluster -HARestartPriority High -Confirm:$false } + +if ((Get-Cluster $cluster | Get-VMHost).count -lt 4) { Get-Cluster $cluster | Set-Cluster -HAAdmissionControlEnabled:$false } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + +#start of function +Function CreateCluster +{ +<# +.SYNOPSIS + Create CreateCluster DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS CreateCluster rules between VMs where VMs will be made to stay on the same host by the DRS. +.NOTES + File Name : CreateCluster.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + $cluster = Read-Host "Name of the Cluster?" + if ((Get-datacenter).count -gt 1) { + $dc = Read-Host "name of the datacenter?" + get-datacenter -Name $dc | New-Cluster -Name $cluster -Confirm:$false + } + + if ((Get-datacenter).count -eq 1) { + get-datacenter | New-Cluster -Name $cluster -Confirm:$false + } + + if ((Get-datacenter).count -eq 0) { + Write-Host "Please create a datacenter first" -ForegroundColor DarkYellow -BackgroundColor White + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +} #End of function + +#start of function +Function CreateVapp +{ +<# +.SYNOPSIS + Create new vApp. +.DESCRIPTION + This will create vApp in a cluster. It is very easy and less time consuming to do manually but + the motto here is 'manual is an evil when you are automating' and most importantly in future this might have more options where + you can add VMs and control the startup/shutdown order of VMs. +.NOTES + File Name : CreateVapp.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "name of the cluster?" +$vapp = Read-Host "Name of the vApp?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +New-VApp -Name $vapp -Location (get-cluster $cluster) -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + + +#start of function +Function AddDatastores +{ +<# +.SYNOPSIS + Add datastores to a cluster. +.DESCRIPTION + This will create a csv file whcih is opened in excel. Once you popuate the details, you have to save & close it. + Hit return/enter to proceed and the script will + add the datastores to the 1st host of the cluster + rescan all the hosts of the cluster +.NOTES + File Name : AddDatastores.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script + +New-VIProperty -Name "Runtime" -ObjectType "ScsiLun" -Value { + param($scsilun) + #http://www.lucd.info/2010/10/17/runtime-name-via-extensiondata-and-new-viproperty/ + #twitter/lucd22 + #many a times (for some storages) runtime is empty, thus using this scriptlet to populate/repopulate the same + $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 + + +Write-Host " +A CSV file will be opened (open in excel/spreadsheet) +populate the values, +save & close the file, +Hit Enter to proceed +" -ForegroundColor Blue -BackgroundColor White +$csv = "$PSScriptRoot/AddLuns.csv" +get-process | Select-Object Cluster,LunID,DatastoreName,vmhba | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation +Start-Process $csv +Read-Host "Hit Enter/Return to proceed" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$csv = Import-Csv $csv + foreach ($line in $csv) #using trim() to make sure unnecessary spaces before or after any values in the csv files are removed + { + $cluster = $($line.Cluster) + $cluster = $cluster.trim() + + $lunid = $($line.LunID) + $lunid = $lunid.trim() + + $ds = $($line.DatastoreName) + $ds = $ds.trim() + + $vmhba = $($line.vmhba) + $runtime = ":C0:T0:L$lunid" + $runtime = $vmhba+$runtime + $vmhost = (get-cluster $cluster | get-vmhost)[0] + $naa = (Get-SCSILun -VMhost $vmhost -LunType Disk | where Runtime -eq $runtime).CanonicalName + New-Datastore -VMHost $vmhost -Name $ds -Path $naa -vmfs -Confirm:$false + } + + $cluster = $csv.Cluster | get-unique + get-cluster $cluster | get-vmhost | Get-VMHostStorage -RescanAllHba + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + +#start of function +Function ConfigDrs +{ +<# +.SYNOPSIS + Configure DRS on the cluster. +.DESCRIPTION + This will configure DRS on a specified cluster. +.NOTES + File Name : ConfigDrs.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script + +$cluster = Read-Host "name of the cluster?" +Write-Host " +choose the DRS Mode +1. FullyAutomated +2. Manual +3. PartiallyAutomated +" -ForegroundColor Blue -BackgroundColor White +$DrsLevel = Read-Host "type 1 or 2 or 3" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +if ($DrsLevel -eq 1) { $DrsLevel = "FullyAutomated" } +if ($DrsLevel -eq 2) { $DrsLevel = "Manual" } +if ($DrsLevel -eq 3) { $DrsLevel = "PartiallyAutomated" } + +Get-Cluster $cluster | Set-Cluster -DrsEnabled:$true -DrsAutomationLevel $DrsLevel -confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + + +#start of function +Function VMAffinity +{ +<# +.SYNOPSIS + Create VMAffinity DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS VMAffinity rules between VMs where VMs will be made to stay on the same host by the DRS. +.NOTES + File Name : VMAffinity.ps1 + Author : gajendra d ambi + Date : February 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "Name of the Cluster?" +$drsrule = Read-Host "Type the Name of the DRS Rule" +$vms = Read-Host "Name of the VMs (separated by comma, no space)?" +$vms = $vms.split(',') + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +New-DrsRule –Name $drsrule -Cluster $cluster –KeepTogether $true –VM $vms + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + +Function New-DrsVmGroup { +<# +.SYNOPSIS + Creates a new DRS VM group +.DESCRIPTION + This function creates a new DRS VM group in the DRS Group Manager +.NOTES + Author: Arnim van Lieshout +.PARAMETER VM + The VMs to add to the group. Supports objects from the pipeline. +.PARAMETER Cluster + The cluster to create the new group on. +.PARAMETER Name + The name for the new group. +.EXAMPLE + PS> Get-VM VM001,VM002 | New-DrsVmGroup -Name "VmGroup01" -Cluster CL01 +.EXAMPLE + PS> New-DrsVmGroup -VM VM001,VM002 -Name "VmGroup01" -Cluster (Get-CLuster CL01) +#> + + Param( + #http://www.van-lieshout.com/2011/06/drs-rules/ + #Arnim van Lieshout + [parameter(valuefrompipeline = $true, mandatory = $true, + HelpMessage = "Enter a vm entity")] + [PSObject]$VM, + [parameter(mandatory = $true, + HelpMessage = "Enter a cluster entity")] + [PSObject]$Cluster, + [parameter(mandatory = $true, + HelpMessage = "Enter a name for the group")] + [String]$Name) + + begin { + switch ($Cluster.gettype().name) { + "String" {$cluster = Get-Cluster $cluster | Get-View} + "ClusterImpl" {$cluster = $cluster | Get-View} + "Cluster" {} + default {throw "No valid type for parameter -Cluster specified"} + } + $spec = New-Object VMware.Vim.ClusterConfigSpecEx + $group = New-Object VMware.Vim.ClusterGroupSpec + $group.operation = "add" + $group.Info = New-Object VMware.Vim.ClusterVmGroup + $group.Info.Name = $Name + } + + Process { + switch ($VM.gettype().name) { + "String" {Get-VM -Name $VM | %{$group.Info.VM += $_.Extensiondata.MoRef}} + "VirtualMachineImpl" {$group.Info.VM += $VM.Extensiondata.MoRef} + "VirtualMachine" {$group.Info.VM += $VM.MoRef} + default {throw "No valid type for parameter -VM specified"} + } + } + + End { + if ($group.Info.VM) { + $spec.GroupSpec += $group + $cluster.ReconfigureComputeResource_Task($spec,$true) + } + else { + throw "No valid VMs specified" + } + } + +} + +#start of function +Function DrsHostGroup +{ +<# +.SYNOPSIS + Create DrsHostGroup DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS DrsHostGroup rules between VMs where VMs will be made to stay on the same host by the DRS. +.NOTES + File Name : DrsHostGroup.ps1 + Author : gajendra d ambi + Date : February 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "Name of the Cluster?" +$vmhosts = Read-Host "Type the Name of the host/hosts (separated only by a comma and no spaces)" +$vmhosts = $vmhosts.split(',') +$hostgroup = Read-Host "Type the Name of the Hostgroup" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost $vmhosts | New-DrsHostGroup -Name $hostgroup + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + +#start of function +Function DrsHostGroup +{ +<# +.SYNOPSIS + Create DrsHostGroup DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS DrsHostGroup rules between VMs where VMs will be made to stay on the same host by the DRS. +.NOTES + File Name : DrsHostGroup.ps1 + Author : gajendra d ambi + Date : February 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "Name of the Cluster?" +$vmhosts = Read-Host "Type the Name of the host/hosts (separated only by a comma and no spaces)" +$vmhosts = $vmhosts.split(',') +$hostgroup = Read-Host "Type the Name of the Hostgroup" +Get-Cluster $cluster | Get-VMHost $vmhosts | New-DrsHostGroup -Name $hostgroup + +#End of Script +}#End of function + +#start of function +Function DRSVMToHostRule +{ +<# +.SYNOPSIS + Create DRSVMToHostRule DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS DRSVMToHostRule rules between VMs where VMs will be made to stay on the same host by the DRS. +.NOTES + File Name : DRSVMToHostRule.ps1 + Author : gajendra d ambi + Date : February 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "Name of the Cluster?" +$drsrule = Read-Host "Type the Name of the DRS Rule" +$vmgroup = Read-Host "Type the Name of the VM group" +$hostgroup = Read-Host "Type the Name of the Hostgroup" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +New-DrsVMToHostRule -VMGroup $vmgroup -HostGroup $hostgroup -Name $drsrule -Cluster $cluster -AntiAffine -Mandatory + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +Function VMAntiAffinity +{ +<# +.SYNOPSIS + Create VMAntiAffinity DRS Rule. +.DESCRIPTION + This uses custom functions to create DRS VMAntiAffinity rules between VMs where VMs will be made to stay on different hosts by the DRS. +.NOTES + File Name : VMAntiAffinity.ps1 + Author : gajendra d ambi + Date : February 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +$cluster = Read-Host "Name of the Cluster?" +$drsrule = Read-Host "Type the Name of the DRS Rule" +$vms = Read-Host "Name of the VMs (separated by comma, no space)?" +$vms = $vms.split(',') + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +New-DrsRule –Name $drsrule -Cluster $cluster –KeepTogether $false –VM $vms + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script +}#End of function + +Function New-DRSVMToHostRule { +<# +.SYNOPSIS + Creates a new DRS VM to host rule +.DESCRIPTION + This function creates a new DRS vm to host rule +.NOTES + Author: Arnim van Lieshout +.PARAMETER VMGroup + The VMGroup name to include in the rule. +.PARAMETER HostGroup + The VMHostGroup name to include in the rule. +.PARAMETER Cluster + The cluster to create the new rule on. +.PARAMETER Name + The name for the new rule. +.PARAMETER AntiAffine + Switch to make the rule an AntiAffine rule. Default rule type is Affine. +.PARAMETER Mandatory + Switch to make the rule mandatory (Must run rule). Default rule is not mandatory (Should run rule) +.EXAMPLE + PS> New-DrsVMToHostRule -VMGroup "VMGroup01" -HostGroup "HostGroup01" -Name "VMToHostRule01" -Cluster CL01 -AntiAffine -Mandatory +#> + + Param( + #http://www.van-lieshout.com/2011/06/drs-rules/ + #Arnim van Lieshout + [parameter(mandatory = $true, + HelpMessage = "Enter a VM DRS group name")] + [String]$VMGroup, + [parameter(mandatory = $true, + HelpMessage = "Enter a host DRS group name")] + [String]$HostGroup, + [parameter(mandatory = $true, + HelpMessage = "Enter a cluster entity")] + [PSObject]$Cluster, + [parameter(mandatory = $true, + HelpMessage = "Enter a name for the group")] + [String]$Name, + [Switch]$AntiAffine, + [Switch]$Mandatory) + + switch ($Cluster.gettype().name) { + "String" {$cluster = Get-Cluster $cluster | Get-View} + "ClusterImpl" {$cluster = $cluster | Get-View} + "Cluster" {} + default {throw "No valid type for parameter -Cluster specified"} + } + + $spec = New-Object VMware.Vim.ClusterConfigSpecEx + $rule = New-Object VMware.Vim.ClusterRuleSpec + $rule.operation = "add" + $rule.info = New-Object VMware.Vim.ClusterVmHostRuleInfo + $rule.info.enabled = $true + $rule.info.name = $Name + $rule.info.mandatory = $Mandatory + $rule.info.vmGroupName = $VMGroup + if ($AntiAffine) { + $rule.info.antiAffineHostGroupName = $HostGroup + } + else { + $rule.info.affineHostGroupName = $HostGroup + } + $spec.RulesSpec += $rule + $cluster.ReconfigureComputeResource_Task($spec,$true) + +} + +Function New-DrsHostGroup +{ +<# +.SYNOPSIS + Creates a new DRS host group +.DESCRIPTION + This function creates a new DRS host group in the DRS Group Manager +.NOTES + Author: Arnim van Lieshout +.PARAMETER VMHost + The hosts to add to the group. Supports objects from the pipeline. +.PARAMETER Cluster + The cluster to create the new group on. +.PARAMETER Name + The name for the new group. +.EXAMPLE + PS> Get-VMHost ESX001,ESX002 | New-DrsHostGroup -Name "HostGroup01" -Cluster CL01 +.EXAMPLE + PS> New-DrsHostGroup -Host ESX001,ESX002 -Name "HostGroup01" -Cluster (Get-CLuster CL01) +#> + + Param( + #http://www.van-lieshout.com/2011/06/drs-rules/ + #Arnim van Lieshout + [parameter(valuefrompipeline = $true, mandatory = $true, + HelpMessage = "Enter a host entity")] + [PSObject]$VMHost, + [parameter(mandatory = $true, + HelpMessage = "Enter a cluster entity")] + [PSObject]$Cluster, + [parameter(mandatory = $true, + HelpMessage = "Enter a name for the group")] + [String]$Name) + + begin { + switch ($Cluster.gettype().name) { + "String" {$cluster = Get-Cluster $cluster | Get-View} + "ClusterImpl" {$cluster = $cluster | Get-View} + "Cluster" {} + default {throw "No valid type for parameter -Cluster specified"} + } + $spec = New-Object VMware.Vim.ClusterConfigSpecEx + $group = New-Object VMware.Vim.ClusterGroupSpec + $group.operation = "add" + $group.Info = New-Object VMware.Vim.ClusterHostGroup + $group.Info.Name = $Name + } + + Process { + switch ($VMHost.gettype().name) { + "String" {Get-VMHost -Name $VMHost | %{$group.Info.Host += $_.Extensiondata.MoRef}} + "VMHostImpl" {$group.Info.Host += $VMHost.Extensiondata.MoRef} + "HostSystem" {$group.Info.Host += $VMHost.MoRef} + default {throw "No valid type for parameter -VMHost specified"} + } + } + + End { + if ($group.Info.Host) { + $spec.GroupSpec += $group + $cluster.ReconfigureComputeResource_Task($spec,$true) + } + else { + throw "No valid hosts specified" + } + } + +} + +#start of function +function SetDNS +{ +<# +.SYNOPSIS + Update DNS +.DESCRIPTION + This will update the DNS, domain and searchdomain for the esxi hosts. +.NOTES + File Name : SetDNS.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "This new values will replace the existing values, hence add all the values" -ForegroundColor Yellow +$dnsadd = Read-Host "DNS Addresses(separate multiple entries with a comma)?" +$dnsadd = $dnsadd.split(',') +$domain = Read-Host "domain name?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +get-cluster $cluster | get-vmhost | Get-VMHostNetwork | Set-VMHostNetwork -DnsAddress $dnsadd -DomainName $domain -SearchDomain $domain -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#Start of function +function CoreDump +{ +<# +.SYNOPSIS + configure Coredump on esxi hosts +.DESCRIPTION + This will check the version of the esxi and based on the version of it, it will set the coredump settings on the host +.NOTES + File Name : CoreDump.ps1 + Author : gajendra d ambi + Date : January 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#start of the script +#start of the function + +$DumpTarget = Read-Host "Type the DumpTarget?:" +$vmk = Read-Host "Type the vmk number?:" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + foreach ($vmhost in (get-vmhost | sort)) { + if ((get-vmhost $vmhost).version -match 5.) { + $esxcli = get-vmhost $VMHost | Get-EsxCli + $esxcli.system.coredump.network.set($null, $vmk , $DumpTarget , "6500") + $esxcli.system.coredump.network.set("true") + $esxcli.system.coredump.network.get() + } + + if ((get-vmhost $vmhost).version -match 6.) { + $esxcli = get-vmhost $vmhost | get-esxcli + $esxcli.system.coredump.network.set($null , $vmk , $null , $DumpTarget , "6500") + $esxcli.system.coredump.network.set("true") + $esxcli.system.coredump.network.get() + } + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function EsxiAdvanced +{ +<# +.SYNOPSIS + Set value to a chosen advancedsettig +.DESCRIPTION + This will ask set many of the esxi advancedsettings which are exposed in esxi>configuration>advancedsettings. + It will require 2 inputs from the user. + name of the advanced setting and value of the advancedsetting. +.NOTES + File Name : EsxiAdvanced.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$AdvSet = Read-Host "name of the advancedsetting[case sensitive]?" +$value = Read-Host "value for the advancedsetting?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + foreach ($vmhost in (Get-Cluster $cluster)) + { + Get-VMHost $vmhost | get-advancedsetting -Name $AdvSet | Set-AdvancedSetting -Value $value -Confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetIpv6 +{ +<# +.SYNOPSIS + Update Ipv6 +.DESCRIPTION + This will disable/enable Ipv6 on esxi hosts of a chosen cluster. +.NOTES + File Name : SetIpv6.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host " +1. Disable IPv6 +2. Enable IPv6 +" -ForegroundColor Blue -BackgroundColor White +$choice = Read-Host "type between 1 & 2" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +If ($choice -eq 1) { get-cluster $cluster | get-vmhost | Get-VMHostNetwork | Set-VMHostNetwork -IPv6Enabled $false } +If ($choice -eq 2) { get-cluster $cluster | get-vmhost | Get-VMHostNetwork | Set-VMHostNetwork -IPv6Enabled $true } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +function SetNTP +{ +<# +.SYNOPSIS + Update NTP +.DESCRIPTION + This will update the NTP servers to the esxi hosts. It will add one NTP server at a time. + It will not replace or overwrite any existing NTP servers. This will set the ntpd service to on. +.NOTES + File Name : SetNTP.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "This new values will replace the existing values, hence add all the values" -ForegroundColor Yellow +$ntp = Read-Host "NTP address(separate them with comma,no space..)" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$ntp = $ntp.split(',') + + foreach ($vmhost in (Get-Cluster $cluster | get-vmhost | sort)) + { + Write-Host "adding ntp server to $vmhost" -ForegroundColor Green + Add-VMHostNTPServer -NtpServer $ntp -VMHost (Get-VMHost $vmhost) -Confirm:$false + Write-Host "setting ntp policy to on on $vmhost" -ForegroundColor Green + Get-VMHostService -VMHost (Get-VMHost $vmhost) | where Key -eq "ntpd" | Restart-VMHostService -Confirm:$false + Get-VMHostService -VMHost (Get-VMHost $vmhost) | where Key -eq "ntpd" | Set-VMHostService -policy "on" -Confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetFirewall +{ +<# +.SYNOPSIS + firewall settings for esxi hosts +.DESCRIPTION + Configure firewall per host in a cluster. These is a sample firewall setting here. You can populate the rest as per your business + standards. Run + get-vmhost | Get-VmhostFirewallException + to list the available firewall settings that you can turn on or off. +.NOTES + File Name : SetFirewall.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" + + foreach ($vmhost in (Get-Cluster $cluster)) + { + Get-VMHost $vmhost | Get-VmhostFirewallException -Name "NTP Client" | Set-VMHostFirewallException -enabled:$true -Confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetEsxiPerf +{ +<# +.SYNOPSIS + Configure powersaving policy or performance policy on esxi. +.DESCRIPTION + This will configure 1 of the 3 levels of energy saving or performance setting on your esxi hosts. + 3 valid options are HighPerformance, Balanced, LowPower. +.NOTES + File Name : SetEsxiPerf.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# + +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host " +1. HighPerformance +2. Balanced +3. LowPower +" -ForegroundColor Blue -BackgroundColor White +$perf = Read-Host "one of the following is a valid choice. Type 1,2 or 3" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +if ($perf -eq 1) {$perf = "HighPerformance"} +if ($perf -eq 2) {$perf = "Balanced" } +if ($perf -eq 3) {$perf = "LowPower" } + +(Get-View (Get-Cluster $cluster | Get-VMHost | Get-View).ConfigManager.PowerSystem).ConfigurePowerPolicy($perf) + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetScratch +{ +<# +.SYNOPSIS + Create & configure Scratch partition on Esxi hosts +.DESCRIPTION + This will create scratch location on the local storage of the esxi hosts and then map that as the + scratch location for that host. Please note that if the local storage of your esxi blades is of different + format that '*-localstorage' then please change the line + $ds = Get-VMHost -name $vmhost | get-datastore -Name '*-localstorage' + accordingly. +.NOTES + File Name : SetScratch.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$resetloc = get-location +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host " +Leave blank if there is just one datastore, +to create scratch on a datastore with it's name matching 'localstorage' type localstorage, +" -BackgroundColor White -ForegroundColor Black +$pattern = Read-Host "?" +$pattern = "*"+$pattern+"*" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) { + $vmhost = (get-vmhost $vmhost).Name + $scratchfolder = '.locker_'+($vmhost.Split('.')[0]) + $ds = Get-VMHost -name $vmhost | get-datastore -Name $pattern + $location = ($vmhost.Split('.')[0]) + New-PSDrive -Name $location -Root \ -PSProvider VimDatastore -Datastore ($ds) -Scope global + Set-Location $location":" + ni $scratchfolder -ItemType directory -ErrorAction SilentlyContinue + Get-VMhost $vmhost | Get-AdvancedSetting -Name "ScratchConfig.ConfiguredScratchLocation" | Set-AdvancedSetting -Value "/vmfs/volumes/$ds/$scratchfolder" -confirm:$false + Set-Location $resetloc + Remove-PSDrive $location + } + get-cluster $cluster | get-vmhost | sort | Get-AdvancedSetting -Name "ScratchConfig.ConfiguredScratchLocation" | select Entity, Value | fl + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetSnmp +{ +<# +.SYNOPSIS + Configure SNMP +.DESCRIPTION + This will configure SNMP using powercli on esxi hosts. It uses esxcli commands into powercli. +.NOTES + File Name : SetSnmp.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$snmp = Read-Host "Type the snmp target" +$string = Read-Host "Type the snmp communities string" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) { + $esxcli = get-vmhost $vmhost | get-esxcli + $esxcli.system.snmp.set($null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,"true",$null,$null,$null,$null) + $esxcli.system.snmp.set($null,$string,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null) + $esxcli.system.snmp.set($null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,"$snmp/$string","$snmp/$string",$null) + $esxcli.system.snmp.set($null,$null,"true",$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$null) + $esxcli.system.snmp.get() + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetSyslog +{ +<# +.SYNOPSIS + Configure Syslog +.DESCRIPTION + This will configure Syslog using powercli. This only set the syslog servers and enable syslog on the esxi hosts. + You may however include additional advanced syslog configuarations like Syslog.global.defaultSize and others. + This will also create a firewall exception for the syslog. +.NOTES + File Name : SetSyslog.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$syslog = Read-Host "Syslog Target?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) { +get-vmhost $vmhost | Get-AdvancedSetting -Name Syslog.global.logHost | Set-AdvancedSetting -Value $Syslog -Confirm:$false +get-vmhost $vmhost | Get-VMHostFirewallException -Name "syslog" | Set-VMHostFirewallException -enabled:$true -Confirm:$false + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function PowerMgmt +{ +<# +.SYNOPSIS + Perform power actions on esxi +.DESCRIPTION + When we poweroff, shutdown, reboot a host we need to provide a reason to do so. This is especially + boring and time consuming if you have a lot of hosts on which you have to do this. This is to ease + that pain. It has 4 options to choose from + A. Enter Maintenance Mode + B. Exit Maintenance Mode + C. Shutdown + D. Reboot + It will ask the reason to perform that action and it will input that reason before it performs the + chosen action. +.NOTES + File Name : PowerMgmt.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host " +1.Enter Maintenance Mode +2.Exit Maintenance Mode +3.Shutdown (the hosts which are in maintenance mode) +4.Reboot (the hosts which are in maintenance mode) +" -ForegroundColor Blue -BackgroundColor White +$axn = Read-Host "Type a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$vmhosts = Get-cluster $cluster | get-vmhost +if ($axn -eq 1) {$vmhosts | set-vmhost -State Maintenance} +if ($axn -eq 2) {$vmhosts | set-vmhost -State Connected} +$vmhosts = get-cluster $cluster | get-vmhost -State Maintenance +if ($axn -eq 3) + {Write-Host "enter a reason for this action" -ForegroundColor Yellow + $reason = Read-Host "" + foreach ($vmhost in $vmhosts) { + $esxcli = get-esxcli + $esxcli.system.shutdown.poweroff($null,$reason) + } + } +if ($axn -eq 4) + {Write-Host "enter a reason for this action" -ForegroundColor Yellow + $reason = Read-Host "" + foreach ($vmhost in $vmhosts) { + $esxcli = get-esxcli + $esxcli.system.shutdown.poweroff($null,$reason) + } + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setpcscd +{ +<# +.SYNOPSIS + Configure pcscd [PC/SC Smart Card Daemon] +.DESCRIPTION + Depending upon the choice that you make + This will enable pcscd. + This will disable pcscd. + This will set pcscd policy to On which will be persistent across reboot. + This will set pcscd policy to Off which will be persistent across reboot. +.NOTES + File Name : Setpcscd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "pcscd [PC/SC Smart Card Daemon] options + 1. Enable pcscd + 2. Disable pcscd + 3. pcscd Policy On + 4. pcscd Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ pcscd | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ pcscd | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ pcscd | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ pcscd | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setsfcbd +{ +<# +.SYNOPSIS + Configure sfcbd-watchdog [CIM Server] +.DESCRIPTION + Depending upon the choice that you make + This will enable sfcbd. + This will disable sfcbd. + This will set sfcbd policy to On which will be persistent across reboot. + This will set sfcbd policy to Off which will be persistent across reboot. +.NOTES + File Name : Setsfcbd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "sfcbd-watchdog [CIM Server] options + 1. Enable sfcbd + 2. Disable sfcbd + 3. sfcbd Policy On + 4. sfcbd Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ sfcbd | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ sfcbd | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ sfcbd | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ sfcbd | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetTSM +{ +<# +.SYNOPSIS + Configure TSM [ESXi Shell] +.DESCRIPTION + Depending upon the choice that you make + This will enable TSM. + This will disable TSM. + This will set TSM policy to On which will be persistent across reboot. + This will set TSM policy to Off which will be persistent across reboot. +.NOTES + File Name : SetTSM.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "TSM [ESXi Shell] options + 1. Enable TSM + 2. Disable TSM + 3. TSM Policy On + 4. TSM Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setvpxa +{ +<# +.SYNOPSIS + Configure vpxa [VMware vCenter Agent] +.DESCRIPTION + Depending upon the choice that you make + This will enable vpxa. + This will disable vpxa. + This will set vpxa policy to On which will be persistent across reboot. + This will set vpxa policy to Off which will be persistent across reboot. +.NOTES + File Name : Setvpxa.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "vpxa [VMware vCenter Agent] options + 1. Enable vpxa + 2. Disable vpxa + 3. vpxa Policy On + 4. vpxa Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vpxa | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vpxa | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vpxa | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vpxa | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setvprobed +{ +<# +.SYNOPSIS + Configure vprobed [VProbe Daemon] +.DESCRIPTION + Depending upon the choice that you make + This will enable vprobed. + This will disable vprobed. + This will set vprobed policy to On which will be persistent across reboot. + This will set vprobed policy to Off which will be persistent across reboot. +.NOTES + File Name : Setvprobed.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "vprobed [VProbe Daemon] options + 1. Enable vprobed + 2. Disable vprobed + 3. vprobed Policy On + 4. vprobed Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vprobed | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vprobed | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vprobed | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vprobed | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setntpd +{ +<# +.SYNOPSIS + Configure ntpd [NTP Daemon] +.DESCRIPTION + Depending upon the choice that you make + This will enable ntpd. + This will disable ntpd. + This will set ntpd policy to On which will be persistent across reboot. + This will set ntpd policy to Off which will be persistent across reboot. +.NOTES + File Name : Setntpd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "ntpd [NTP Daemon] options + 1. Enable ntpd + 2. Disable ntpd + 3. ntpd Policy On + 4. ntpd Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ ntpd | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ ntpd | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ ntpd | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ ntpd | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setvmsyslogd +{ +<# +.SYNOPSIS + Configure vmsyslogd [Syslog Server] +.DESCRIPTION + Depending upon the choice that you make + This will enable vmsyslogd. + This will disable vmsyslogd. + This will set vmsyslogd policy to On which will be persistent across reboot. + This will set vmsyslogd policy to Off which will be persistent across reboot. +.NOTES + File Name : Setvmsyslogd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "vmsyslogd [Syslog Server] options + 1. Enable vmsyslogd + 2. Disable vmsyslogd + 3. vmsyslogd Policy On + 4. vmsyslogd Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vmsyslogd | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vmsyslogd | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vmsyslogd | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ vmsyslogd | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setlwsmd +{ +<# +.SYNOPSIS + Configure lwsmd [Active Directory Service] +.DESCRIPTION + Depending upon the choice that you make + This will enable lwsmd. + This will disable lwsmd. + This will set lwsmd policy to On which will be persistent across reboot. + This will set lwsmd policy to Off which will be persistent across reboot. +.NOTES + File Name : Setlwsmd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "lwsmd [Active Directory Service] options + 1. Enable lwsmd + 2. Disable lwsmd + 3. lwsmd Policy On + 4. lwsmd Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lwsmd | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lwsmd | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lwsmd | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lwsmd | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetSSH +{ +<# +.SYNOPSIS + Configure TSM-SSH [SSH] +.DESCRIPTION + Depending upon the choice that you make + This will enable TSM-SSH. + This will disable TSM-SSH. + This will set TSM-SSH policy to On which will be persistent across reboot. + This will set TSM-SSH policy to Off which will be persistent across reboot. +.NOTES + File Name : SetSSH.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "TSM-SSH [SSH] options + 1. Enable TSM-SSH + 2. Disable TSM-SSH + 3. TSM-SSH Policy On + 4. TSM-SSH Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM-SSH | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM-SSH | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM-SSH | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ TSM-SSH | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setxorg +{ +<# +.SYNOPSIS + Configure xorg [X.Org Server] +.DESCRIPTION + Depending upon the choice that you make + This will enable xorg. + This will disable xorg. + This will set xorg policy to On which will be persistent across reboot. + This will set xorg policy to Off which will be persistent across reboot. +.NOTES + File Name : Setxorg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "xorg [X.Org Server] options + 1. Enable xorg + 2. Disable xorg + 3. xorg Policy On + 4. xorg Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ xorg | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ xorg | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ xorg | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ xorg | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setsnmpd +{ +<# +.SYNOPSIS + Configure snmpd [SNMP Server] +.DESCRIPTION + Depending upon the choice that you make + This will enable snmpd. + This will disable snmpd. + This will set snmpd policy to On which will be persistent across reboot. + This will set snmpd policy to Off which will be persistent across reboot. +.NOTES + File Name : Setsnmpd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "snmpd [SNMP Server] options + 1. Enable snmpd + 2. Disable snmpd + 3. snmpd Policy On + 4. snmpd Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ snmpd | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ snmpd | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ snmpd | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ snmpd | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function SetDCUI +{ +<# +.SYNOPSIS + Configure DCUI [Direct Console UI] +.DESCRIPTION + Depending upon the choice that you make + This will enable DCUI. + This will disable DCUI. + This will set DCUI policy to On which will be persistent across reboot. + This will set DCUI policy to Off which will be persistent across reboot. +.NOTES + File Name : SetDCUI.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "DCUI [Direct Console UI] options + 1. Enable DCUI + 2. Disable DCUI + 3. DCUI Policy On + 4. DCUI Policy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ DCUI | Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ DCUI | stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ DCUI | Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ DCUI | Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function Setlbtd +{ +<# +.SYNOPSIS + Configure lbtd[Load-Based Teaming Daemon] +.DESCRIPTION + Depending upon the choice that you make + This will enable lbtd. + This will disable lbtd. + This will set lbtdpolicy to On which will be persistent across reboot. + This will set lbtdpolicy to Off which will be persistent across reboot. +.NOTES + File Name : SetLbtd.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of script# +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +Write-Host "lbtd[Load-Based Teaming Daemon] options + 1. Enable lbtd + 2. Disable lbtd + 3. lbtdPolicy On + 4. lbtdPolicy Off + " -BackgroundColor White -ForegroundColor Blue #options to choose from + $a = Read-Host "Choose a number from 1 to 4" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + + if ($a -eq 1) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lbtd| Start-VMHostService -Confirm:$false} + if ($a -eq 2) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lbtd| stop-VMHostService -Confirm:$false} + if ($a -eq 3) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lbtd| Set-VMHostService -Policy On -Confirm:$false} + if ($a -eq 4) {get-cluster $cluster | get-vmhost | get-vmhostservice | where Key -EQ lbtd| Set-VMHostService -Policy Off -Confirm:$false} + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function VMotionOff +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : VMotionOff.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -VMotionEnabled $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function VmotionOn +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : VmotionOn.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -VMotionEnabled $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function FaultToleranceOn +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : FaultToleranceOn.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -FaultToleranceLoggingEnabled $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function VsanTrafficOn +{ +<# +.SYNOPSIS + Enable VsanTrafficOn +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : VsanTrafficOn.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -VsanTrafficEnabled $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function ManagementTrafficOn +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : ManagementTrafficOn.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -ManagementTrafficEnabled $false -Confirm:$false +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function ManagementTrafficOff +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : ManagementTrafficOff.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -ManagementTrafficEnabled $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function ManagementTrafficOff +{ +<# +.SYNOPSIS + Enable vMotion +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : ManagementTrafficOff.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -ManagementTrafficEnabled $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +function VsanTrafficOff +{ +<# +.SYNOPSIS + Enable VsanTrafficOff +.DESCRIPTION + Enable vMotion across the Cluster +.NOTES + File Name : VsanTrafficOff.ps1 + Author : gajendra d ambi + Date : Feb 2016 + recommended : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#start of script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VMHostNetworkAdapter | where PortGroupname -EQ $pg | Set-VMHostNetworkAdapter -VsanTrafficEnabled $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +Function HostVds +{ +<# +.SYNOPSIS + Add Esxi host to distributed switch. +.DESCRIPTION + This will create a csv file whcih is opened in excel. Once you popuate the details, you have to save & close it. + Hit return/enter to proceed and the script will + add the esxi hosts to a chosen dvswitch. +.NOTES + File Name : HostVds.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +Write-Host " +A CSV file will be opened (open in excel/spreadsheet) +populate the values, +save & close the file, +Hit Enter to proceed +" -ForegroundColor Blue -BackgroundColor White +$csv = "$PSScriptRoot/HostVds.csv" +get-process | Select-Object dvSwitch,hostname,vmnic | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation +Start-Process $csv +Read-Host "Hit Enter/Return to proceed" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$csv = Import-Csv $csv + foreach ($line in $csv) + { + $dvs = $($line.dvSwitch) + $vmhost = $($line.hostname) + $vmnic = $($line.vmnic) + Get-VDSwitch -Name $dvs | Add-VDSwitchVMHost -VMHost $vmhost + $vmhostNetworkAdapter = Get-VMHost $vmhost | Get-VMHostNetworkAdapter -Physical -Name $vmnic + Get-VDSwitch $dvs | Add-VDSwitchPhysicalNetworkAdapter -VMHostNetworkAdapter $vmhostNetworkAdapter + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function AddDpg +{ +<# +.SYNOPSIS + Add dvportgroups to a dvswitch. +.DESCRIPTION + This will create a csv file whcih is opened in excel. Once you popuate the details, you have to save & close it. + Hit return/enter to proceed and the script will + add the dvportgroups to a chosen dvswitch. +.NOTES + File Name : AddDpg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> + +#Start of Script +Write-Host " +A CSV file will be opened (open in excel/spreadsheet) +populate the values, +save & close the file, +Hit Enter to proceed +" -ForegroundColor Blue -BackgroundColor White + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$csv = "$PSScriptRoot/AddDpg.csv" +get-process | Select-Object dvSwitch,dvPortgroup,VlanId,NumberOfPorts | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation +Start-Process $csv +Read-Host "Hit Enter/Return to proceed" + +$csv = Import-Csv $csv + foreach ($line in $csv) + { + $dvs = $($line.dvSwitch) + $dpg = $($line.dvPortgroup) + $vlan = $($line.VlanId) + $ports = $($line.NumberOfPorts) + Get-VDSwitch -Name $dvs | New-VDPortgroup -Name $dpg -VlanId $vlan -NumPorts $ports + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function CreateVds +{ +<# +.SYNOPSIS + Create VDS. +.DESCRIPTION + This will create a vds on a chosen datacenter.. +.NOTES + File Name : CreateVds.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$dc = Read-Host "name of the datacenter?" +$ul = Read-Host "number of uplinks?" +$dvs = Read-Host "name of the dvSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +New-VDSwitch -Name $dvs -Location $dc -NumUplinkPorts $ul -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black +#End of Script# +}#End of function + +#start of function +Function Setef +{ +<# +.SYNOPSIS + Set ExplicitFailover on VDS. +.DESCRIPTION + This will set the loadbalancing on the vds as ExplicitFailover. +.NOTES + File Name : Setef.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$dvs = Read-Host "name of the dvSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VDSwitch -Name $dvs | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy ExplicitFailover -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Setlbsm +{ +<# +.SYNOPSIS + Set LoadBalanceSrcMac on VDS. +.DESCRIPTION + This will set the loadbalancing on the vds as LoadBalanceSrcMac. +.NOTES + File Name : Setlbsm.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$dvs = Read-Host "name of the dvSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VDSwitch -Name $dvs | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceSrcMac -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function SetLbip +{ +<# +.SYNOPSIS + Set LoadBalanceIP on VDS. +.DESCRIPTION + This will set the loadbalancing on the vds as LoadBalanceIP. +.NOTES + File Name : SetLbip.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$dvs = Read-Host "name of the dvSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VDSwitch -Name $dvs | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceIP -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Setlbsi +{ +<# +.SYNOPSIS + Set LoadBalanceSrcId on VDS. +.DESCRIPTION + This will set the loadbalancing on the vds as LoadBalanceSrcId. +.NOTES + File Name : Setlbsi.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$dvs = Read-Host "name of the dvSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VDSwitch -Name $dvs | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceSrcId -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Setllb +{ +<# +.SYNOPSIS + Set LoadBalanceLoadBased on VDS. +.DESCRIPTION + This will set the loadbalancing on the vds as LoadBalanceLoadBased. +.NOTES + File Name : Setllb.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$dvs = Read-Host "name of the dvSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-VDSwitch -Name $dvs | Get-VDUplinkTeamingPolicy | Set-VDUplinkTeamingPolicy -LoadBalancingPolicy LoadBalanceLoadBased -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +function ShootVmkPg +{ +<# +.SYNOPSIS + Remove vmkernel portgroup +.DESCRIPTION + This will remove the virtual machine portgroup of all the hosts of a cluster/clusters. +.NOTES + File Name : ShootVmkPg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) + { + $vmk = Get-VMHostNetworkAdapter -VMHost $vmhost | where PortgroupName -eq $pg + Write-Host "removing vmkernel from the $pg on $vmhost" + Remove-VMHostNetworkAdapter -Nic $vmk -confirm:$false + + Write-Host "removing $pg on $vmhost" + get-vmhost $vmhost | get-virtualportgroup -Name $pg | Remove-VirtualPortGroup -Confirm:$false + }#End of Script +}#End of function + +#start of function +Function ShootVmPg +{ +<# +.SYNOPSIS + Remove virtual machine portgroup +.DESCRIPTION + This will remove the virtual machine portgroup of all the hosts of a cluster/clusters. +.NOTES + File Name : ShootVmPg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $pg | Remove-VirtualPortGroup -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Pglbip +{ +<# +.SYNOPSIS + update virtual machine portgroup's loadbalancing to LoadBalanceIP on vSwitch. +.DESCRIPTION + This will update virtual machine portgroup's loadbalancing to LoadBalanceIP on a chosen standard portgroup of hosts of a chosen cluster. +.NOTES + File Name : Pglbip.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -LoadBalancingPolicy LoadBalanceIP -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function CreateVss +{ +<# +.SYNOPSIS + Create standard vSwitch. +.DESCRIPTION + This will create a standard vSwitch of hosts of a chosen cluster. +.NOTES + File Name : CreateVss.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "name of the vSphere standard Switch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | New-VirtualSwitch -Name $vss -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Pglbsi +{ +<# +.SYNOPSIS + update virtual machine portgroup's loadbalancing to LoadBalanceSrcId on vSwitch. +.DESCRIPTION + This will update virtual machine portgroup's loadbalancing to LoadBalanceSrcId on a chosen standard portgroup of hosts of a chosen cluster. +.NOTES + File Name : Pglbsi.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -LoadBalancingPolicy LoadBalanceSrcId -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Pglbsm +{ +<# +.SYNOPSIS + update virtual machine portgroup's loadbalancing to LoadBalanceSrcMac on vSwitch. +.DESCRIPTION + This will update virtual machine portgroup's loadbalancing to LoadBalanceSrcMac on a chosen standard portgroup of hosts of a chosen cluster. +.NOTES + File Name : Pglbsm.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -LoadBalancingPolicy LoadBalanceSrcMac -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function PgVlan +{ +<# +.SYNOPSIS + update virtual machine portgroup's Vlan on vSwitch. +.DESCRIPTION + This will update virtual machine portgroup's Vlan on a chosen portgroup of hosts of a chosen cluster. +.NOTES + File Name : PgVlan.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" +$vlan = Read-Host "New Vlan?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $pg | Set-VirtualPortGroup -VLanId $vlan -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function Pgef +{ +<# +.SYNOPSIS + update virtual machine portgroup's loadbalancing to ExplicitFailover on vSwitch. +.DESCRIPTION + This will update virtual machine portgroup's loadbalancing to ExplicitFailover on a chosen standard portgroup of hosts of a chosen cluster. +.NOTES + File Name : Pgef.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$pg = Read-Host "Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $pg | Get-NicTeamingPolicy | Set-NicTeamingPolicy -LoadBalancingPolicy ExplicitFailover -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function PgRename +{ +<# +.SYNOPSIS + update virtual machine portgroup's name on vSwitch. +.DESCRIPTION + This will update virtual machine portgroup's name on a chosen standard vSwitch of hosts of a chosen cluster. +.NOTES + File Name : PgRename.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$oldpg = Read-Host "Old Name of the portgroup?" +$newpg = Read-Host "New Name of the portgroup?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualPortGroup -Name $oldpg | Set-VirtualPortGroup -Name $newpg -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssPmOn +{ +<# +.SYNOPSIS + Allow promiscous mode +.DESCRIPTION + This will allow promiscous mode on a vswitch. +.NOTES + File Name : VssPmOn.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "Name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Get-SecurityPolicy | Set-SecurityPolicy -AllowPromiscuous $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssPmOff +{ +<# +.SYNOPSIS + Allow promiscous mode +.DESCRIPTION + This will allow promiscous mode on a vswitch. +.NOTES + File Name : VssPmOff.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "Name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Get-SecurityPolicy | Set-SecurityPolicy -AllowPromiscuous $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssVmkPg +{ +<# +.SYNOPSIS + update vmkernel portgroup on vSwitch. +.DESCRIPTION + This will update vmkernel portgroup on a chosen standard vSwitch of hosts of a chosen cluster. +.NOTES + File Name : VssVmkPg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "name of the vSphere standard Switch?" +$pg = Read-Host "Name of the portgroup?" +$vmk = Read-Host "vmk number? ex:- vmk9" +$ip = Read-Host "starting ip address?" +$mask = Read-Host "subnet mask" +$vlan = Read-Host "Vlan?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +$a = $ip.Split('.')[0..2] + + #first 3 octets of the ip address + $b = [string]::Join(".",$a) + + #last octet of the ip address + $c = $ip.Split('.')[3] + $c = [int]$c + + foreach ($vmhost in (get-cluster $cluster | get-vmhost | sort)) { + get-vmhost $vmhost | get-virtualswitch -Name $vss | New-VirtualPortGroup -Name $pg -VLanId $vlan -Confirm:$false + $esxcli = get-vmhost $vmhost | Get-EsxCli + $esxcli.network.ip.interface.add($null, $null, "$vmk", $null, "1500", $null, "$pg") + $esxcli.network.ip.interface.ipv4.set("$vmk", "$b.$(($c++))", "$mask", $null, "static") + } + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssPorts +{ +<# +.SYNOPSIS + update portgroups on vSwitch. +.DESCRIPTION + This will update portgroups on a chosen standard vSwitch of hosts of a chosen cluster. +.NOTES + File Name : VssPorts.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "name of the vSphere standard Switch?" +$ports = Read-Host "number of ports?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Set-VirtualSwitch -NumPorts $ports -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssFtOff +{ +<# +.SYNOPSIS + Allow promiscous mode +.DESCRIPTION + This will allow promiscous mode on a vswitch. +.NOTES + File Name : VssFtOff.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "Name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Get-SecurityPolicy | Set-SecurityPolicy -ForgedTransmits $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssVmPg +{ +<# +.SYNOPSIS + update virtual machine portgroup on vSwitch. +.DESCRIPTION + This will update virtual machie portgroup on a chosen standard vSwitch of hosts of a chosen cluster. +.NOTES + File Name : VssVmPg.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "name of the vSphere standard Switch?" +$pg = Read-Host "Name of the portgroup?" +$vlan = read-host "VLAN?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | New-VirtualPortGroup -Name $pg -VLanId $vlan -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssMcOff +{ +<# +.SYNOPSIS + Allow promiscous mode +.DESCRIPTION + This will allow promiscous mode on a vswitch. +.NOTES + File Name : VssMcOff.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "Name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Get-SecurityPolicy | Set-SecurityPolicy -MacChanges $false -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssMcOn +{ +<# +.SYNOPSIS + Allow promiscous mode +.DESCRIPTION + This will allow promiscous mode on a vswitch. +.NOTES + File Name : VssMcOn.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "Name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Get-SecurityPolicy | Set-SecurityPolicy -MacChanges $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssFtOn +{ +<# +.SYNOPSIS + Allow promiscous mode +.DESCRIPTION + This will allow promiscous mode on a vswitch. +.NOTES + File Name : VssFtOn.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "Name of the vSwitch?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-cluster $cluster | Get-VMHost | Get-VirtualSwitch -Name $vss | Get-SecurityPolicy | Set-SecurityPolicy -ForgedTransmits $true -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#start of function +Function VssMtu +{ +<# +.SYNOPSIS + update Mtu on vSwitch. +.DESCRIPTION + This will update Mtu on a chosen standard vSwitch of hosts of a chosen cluster. +.NOTES + File Name : VssMtu.ps1 + Author : gajendra d ambi + Date : March 2016 + Prerequisite : PowerShell v4+, powercli 6+ over win7 and upper. + Copyright - None +.LINK + Script posted over: github.com/gajuambi/vmware +#> +#Start of Script +$cluster = Read-Host "name of the cluster[type * to include all clusters]?" +$vss = Read-Host "name of the vSphere standard Switch?" +$mtu = Read-Host "mtu?" + +$stopWatch = [system.diagnostics.stopwatch]::startNew() +$stopWatch.Start() + +Get-Cluster $cluster | get-vmhost | Get-Virtualswitch -Name $vss | Set-VirtualSwitch -Mtu $mtu -Confirm:$false + +$stopWatch.Stop() +Write-Host "Elapsed Runtime:" $stopWatch.Elapsed.Hours "Hours" $stopWatch.Elapsed.Minutes "minutes and" $stopWatch.Elapsed.Seconds "seconds." -BackgroundColor White -ForegroundColor Black + #End of Script# +}#End of function + +#------------------------------End of Collection of Functions of automation------------------------# + +#------------------------------Start of Collection of Menu Functions-------------------------------# + +#Start of NicMenu +function NicMenu +{ + do { + do { + Write-Host "`NicMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. vSwitch + B. portgroup + " #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { NicStatusVss } + "B" { NicStatusPg } + + "X" { vCenterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} #end of NicMenu + +#Start of StandHostsMenu +function StandHostsMenu +{ + do { + do { + Write-Host "`StandHostsMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. Connect to standalone hosts + B. Create virtual Standard Switch + C. Create virtual Machine Portgroup + D. Create VMkernel Portgroup + E. Rename Portgroups + F. Add Nics to vSwitch + G. Remove VM portgroup + H. Remove VMkernel portgroup" #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdefghxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { shGetShHosts } + "B" { shNewVss } + "C" { shNewVMPg } + "D" { shNewVMkernelPg } + "E" { shRenamePg } + "F" { shAddNic } + "G" { shShootVmPg } + "H" { shShootVmkPg } + + "X" { vCenterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of StandHostsMenu + +#Start of vdsLoadBalancingMenu +function vdsLoadBalancingMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nvdsLoadBalancingMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. LoadBalanceIP + B. LoadBalanceLoadBased + C. LoadBalanceSrcMac + D. LoadBalanceSrcId + E. ExplicitFailover" #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdexyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { SetLbip } + "B" { Setllb } + "C" { Setlbsm } + "D" { Setlbsi } + "E" { Setef } + "X" { vdsMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of vdsLoadBalancingMenu + +#Start of VMKservicesMenu +function VMKservicesMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nVMKservicesMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. Enable VMotion + B. Enable VsanTraffic + C. Enable FaultTolerance + D. Enable ManagementTraffic + E. Disable VMotion + F. Disable VsanTraffic + G. Disable FaultTolerance + H. Disable ManagementTraffic" #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdefghxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { VmotionOn } + "B" { VsanTrafficOn } + "C" { FaultToleranceOn } + "D" { ManagementTrafficOn } + "E" { VMotionOff } + "F" { VsanTrafficOff } + "G" { FaultToleranceOff } + "H" { ManagementTrafficOff } + "X" { HostMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of VMKservicesMenu + +#Start of vdsMenu +function vdsMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nvdsMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. Create VDS + B. Create dvPortgroup + C. Add hosts to VDS + D. Load balancing + E. (L3)TCP/IP stack" #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdexyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { CreateVds } + "B" { AddDpg } + "C" { HostVds } + "D" { vdsLoadBalancingMenu } + "E" { Write-Host This feature is not available yet } + "X" { vCenterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of vdsMenu + +#Start of VssMenu +Function VssMenu +{ + do { + do { + Write-Host -BackgroundColor White -ForegroundColor Black "`nVssMenu" + Write-Host " + A. Create vSwitch + B. Update NumPorts + C. Update Nic + D Update MTU + E. Create VM Portgroup + F. Create VMkernel Portgroup + G. Rename Portgroup + H. Update Portgroup's Vlan + I. LoadBalanceIP + J. LoadBalanceSrcMac + K. LoadBalanceSrcId + L. ExplicitFailover + M. Delete VM Portgroup + N. Enable AllowPromiscuous + O. Enable ForgedTransmits + P. Enable MacChanges + Q. Disable AllowPromiscuous + R. Disable ForgedTransmits + S. Disable MacChanges + T. Delete VMkernel Portgroup + U. Sync portgroup with vSwitch(inherit all properties of vswitch to portgroup) + V. L3 vMotion Portgroup + " #options to choose from... + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit + " -BackgroundColor White -ForegroundColor Black + + $user = [Environment]::UserName + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdefghijklmnopqrstuvxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { CreateVss } + "B" { VssPorts } + "C" { NicMenu } + "D" { VssMtu } + "E" { VssVmPg } + "F" { VssVmkPg } + "G" { PgRename } + "H" { PgVlan } + "I" { Pglbip } + "J" { Pglbsm } + "K" { Pglbsi } + "L" { Pgef } + "M" { ShootVmPg } + "N" { VssPmOn } + "O" { VssFtOn } + "P" { VssMcOn } + "Q" { VssPmOff } + "R" { VssFtOff } + "S" { VssMcOff } + "T" { ShootVmkPg } + "U" { PgSync } + "V" { l3vmotion } + "X" { vCenterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} #End of VssMenu + +#Start of MainMenu +function MainMenu +{ + do { + do { + $version = '2016Aug' + Write-Host -BackgroundColor Black -ForegroundColor Cyan "`nvTool $version" + Write-Host -BackgroundColor White -ForegroundColor Black "`nMain Menu" + Write-Host " + A. vCenter + B. Standalone Hosts" #options to choose from... + + write-host " + Z - Exit" -ForegroundColor Yellow #exits the script + + $user = [Environment]::UserName + $choice = Read-Host "Hi $user, choose one of the above" #Get user's entry + $ok = $choice -match '^[abz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { vCenterMenu } + "B" { StandHostsMenu } + } + } until ( $choice -match "Z" ) + #if ($choice -eq "z") { exit } +} +#end of MainMenu + +#Start of DrsRulesMenu +function DrsRulesMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nDrsRulesMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. VMAffinity + B. VMAntiAffinity + C. DrsVmGroup + D. DrsHostGroup + E. DRSVMToHostRule + " #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdexyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { VMAffinity } + "B" { VMAntiAffinity } + "C" { DrsVmGroup } + "D" { DrsHostGroup } + "E" { DRSVMToHostRule } + "X" { ClusterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of DrsRulesMenu + +#Start of ClusterMenu +function ClusterMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nClusterMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. Create Cluster + B. Add Hosts + C. Configure HA + D. Configure DRS + E. DRS rules + F. Create vApp + G. Add Datastores" #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdefgxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { CreateCluster } + "B" { AddHosts } + "C" { ConfigHA } + "D" { ConfigDrs } + "E" { DrsRulesMenu } + "F" { CreateVapp } + "G" { AddDatastores } + "X" { vCenterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of ClusterMenu + +#Start of HostServicesMenu +function HostServicesMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nHostServicesMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. DCUI [Direct Console UI] + B. TSM [ESXi Shell] + C. TSM-SSH [SSH] + D. lbtd [Load-Based Teaming Daemon] + E. lwsmd [Active Directory Service] + F. ntpd [NTP Daemon] + G. pcscd [PC/SC Smart Card Daemon] + H. sfcbd-watchdog [CIM Server] + I. snmpd [SNMP Server] + J. vmsyslogd [Syslog Server] + K. vprobed [VProbe Daemon] + L. vpxa [VMware vCenter Agent] + M. xorg [X.Org Server] + " #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdefghijklmxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { SetDCUI } + "B" { SetTSM } + "C" { SetSSH } + "D" { SetLbtd } + "E" { Setlwsmd } + "F" { Setntpd } + "G" { Setpcscd } + "H" { Setsfcbd } + "I" { Setsnmpd } + "J" { Setvmsyslogd } + "K" { Setvprobed } + "L" { Setvpxa } + "M" { Setxorg } + "X" { HostMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of HostServicesMenu + +#Start of HostMenu +function HostMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nHostMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. SNMP + B. Syslog settings + C. DNS settings + D. NTP settings + E. Any Advanced setting + F. Firewall Settings + G. Scratch partition + H. Performance settings + I. Core dump settings + J. Power Management (shutdown, reboot, maintenance) + k. Enable/disable services + L. IPv6 + M. VMKernel Services + N. WinSSH (Run SSH commands on esxi from directly from windows) + + W. Others" #[Others menu is to include miscellaneous settings as per business needs] #options to choose from + + Write-Host " + X. Previous Menu + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdefghijklmnwxyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { SetSnmp } + "B" { SetSyslog } + "C" { SetDNS } + "D" { SetNTP } + "E" { EsxiAdvanced } + "F" { SetFirewall } + "G" { SetScratch } + "H" { HostPerf } + "I" { CoreDump } + "J" { PowerMgmt } + "K" { HostServicesMenu } + "L" { SetIpv6 } + "M" { VMKservicesMenu } + "N" { WinSSH } + "W" { Write-Host you chose others. This is not implemented yet } + "X" { vCenterMenu } + "Y" { MainMenu } + } + } until ( $choice -match "Z" ) +} +#end of HostMenu + +#Start of vCenterMenu +function vCenterMenu +{ + do { + do { + Write-Host "Make sure you are connected to a vCenter" -ForegroundColor Yellow + Write-Host "`nvCenterMenu" -BackgroundColor White -ForegroundColor Black + Write-Host " + A. Cluster + B. Host + C. vSwitch + D. dvSwitch" #options to choose from + + Write-Host " + Y. Main Menu + Z. Exit" -BackgroundColor Black -ForegroundColor Green #return to main menu + + $choice = Read-Host "choose one of the above" #Get user's entry + $ok = $choice -match '^[abcdyz]+$' + if ( -not $ok) { write-host "Invalid selection" -BackgroundColor Red } + } until ( $ok ) + switch -Regex ($choice) + { + "A" { ClusterMenu } + "B" { HostMenu } + "C" { VssMenu } + "D" { vdsMenu } + "Y" { HostMenu } + } + } until ( $choice -match "Z" ) +} +#end of vCenterMenu + +#------------------------------End of Collection of Menu Functions-------------------------------# + +PcliPshell +MainMenu +##End of Script##