diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e69de29 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4ac9d8d --- /dev/null +++ b/.gitignore @@ -0,0 +1,51 @@ +# PowerShell Studio Files +*.temppoint.* +*.psproj.psbuild +*.psbuild + +#VS Code Files +*.vscode + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# ========================= +# Operating System Files +# ========================= + +# OSX +# ========================= + +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk \ No newline at end of file diff --git a/Modules/Backup-VCSA.psm1 b/Modules/Backup-VCSA/Backup-VCSA.psm1 similarity index 100% rename from Modules/Backup-VCSA.psm1 rename to Modules/Backup-VCSA/Backup-VCSA.psm1 diff --git a/Modules/DatastoreFunctions/DatastoreFunctions.psm1 b/Modules/DatastoreFunctions/DatastoreFunctions.psm1 new file mode 100644 index 0000000..e417112 --- /dev/null +++ b/Modules/DatastoreFunctions/DatastoreFunctions.psm1 @@ -0,0 +1,184 @@ +#Created by Alan Renouf, published at https://communities.vmware.com/docs/DOC-18008 +Function Get-DatastoreMountInfo { + [CmdletBinding()] + Param ( + [Parameter(ValueFromPipeline=$true)] + $Datastore + ) + Process { + $AllInfo = @() + if (-not $Datastore) { + $Datastore = Get-Datastore + } + Foreach ($ds in $Datastore) { + if ($ds.ExtensionData.info.Vmfs) { + $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].diskname + if ($ds.ExtensionData.Host) { + $attachedHosts = $ds.ExtensionData.Host + Foreach ($VMHost in $attachedHosts) { + $hostview = Get-View $VMHost.Key + $hostviewDSState = $VMHost.MountInfo.Mounted + $StorageSys = Get-View $HostView.ConfigManager.StorageSystem + $devices = $StorageSys.StorageDeviceInfo.ScsiLun + Foreach ($device in $devices) { + $Info = "" | Select Datastore, VMHost, Lun, Mounted, State + if ($device.canonicalName -eq $hostviewDSDiskName) { + $hostviewDSAttachState = "" + if ($device.operationalState[0] -eq "ok") { + $hostviewDSAttachState = "Attached" + } elseif ($device.operationalState[0] -eq "off") { + $hostviewDSAttachState = "Detached" + } else { + $hostviewDSAttachState = $device.operationalstate[0] + } + $Info.Datastore = $ds.Name + $Info.Lun = $hostviewDSDiskName + $Info.VMHost = $hostview.Name + $Info.Mounted = $HostViewDSState + $Info.State = $hostviewDSAttachState + $AllInfo += $Info + } + } + + } + } + } + } + $AllInfo + } +} + +Function Detach-Datastore { + [CmdletBinding()] + Param ( + [Parameter(ValueFromPipeline=$true)] + $Datastore + ) + Process { + if (-not $Datastore) { + Write-Host "No Datastore defined as input" + Exit + } + Foreach ($ds in $Datastore) { + $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname + if ($ds.ExtensionData.Host) { + $attachedHosts = $ds.ExtensionData.Host + Foreach ($VMHost in $attachedHosts) { + $hostview = Get-View $VMHost.Key + $StorageSys = Get-View $HostView.ConfigManager.StorageSystem + $devices = $StorageSys.StorageDeviceInfo.ScsiLun + Foreach ($device in $devices) { + if ($device.canonicalName -eq $hostviewDSDiskName) { + $LunUUID = $Device.Uuid + Write-Host "Detaching LUN $($Device.CanonicalName) from host $($hostview.Name)..." + $StorageSys.DetachScsiLun($LunUUID); + } + } + } + } + } + } +} + +Function Unmount-Datastore { + [CmdletBinding()] + Param ( + [Parameter(ValueFromPipeline=$true)] + $Datastore + ) + Process { + if (-not $Datastore) { + Write-Host "No Datastore defined as input" + Exit + } + Foreach ($ds in $Datastore) { + $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname + if ($ds.ExtensionData.Host) { + $attachedHosts = $ds.ExtensionData.Host + Foreach ($VMHost in $attachedHosts) { + $hostview = Get-View $VMHost.Key + $StorageSys = Get-View $HostView.ConfigManager.StorageSystem + Write-Host "Unmounting VMFS Datastore $($DS.Name) from host $($hostview.Name)..." + $StorageSys.UnmountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); + } + } + } + } +} + +Function Mount-Datastore { + [CmdletBinding()] + Param ( + [Parameter(ValueFromPipeline=$true)] + $Datastore + ) + Process { + if (-not $Datastore) { + Write-Host "No Datastore defined as input" + Exit + } + Foreach ($ds in $Datastore) { + $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname + if ($ds.ExtensionData.Host) { + $attachedHosts = $ds.ExtensionData.Host + Foreach ($VMHost in $attachedHosts) { + $hostview = Get-View $VMHost.Key + $StorageSys = Get-View $HostView.ConfigManager.StorageSystem + Write-Host "Mounting VMFS Datastore $($DS.Name) on host $($hostview.Name)..." + $StorageSys.MountVmfsVolume($DS.ExtensionData.Info.vmfs.uuid); + } + } + } + } +} + +Function Attach-Datastore { + [CmdletBinding()] + Param ( + [Parameter(ValueFromPipeline=$true)] + $Datastore + ) + Process { + if (-not $Datastore) { + Write-Host "No Datastore defined as input" + Exit + } + Foreach ($ds in $Datastore) { + $hostviewDSDiskName = $ds.ExtensionData.Info.vmfs.extent[0].Diskname + if ($ds.ExtensionData.Host) { + $attachedHosts = $ds.ExtensionData.Host + Foreach ($VMHost in $attachedHosts) { + $hostview = Get-View $VMHost.Key + $StorageSys = Get-View $HostView.ConfigManager.StorageSystem + $devices = $StorageSys.StorageDeviceInfo.ScsiLun + Foreach ($device in $devices) { + if ($device.canonicalName -eq $hostviewDSDiskName) { + $LunUUID = $Device.Uuid + Write-Host "Attaching LUN $($Device.CanonicalName) to host $($hostview.Name)..." + $StorageSys.AttachScsiLun($LunUUID); + } + } + } + } + } + } +} +# +#Get-Datastore | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize +# +#Get-Datastore IX2ISCSI01 | Unmount-Datastore +# +#Get-Datastore IX2ISCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize +# +#Get-Datastore IX2iSCSI01 | Mount-Datastore +# +#Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize +# +#Get-Datastore IX2iSCSI01 | Detach-Datastore +# +#Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize +# +#Get-Datastore IX2iSCSI01 | Attach-datastore +# +#Get-Datastore IX2iSCSI01 | Get-DatastoreMountInfo | Sort Datastore, VMHost | FT -AutoSize +# diff --git a/Modules/Get-NICDetails/Get-NICDetails.psm1 b/Modules/Get-NICDetails/Get-NICDetails.psm1 new file mode 100644 index 0000000..30f1440 --- /dev/null +++ b/Modules/Get-NICDetails/Get-NICDetails.psm1 @@ -0,0 +1,93 @@ +function Get-NICDetails { +<# + .NOTES + =========================================================================== + Created by: Markus Kraus + Twitter: @VMarkus_K + Private Blog: mycloudrevolution.com + =========================================================================== + Changelog: + 2017.02 ver 1.0 Base Release + =========================================================================== + External Code Sources: + - + =========================================================================== + Tested Against Environment: + vSphere Version: ESXi 6.0 U2, ESXi 6.5 + PowerCLI Version: PowerCLI 6.3 R1, PowerCLI 6.5 R1 + PowerShell Version: 4.0, 5.0 + OS Version: Windows 8.1, Server 2008 R2, Server 2012 R2 + Keyword: ESXi, NIC, vmnic, Driver, Firmware + =========================================================================== + + .DESCRIPTION + Reports Firmware and Driver Details for your ESXi vmnics. + + .Example + Get-NICDetails -Clustername * + + .PARAMETER Clustername + Name or Wildcard of your vSphere Cluster Name to process. + + +#Requires PS -Version 4.0 +#Requires -Modules VMware.VimAutomation.Core, @{ModuleName="VMware.VimAutomation.Core";ModuleVersion="6.3.0.0"} +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0)] + [ValidateNotNullorEmpty()] + [String] $Clustername + +) + +Begin { + $Validate = $True + + if (($myCluster = Get-Cluster -Name $Clustername).count -lt 1) { + $Validate = $False + thow "No Cluster '$myCluster' found!" + } + +} + +Process { + + $MyView = @() + if ($Validate -eq $True) { + + foreach ($myVMhost in ($myCluster | Get-VMHost)) { + + $esxcli2 = Get-ESXCLI -VMHost $myVMhost -V2 + $niclist = $esxcli2.network.nic.list.invoke() + + $nicdetails = @() + foreach ($nic in $niclist) { + + $args = $esxcli2.network.nic.get.createargs() + $args.nicname = $nic.name + $nicdetail = $esxcli2.network.nic.get.Invoke($args) + $nicdetails += $nicdetail + + } + ForEach ($nicdetail in $nicdetails){ + $NICReport = [PSCustomObject] @{ + Host = $myVMhost.Name + vmnic = $nicdetail.Name + LinkStatus = $nicdetail.LinkStatus + BusInfo = $nicdetail.driverinfo.BusInfo + Driver = $nicdetail.driverinfo.Driver + FirmwareVersion = $nicdetail.driverinfo.FirmwareVersion + DriverVersion = $nicdetail.driverinfo.Version + } + $MyView += $NICReport + } + + } + + $MyView + + } +} +} \ No newline at end of file diff --git a/Modules/Get-NewAndRemovedVMs/Get-NewAndRemovedVMs.psm1 b/Modules/Get-NewAndRemovedVMs/Get-NewAndRemovedVMs.psm1 new file mode 100644 index 0000000..4a2e3ba --- /dev/null +++ b/Modules/Get-NewAndRemovedVMs/Get-NewAndRemovedVMs.psm1 @@ -0,0 +1,131 @@ +function Get-NewAndRemovedVMs { +<# + .NOTES + =========================================================================== + Created by: Markus Kraus + Twitter: @VMarkus_K + Private Blog: mycloudrevolution.com + =========================================================================== + Changelog: + 2016.12 ver 1.0 Base Release + =========================================================================== + External Code Sources: + https://github.com/alanrenouf/vCheck-vSphere + =========================================================================== + 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 + =========================================================================== + Keywords vSphere, VM + =========================================================================== + + .DESCRIPTION + This Function report newly created and deleted VMs by Cluster. + + .Example + Get-NewAndRemovedVMs -ClusterName Cluster* | ft -AutoSize + + .Example + Get-NewAndRemovedVMs -ClusterName Cluster01 -Days 90 + + .PARAMETER ClusterName + Name or Wildcard of your vSphere Cluster Name(s) to report. + + .PARAMETER Day + Range in Days to report. + + +#Requires PS -Version 4.0 +#Requires -Modules VMware.VimAutomation.Core, @{ModuleName="VMware.VimAutomation.Core";ModuleVersion="6.3.0.0"} +#> + +param( + [Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0, HelpMessage = "Name or Wildcard of your vSphere Cluster Name to report")] + [ValidateNotNullorEmpty()] + [String]$ClusterName, + [Parameter(Mandatory=$False, ValueFromPipeline=$False, Position=1, HelpMessage = "Range in Days to report")] + [ValidateNotNullorEmpty()] + [String]$Days = "30" +) +Begin { + function Get-VIEventPlus { + + param( + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl[]]$Entity, + [string[]]$EventType, + [DateTime]$Start, + [DateTime]$Finish = (Get-Date), + [switch]$Recurse, + [string[]]$User, + [Switch]$System, + [string]$ScheduledTask, + [switch]$FullMessage = $false, + [switch]$UseUTC = $false + ) + + process { + $eventnumber = 100 + $events = @() + $eventMgr = Get-View EventManager + $eventFilter = New-Object VMware.Vim.EventFilterSpec + $eventFilter.disableFullMessage = ! $FullMessage + $eventFilter.entity = New-Object VMware.Vim.EventFilterSpecByEntity + $eventFilter.entity.recursion = &{if($Recurse){"all"}else{"self"}} + $eventFilter.eventTypeId = $EventType + if($Start -or $Finish){ + $eventFilter.time = New-Object VMware.Vim.EventFilterSpecByTime + if($Start){ + $eventFilter.time.beginTime = $Start + } + if($Finish){ + $eventFilter.time.endTime = $Finish + } + } + if($User -or $System){ + $eventFilter.UserName = New-Object VMware.Vim.EventFilterSpecByUsername + if($User){ + $eventFilter.UserName.userList = $User + } + if($System){ + $eventFilter.UserName.systemUser = $System + } + } + if($ScheduledTask){ + $si = Get-View ServiceInstance + $schTskMgr = Get-View $si.Content.ScheduledTaskManager + $eventFilter.ScheduledTask = Get-View $schTskMgr.ScheduledTask | + where {$_.Info.Name -match $ScheduledTask} | + Select -First 1 | + Select -ExpandProperty MoRef + } + if(!$Entity){ + $Entity = @(Get-Folder -NoRecursion) + } + $entity | %{ + $eventFilter.entity.entity = $_.ExtensionData.MoRef + $eventCollector = Get-View ($eventMgr.CreateCollectorForEvents($eventFilter)) + $eventsBuffer = $eventCollector.ReadNextEvents($eventnumber) + while($eventsBuffer){ + $events += $eventsBuffer + $eventsBuffer = $eventCollector.ReadNextEvents($eventnumber) + } + $eventCollector.DestroyCollector() + } + if (-not $UseUTC) + { + $events | % { $_.createdTime = $_.createdTime.ToLocalTime() } + } + + $events + } +} +} + +process { + $result = Get-VIEventPlus -Start ((get-date).adddays(-$Days)) -EventType @("VmCreatedEvent", "VmBeingClonedEvent", "VmBeingDeployedEvent","VmRemovedEvent") + $sortedResult = $result | Select CreatedTime, @{N='Cluster';E={$_.ComputeResource.Name}}, @{Name="VMName";Expression={$_.vm.name}}, UserName, @{N='Type';E={$_.GetType().Name}}, FullFormattedMessage | Sort CreatedTime + $sortedResult | where {$_.Cluster -like $ClusterName} +} +} \ No newline at end of file diff --git a/Modules/Get-VMmaxIOPS.psm1 b/Modules/Get-VMmaxIOPS.psm1 deleted file mode 100644 index 8ef86e3..0000000 --- a/Modules/Get-VMmaxIOPS.psm1 +++ /dev/null @@ -1,85 +0,0 @@ -function Get-VMmaxIOPS { -<# - - .SYNOPSIS - Report VM Disk IOPS of VMs - - .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) - - .Notes - NAME: Get-VMmaxIOPS.ps1 - LASTEDIT: 08/23/2016 - VERSION: 1.1 - KEYWORDS: VMware, vSphere, ESXi, IOPS - - .Link - http://mycloudrevolution.com/ - -#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, - [Parameter(Mandatory=$false, Position=1)] - [int] $Minutes = 30 -) - -Process { - - #region: Global Definitions - [int]$TimeRange = "-" + $Minutes - #endregion - - #region: Creating Metrics - Write-Debug "Starting to Create Metrics..." - $metrics = "virtualDisk.numberReadAveraged.average","virtualDisk.numberWriteAveraged.average" - $start = (Get-Date).AddMinutes($TimeRange) - $stats = Get-Stat -Stat $metrics -Entity $VMs -Start $start - #endregion - - #region: Creating HD-Tab - Write-Debug "Starting to 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('[') - } - #endregion - - #region: Creating Reports - Write-Debug "Starting to Process IOPS Report..." - $reportPerf = @() - $reportPerf = $stats | Group-Object -Property {$_.Entity.Name},Instance | %{ - New-Object PSObject -Property @{ - VM = $_.Values[0] - Disk = $_.Values[1] - IOPSMax = ($_.Group | ` - Group-Object -Property Timestamp | ` - %{$_.Group[0].Value + $_.Group[1].Value} | ` - Measure-Object -Maximum).Maximum - Datastore = $hdTab[$_.Values[0] + "/"+ $_.Values[1]] - } - } - $reportPerf | Select-Object VM, Disk, Datastore, IOPSMax - #endregion - } -} \ No newline at end of file diff --git a/Modules/Get-VMmaxIOPS/Get-VMmaxIOPS.psm1 b/Modules/Get-VMmaxIOPS/Get-VMmaxIOPS.psm1 new file mode 100644 index 0000000..27af1ad --- /dev/null +++ b/Modules/Get-VMmaxIOPS/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/Konfig-ESXi/Konfig-ESXi.psm1 b/Modules/Konfig-ESXi/Konfig-ESXi.psm1 new file mode 100644 index 0000000..f14386a --- /dev/null +++ b/Modules/Konfig-ESXi/Konfig-ESXi.psm1 @@ -0,0 +1,234 @@ +function Konfig-ESXi { +<# + .NOTES + =========================================================================== + Created by: Markus Kraus + Twitter: @VMarkus_K + Private Blog: mycloudrevolution.com + =========================================================================== + Changelog: + 2016.12 ver 1.0 Base Release + 2016.12 ver 1.1 ESXi 6.5 Tests, Minor enhancements + =========================================================================== + External Code Sources: + Function My-Logger : http://www.virtuallyghetto.com/ + =========================================================================== + Tested Against Environment: + vSphere Version: ESXi 5.5 U2, ESXi 6.5 + PowerCLI Version: PowerCLI 6.3 R1, PowerCLI 6.5 R1 + PowerShell Version: 4.0, 5.0 + OS Version: Windows 8.1, Server 2012 R2 + Keyword: ESXi, NTP, SSH, Syslog, SATP, + =========================================================================== + + .DESCRIPTION + This Function sets the Basic settings for a new ESXi. + + * NTP + * SSH + * Syslog + * Power Management + * HP 3PAR SATP/PSP Rule + * ... + + .Example + Konfig-ESXi -VMHost myesxi.lan.local -NTP 192.168.2.1, 192.168.2.2 -syslog "udp://loginsight.lan.local:514" + + .PARAMETER VMHost + Host to configure. + + .PARAMETER NTP + NTP Server(s) to set. + + .PARAMETER Syslog + Syslog Server to set, e.g. "udp://loginsight.lan.local:514" + + DNS Name must be resolvable! + + +#Requires PS -Version 4.0 +#Requires -Modules VMware.VimAutomation.Core, @{ModuleName="VMware.VimAutomation.Core";ModuleVersion="6.3.0.0"} +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0)] + [String] $VMHost, + [Parameter(Mandatory=$true, ValueFromPipeline=$False, Position=1)] + [array]$NTP, + [Parameter(Mandatory=$true, ValueFromPipeline=$False, Position=2)] + [String] $syslog + +) + +Begin { + 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" + } + function Set-MyESXiOption { + [CmdletBinding()] + param( + [Parameter(Mandatory=$True, ValueFromPipeline=$False, Position=0)] + [String] $Name, + [Parameter(Mandatory=$False, ValueFromPipeline=$False, Position=1)] + [String] $Value + ) + process { + $myESXiOption = Get-AdvancedSetting -Entity $ESXiHost -Name $Name + if ($myESXiOption.Value -ne $Value) { + My-Logger " Setting ESXi Option $Name to Value $Value" + $myESXiOption | Set-AdvancedSetting -Value $Value -Confirm:$false | Out-Null + } + else { + My-Logger " ESXi Option $Name already has Value $Value" + } + } + } +} + +Process { + $Validate = $True + + #region: Start vCenter Connection + My-Logger "Starting to Process ESXi Server Connection to $VMHost ..." + if (($global:DefaultVIServers).count -gt 0) { + Disconnect-VIServer -Force -Confirm:$False -ErrorAction SilentlyContinue + } + $VIConnection = Connect-VIServer -Server $VMHost + if (-not $VIConnection.IsConnected) { + Write-Error "ESXi Connection Failed." + $Validate = $False + } + elseif ($VIConnection.ProductLine -ne "EmbeddedEsx") { + Write-Error "Connencted System is not an ESXi." + $Validate = $False + } + else { + $ESXiHost = Get-VMHost + My-Logger "Connected ESXi Version: $($ESXiHost.Version) $($ESXiHost.Build) " + } + #endregion + + if ($Validate -eq $True) { + + #region: Enable SSH and disable SSH Warning + $SSHService = $ESXiHost | Get-VMHostService | where {$_.Key -eq 'TSM-SSH'} + My-Logger "Starting SSH Service..." + if($SSHService.Running -ne $True){ + Start-VMHostService -HostService $SSHService -Confirm:$false | Out-Null + } + else { + My-Logger " SSH Service is already running" + } + My-Logger "Setting SSH Service to Automatic Start..." + if($SSHService.Policy -ne "automatic"){ + Set-VMHostService -HostService $SSHService -Policy "Automatic" | Out-Null + } + else { + My-Logger " SSH Service is already set to Automatic Start" + } + My-Logger "Disabling SSH Warning..." + Set-MyESXiOption -Name "UserVars.SuppressShellWarning" -Value "1" + #endregion + + #region: Config NTP + My-Logger "Removing existing NTP Server..." + try { + $ESXiHost | Remove-VMHostNtpServer -NtpServer (Get-VMHostNtpServer) -Confirm:$false + } + catch [System.Exception] { + Write-Warning "Error during removing existing NTP Servers." + } + My-Logger "Setting new NTP Servers..." + foreach ($myNTP in $NTP) { + $ESXiHost | Add-VMHostNtpServer -ntpserver $myNTP -confirm:$False | Out-Null + } + + My-Logger "Configure NTP Service..." + $NTPService = $ESXiHost | Get-VMHostService| Where-Object {$_.key -eq "ntpd"} + if($NTPService.Running -eq $True){ + Stop-VMHostService -HostService $NTPService -Confirm:$false | Out-Null + } + if($NTPService.Policy -ne "on"){ + Set-VMHostService -HostService $NTPService -Policy "on" -confirm:$False | Out-Null + } + + My-Logger "Configure Local Time..." + $HostTimeSystem = Get-View $ESXiHost.ExtensionData.ConfigManager.DateTimeSystem + $HostTimeSystem.UpdateDateTime([DateTime]::UtcNow) + + My-Logger "Start NTP Service..." + Start-VMHostService -HostService $NTPService -confirm:$False | Out-Null + #endregion + + #region: Remove default PG + My-Logger "Checking for Default Port Group ..." + if ($defaultPG = $ESXiHost | Get-VirtualSwitch -Name vSwitch0 | Get-VirtualPortGroup -Name "VM Network" -ErrorAction SilentlyContinue ){ + Remove-VirtualPortGroup -VirtualPortGroup $defaultPG -confirm:$False | Out-Null + My-Logger " Default PG Removed" + } + else { + My-Logger " No Default PG found" + } + #endregion + + #region: Configure Static HighPower + My-Logger "Setting PowerProfile to Static HighPower..." + try { + $HostView = ($ESXiHost | Get-View) + (Get-View $HostView.ConfigManager.PowerSystem).ConfigurePowerPolicy(1) + } + catch [System.Exception] { + Write-Warning "Error during Configure Static HighPower. See latest errors..." + } + #endregion + + #region: Conf Syslog + My-Logger "Setting Syslog Firewall Rule ..." + $SyslogFW = ($ESXiHost | Get-VMHostFirewallException | where {$_.Name -eq 'syslog'}) + if ($SyslogFW.Enabled -eq $False ){ + $SyslogFW | Set-VMHostFirewallException -Enabled:$true -Confirm:$false | Out-Null + My-Logger " Syslog Firewall Rule enabled" + } + else { + My-Logger " Syslog Firewall Rule already enabled" + } + My-Logger "Setting Syslog Server..." + Set-MyESXiOption -Name "Syslog.global.logHost" -Value $syslog + #endregion + + #region: Change Disk Scheduler + My-Logger "Changing Disk Scheduler..." + Set-MyESXiOption -Name "Disk.SchedulerWithReservation" -Value "0" + #endregion + + #region: Configure HP 3PAR SATP/PSP Rule + My-Logger "Configure HP 3PAR SATP/PSP Rule" + $esxcli2 = Get-ESXCLI -VMHost $ESXiHost -V2 + $arguments = $esxcli2.storage.nmp.satp.rule.add.CreateArgs() + $arguments.satp = "VMW_SATP_ALUA" + $arguments.psp = "VMW_PSP_RR" + $arguments.pspoption = "iops=100" + $arguments.claimoption = "tpgs_on" + $arguments.vendor = "3PARdata" + $arguments.model = "VV" + $arguments.description = "HP 3PAR custom SATP Claimrule" + try { + $esxcli2.storage.nmp.satp.rule.add.Invoke($arguments) + } + catch { + Write-Warning "Error during Configure HP 3PAR SATP/PSP Rule. See latest errors..." + } + #endregion + + } + } +} diff --git a/Modules/PSvLIMessage.psm1 b/Modules/PSvLIMessage/PSvLIMessage.psm1 similarity index 100% rename from Modules/PSvLIMessage.psm1 rename to Modules/PSvLIMessage/PSvLIMessage.psm1 diff --git a/Modules/ProactiveHA/ProactiveHA.psm1 b/Modules/ProactiveHA/ProactiveHA.psm1 new file mode 100644 index 0000000..ea4e92f --- /dev/null +++ b/Modules/ProactiveHA/ProactiveHA.psm1 @@ -0,0 +1,468 @@ +Function New-PHAProvider { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to register a new Proactive HA Provider with vCenter Server + .PARAMETER ProviderName + Name of ProactiveHA Provider + .PARAMETER ComponentType + Name of a supported ComponentType that ProactiveHA supports (Fan, Memory, Network, Power or Storage) + .PARAMETER ComponentDescription + Description of the health check for the given component + .PARAMETER ComponentId + Unique identifier for the given component within a ProactiveHA Provider + .EXAMPLE + New-PHAProvider -ProviderName "virtuallyGhetto" -ComponentType Power -ComponentDescription "Simulated ProactiveHA Provider" -ComponentId "Power" +#> + param( + [Parameter(Mandatory=$true)][String]$ProviderName, + [Parameter(Mandatory=$true)][ValidateSet("Fan","Memory","Network","Power","Storage")][String]$ComponentType, + [Parameter(Mandatory=$true)][String]$ComponentDescription, + [Parameter(Mandatory=$true)][String]$ComponentId + ) + Write-Host -ForegroundColor Red "`n******************** DISCLAIMER ********************" + Write-Host -ForegroundColor Red "**** THIS IS NOT INTENDED FOR PRODUCTION USE ****" + Write-Host -ForegroundColor Red "**** LEARNING PURPOSES ONLY ****" + Write-Host -ForegroundColor Red "******************** DISCLAIMER ********************`n" + + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + $healthInfo = [VMware.Vim.HealthUpdateInfo] @{ + ComponentType = $ComponentType + description = $ComponentDescription + Id = $ComponentId + } + + try { + Write-Host "`nRegistering new Proactive HA Provider $ProviderName ..." + $providerId = $healthManager.RegisterHealthUpdateProvider($ProviderName,$healthInfo) + } catch { + Write-host -ForegroundColor Red $Error[0].Exception + } +} + +Function Get-PHAProvider { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to return list of all Proactive HA Providers registered with vCenter Server + .EXAMPLE + Get-PHAProvider +#> + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + $healthProviderResults = @() + $hpIDs = $healthManager.QueryProviderList() + + foreach ($hpID in $hpIDs) { + $hpName = $healthManager.QueryProviderName($hpID) + $hpConfig = $healthManager.QueryHealthUpdateInfos($hpID) + + $hp = [pscustomobject] @{ + ProviderName = $hpName + ProviderID = $hpID + ComponentType = $hpConfig.componentType + ComponentID = $hpConfig.id + Description = $hpConfig.description + } + $healthProviderResults+=$hp + } + $healthProviderResults +} + +Function Remove-PHAProvider { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to remove a registered Proactive HA Provider from vCenter Server + .PARAMETER ProviderId + The ProactiveHA provider ID (retrieved from Get-PHAProvider) to unregister + .EXAMPLE + Remove-PHAProvider -ProviderID "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79" +#> + param( + [Parameter(Mandatory=$true)][String]$ProviderId + ) + + Write-Host -ForegroundColor Red "`n******************** DISCLAIMER ********************" + Write-Host -ForegroundColor Red "**** THIS IS NOT INTENDED FOR PRODUCTION USE ****" + Write-Host -ForegroundColor Red "**** LEARNING PURPOSES ONLY ****" + Write-Host -ForegroundColor Red "******************** DISCLAIMER ********************`n" + + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + try { + Write-Host "`nUnregistering Proactive HA Provider $ProviderId ... " + $healthManager.UnregisterHealthUpdateProvider($providerId) + } catch { + if($Error[0].Exception.InnerException.MethodFault.getType().Name -eq "InvalidState") { + Write-host -ForegroundColor Red "The Proactive HA Provider is still in use, please disable it before unregistering" + } else { + Write-host -ForegroundColor Red $Error[0].Exception + } + } +} + +Function Set-PHAConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to enable/disable Proactive HA for vSphere Cluster + .PARAMETER Cluster + Name of the vSphere Cluster to enable Proactive HA + .PARAMETER ProviderId + Proactive HA Provider ID to enable in vSphere Cluster + .PARAMETER ClusterMode + Whether Proactive HA should be "Automated" or "Manual" for actions it will take + .PARAMETER ModerateRemediation + Type of operation (Maintenance Mode or Quaratine Mode) to perform when a Moderate issue is observed + .PARAMETER SevereRemediation + Type of operation (Maintenance Mode or Quaratine Mode) to perform when a Severe issue is observed + .EXAMPLE + Set-PHAConfig -Cluster VSAN-Cluster -Enabled -ClusterMode Automated -ModerateRemediation QuarantineMode -SevereRemediation QuarantineMode -ProviderID "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79" + .EXAMPLE + Set-PHAConfig -Cluster VSAN-Cluster -Disabled -ProviderID "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79" +#> + param( + [Parameter(Mandatory=$true)][String]$ProviderId, + [Parameter(Mandatory=$true)][String]$Cluster, + [Parameter(Mandatory=$false)][ValidateSet("Automated","Manual")]$ClusterMode="Manual", + [Parameter(Mandatory=$false)][ValidateSet("MaintenanceMode","QuarantineMode")]$ModerateRemediation="QuarantineMode", + [Parameter(Mandatory=$false)][ValidateSet("MaintenanceMode","QuarantineMode")]$SevereRemediation="QuarantineMode", + [Switch]$Enabled, + [Switch]$Disabled + ) + + $ClusterView = Get-View -ViewType ClusterComputeResource -Property Name,Host,ConfigurationEx -Filter @{"Name" = $Cluster} + + if($ClusterView -eq $null) { + Write-Host -ForegroundColor Red "Unable to find vSphere Cluster $cluster ..." + break + } + + $vmhosts = $ClusterView.host + + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + if($Enabled) { + try { + $entities = @() + foreach ($vmhost in $vmhosts) { + if(-not $healthManager.HasMonitoredEntity($ProviderId,$vmhost)) { + $entities += $vmhost + } + } + + Write-Host "Enabling Proactive HA monitoring for all ESXi hosts in cluster ..." + $healthManager.AddMonitoredEntities($ProviderId,$entities) + } catch { + Write-host -ForegroundColor Red $Error[0].Exception + } + + try { + $healthProviders = @() + + # Make sure not to remove existing ProactiveHA providers + if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) { + $currentHPs = $ClusterView.ConfigurationEx.infraUpdateHaConfig.providers + foreach ($currentHP in $currentHPs) { + $healthProviders+=$currentHP + } + if(-not ($healthProviders -contains $ProviderID)) { + $healthProviders+=$ProviderId + } + } else { + $healthProviders+=$ProviderId + } + + $PHASpec = [VMware.Vim.ClusterInfraUpdateHaConfigInfo] @{ + enabled = $true + behavior = $ClusterMode + moderateRemediation = $ModerateRemediation + severeRemediation = $SevereRemediation + providers = $healthProviders + } + + $spec = [VMware.Vim.ClusterConfigSpecEx] @{ + infraUpdateHaConfig = $PHASpec + } + + Write-Host "Enabling Proactive HA Provider $ProviderId on $Cluster ..." + $task = $ClusterView.ReconfigureComputeResource_Task($spec,$True) + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task | Out-Null + } catch { + Write-host -ForegroundColor Red $Error[0].Exception + } + } + + if($Disabled) { + foreach ($vmhost in $vmhosts) { + if($vmhost.runtime.inQuarantineMode) { + Write-Host -ForegroundColor Red $vmhost.name " is currently still in Quaratine Mode, please remediate this before disabling Proactive HA" + break + } + } + + try { + $healthProviders = @() + + # Make sure not to remove existing ProactiveHA providers + if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) { + $currentHPs = $ClusterView.ConfigurationEx.infraUpdateHaConfig.providers + foreach ($currentHP in $currentHPs) { + if($currentHP -ne $ProviderId) { + $healthProviders+=$currentHP + } + } + } + + $PHASpec = [VMware.Vim.ClusterInfraUpdateHaConfigInfo] @{ + enabled = $true + behavior = $ClusterMode + moderateRemediation = $ModerateRemediation + severeRemediation = $SevereRemediation + providers = $healthProviders + } + + $spec = [VMware.Vim.ClusterConfigSpecEx] @{ + infraUpdateHaConfig = $PHASpec + } + + Write-Host "Disabling Proactive HA Provider $ProviderId on $Cluster ..." + $task = $ClusterView.ReconfigureComputeResource_Task($spec,$True) + $task1 = Get-Task -Id ("Task-$($task.value)") + $task1 | Wait-Task | Out-Null + } catch { + Write-host -ForegroundColor Red $Error[0].Exception + } + + $ClusterView.UpdateViewData() + + try { + $entities = @() + foreach ($vmhost in $vmhosts) { + if($healthManager.HasMonitoredEntity($ProviderId,$vmhost)) { + $entities += $vmhost + } + } + + Write-Host "Disabling Proactive HA monitoring for all ESXi hosts in cluster ..." + $healthManager.RemoveMonitoredEntities($ProviderId,$entities) + } catch { + Write-host -ForegroundColor Red $Error[0].Exception + } + } +} + +Function Get-PHAConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to retrieve Proactive HA configuration for a vSphere Cluster + .PARAMETER Cluster + Name of the vSphere Cluster to check Proactive HA configuration + .EXAMPLE + Get-PHAConfig -Cluster VSAN-Cluster +#> + param( + [Parameter(Mandatory=$true)][String]$Cluster + ) + + $ClusterView = Get-View -ViewType ClusterComputeResource -Property Name,ConfigurationEx -Filter @{"Name" = $Cluster} + + if($ClusterView -eq $null) { + Write-Host -ForegroundColor Red "Unable to find vSphere Cluster $cluster ..." + break + } + + if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) { + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + $phSettings = $ClusterView.ConfigurationEx.InfraUpdateHaConfig + $providers = $ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers + $healthProviders = @() + foreach ($provider in $providers) { + $providerName = $healthManager.QueryProviderName($provider) + $healthProviders+=$providerName + } + + $pHAConfig = [pscustomobject] @{ + Enabled = $phSettings.Enabled + ClusterMode = $phSettings.behavior + ModerateRemediation = $phSettings.ModerateRemediation + SevereRemediation = $phSettings.SevereRemediation + HealthProviders = $healthProviders + } + $pHAConfig + } else { + Write-Host "Proactive HA has not been configured on this vSphere Cluster" + } +} + +Function Get-PHAHealth { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to retrieve the Proactive HA health info for all ESXi hosts in vSphere Cluster + .PARAMETER Cluster + Name of the vSphere Cluster to check Proactive HA health information + .EXAMPLE + Get-PHAHealth -Cluster VSAN-Cluster +#> + param( + [Parameter(Mandatory=$true)][String]$Cluster + ) + + $ClusterView = Get-View -ViewType ClusterComputeResource -Property Name,ConfigurationEx -Filter @{"Name" = $Cluster} + + if($ClusterView -eq $null) { + Write-Host -ForegroundColor Red "Unable to find vSphere Cluster $cluster ..." + break + } + + if($ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers -ne $null) { + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + $providers = $ClusterView.ConfigurationEx.InfraUpdateHaConfig.Providers + + foreach ($provider in $providers) { + $providerName = $healthManager.QueryProviderName($provider) + $healthUpdates = $healthManager.QueryHealthUpdates($provider) + + $healthResults = @() + Write-Host -NoNewline -ForegroundColor Magenta "Health summary for Proactive HA Provider $providerName`:`n" + foreach ($healthUpdate in $healthUpdates) { + $vmhost = Get-View $healthUpdate.Entity + + $hr = [PSCustomObject] @{ + Entity = $vmhost.name + Status = $healthUpdate.status + HealthComponentId = $healthUpdate.HealthUpdateInfoId + HealthUpdateId = $healthUpdate.Id + Remediation = $healthUpdate.Remediation + } + $healthResults+=$hr + } + $healthResults + } + } else { + Write-Host "Proactive HA has not been configured on this vSphere Cluster" + } +} + +Function New-PHASimulation { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + Function to return VCHA Configuration + .PARAMETER ProviderId + The Proactive HA Provider ID that you like to simulate a health update from + .PARAMETER EsxiHost + The name of ESXi host to update the health on + .PARAMETER Component + The name of the matching component ID from Proactive HA Provider to simulate a health update from + .PARAMETER HealthStatus + The health value (green, yellow or red) for the given simulated health Update + .PARAMETER Remediation + The remediation message associated with simulated health update + .EXAMPLE + New-PHASimulation -EsxiHost vesxi65-4.primp-industries.com -Component Power -HealthStatus green -Remediation "" -ProviderId "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79" + .EXAMPLE + New-PHASimulation -EsxiHost vesxi65-4.primp-industries.com -Component Power -HealthStatus red -Remediation "Please replace my virtual PSU" -ProviderId "52 85 22 c2 f2 6a e7 b9-fc ff 63 9e 10 81 00 79" +#> + param( + [Parameter(Mandatory=$true)][String]$ProviderId, + [Parameter(Mandatory=$true)][String]$EsxiHost, + [Parameter(Mandatory=$true)][String]$Component, + [Parameter(Mandatory=$true)][ValidateSet("green","red","yellow")][String]$HealthStatus, + [Parameter(Mandatory=$false)][String]$Remediation + ) + + Write-Host -ForegroundColor Red "`n******************** DISCLAIMER ********************" + Write-Host -ForegroundColor Red "**** THIS IS NOT INTENDED FOR PRODUCTION USE ****" + Write-Host -ForegroundColor Red "**** LEARNING PURPOSES ONLY ****" + Write-Host -ForegroundColor Red "******************** DISCLAIMER ********************`n" + + $vmhost = Get-View -ViewType HostSystem -Property Name -Filter @{"name" = $EsxiHost} + + if($vmhost -eq $null) { + Write-Host -ForegroundColor Red "`nUnable to find ESXi host $EsxiHost ..." + break + } + + $healthManager = Get-View $global:DefaultVIServer.ExtensionData.Content.HealthUpdateManager + + # Randomly generating an ID for Health Update + # In general, you would want to generate a specific ID + # which can be referenced between ProactiveHA Provider + # and VMware logs for troubleshooting purposes + $HealthUpdateID = "vghetto-" + (Get-Random -Minimum 1 -Maximum 100000) + + # All other Health Status can have a remediation message + # but for green, it must be an empty string or API call will fail + if($HealthStatus -eq "green") { + $Remediation = "" + } + + $healthUpdate = [VMware.Vim.HealthUpdate] @{ + Entity = $vmhost.moref + HealthUpdateInfoId = $Component + Id = $HealthUpdateId + Status = $HealthStatus + Remediation = $Remediation + } + + try { + Write-Host "`nSimulating Proactive HA Health Update to ..." + Write-Host "`tHost: $EsxiHost " + Write-Host -NoNewline "`tStatus: " + Write-Host -ForegroundColor $HealthStatus "$HealthStatus" + Write-Host "`tRemediation Messsage: $Remediation" + $healthManager.PostHealthUpdates($providerId,$healthUpdate) + } catch { + Write-host -ForegroundColor Red $Error[0].Exception + } +} \ No newline at end of file diff --git a/Modules/Recommend-Sizing.psm1 b/Modules/Recommend-Sizing/Recommend-Sizing.psm1 similarity index 100% rename from Modules/Recommend-Sizing.psm1 rename to Modules/Recommend-Sizing/Recommend-Sizing.psm1 diff --git a/Modules/Set-CBT.psm1 b/Modules/Set-CBT/Set-CBT.psm1 similarity index 100% rename from Modules/Set-CBT.psm1 rename to Modules/Set-CBT/Set-CBT.psm1 diff --git a/Modules/Start-UNMAP.psm1 b/Modules/Start-UNMAP/Start-UNMAP.psm1 similarity index 100% rename from Modules/Start-UNMAP.psm1 rename to Modules/Start-UNMAP/Start-UNMAP.psm1 diff --git a/Modules/VAMI/VAMI.psm1 b/Modules/VAMI/VAMI.psm1 new file mode 100755 index 0000000..92c5d5f --- /dev/null +++ b/Modules/VAMI/VAMI.psm1 @@ -0,0 +1,716 @@ +Function Get-VAMISummary { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves some basic information from VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return basic VAMI summary info + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMISummary +#> + $systemVersionAPI = Get-CisService -Name 'com.vmware.appliance.system.version' + $results = $systemVersionAPI.get() | select product, type, version, build, install_time + + $systemUptimeAPI = Get-CisService -Name 'com.vmware.appliance.system.uptime' + $ts = [timespan]::fromseconds($systemUptimeAPI.get().toString()) + $uptime = $ts.ToString("hh\:mm\:ss\,fff") + + $summaryResult = [pscustomobject] @{ + Product = $results.product; + Type = $results.type; + Version = $results.version; + Build = $results.build; + InstallTime = $results.install_time; + Uptime = $uptime + } + $summaryResult +} + +Function Get-VAMIHealth { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves health information from VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return VAMI health + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIHealth +#> + $healthOverall = (Get-CisService -Name 'com.vmware.appliance.health.system').get() + $healthLastCheck = (Get-CisService -Name 'com.vmware.appliance.health.system').lastcheck() + $healthCPU = (Get-CisService -Name 'com.vmware.appliance.health.load').get() + $healthMem = (Get-CisService -Name 'com.vmware.appliance.health.mem').get() + $healthSwap = (Get-CisService -Name 'com.vmware.appliance.health.swap').get() + $healthStorage = (Get-CisService -Name 'com.vmware.appliance.health.storage').get() + + # DB health only applicable for Embedded/External VCSA Node + $vami = (Get-CisService -Name 'com.vmware.appliance.system.version').get() + + if($vami.type -eq "vCenter Server with an embedded Platform Services Controller" -or $vami.type -eq "vCenter Server with an external Platform Services Controller") { + $healthVCDB = (Get-CisService -Name 'com.vmware.appliance.health.databasestorage').get() + } else { + $healthVCDB = "N/A" + } + $healthSoftwareUpdates = (Get-CisService -Name 'com.vmware.appliance.health.softwarepackages').get() + + $healthResult = [pscustomobject] @{ + HealthOverall = $healthOverall; + HealthLastCheck = $healthLastCheck; + HealthCPU = $healthCPU; + HealthMem = $healthMem; + HealthSwap = $healthSwap; + HealthStorage = $healthStorage; + HealthVCDB = $healthVCDB; + HealthSoftware = $healthSoftwareUpdates + } + $healthResult +} + +Function Get-VAMIAccess { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves access information from VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return VAMI access interfaces (Console,DCUI,Bash Shell & SSH) + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIAccess +#> + $consoleAccess = (Get-CisService -Name 'com.vmware.appliance.access.consolecli').get() + $dcuiAccess = (Get-CisService -Name 'com.vmware.appliance.access.dcui').get() + $shellAccess = (Get-CisService -Name 'com.vmware.appliance.access.shell').get() + $sshAccess = (Get-CisService -Name 'com.vmware.appliance.access.ssh').get() + + $accessResult = New-Object PSObject -Property @{ + Console = $consoleAccess; + DCUI = $dcuiAccess; + BashShell = $shellAccess.enabled; + SSH = $sshAccess + } + $accessResult +} + +Function Get-VAMITime { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves the time and NTP info from VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return current Time and NTP information + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMITime +#> + $systemTimeAPI = Get-CisService -Name 'com.vmware.appliance.system.time' + $timeResults = $systemTimeAPI.get() + + $timeSync = (Get-CisService -Name 'com.vmware.appliance.techpreview.timesync').get() + $timeSyncMode = $timeSync.mode + + $timeResult = [pscustomobject] @{ + Timezone = $timeResults.timezone; + Date = $timeResults.date; + CurrentTime = $timeResults.time; + Mode = $timeSyncMode; + NTPServers = "N/A"; + NTPStatus = "N/A"; + } + + if($timeSyncMode -eq "NTP") { + $ntpServers = (Get-CisService -Name 'com.vmware.appliance.techpreview.ntp').get() + $timeResult.NTPServers = $ntpServers.servers + $timeResult.NTPStatus = $ntpServers.status + } + $timeResult +} + +Function Get-VAMINetwork { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves network information from VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return networking information including details for each interface + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMINetwork +#> + $netResults = @() + + $Hostname = (Get-CisService -Name 'com.vmware.appliance.networking.dns.hostname').get() + $dns = (Get-CisService -Name 'com.vmware.appliance.networking.dns.servers').get() + + Write-Host "Hostname: " $hostname + Write-Host "DNS Servers: " $dns.servers + + $interfaces = (Get-CisService -Name 'com.vmware.appliance.networking.interfaces').list() + foreach ($interface in $interfaces) { + $ipv4API = (Get-CisService -Name 'com.vmware.appliance.techpreview.networking.ipv4') + $spec = $ipv4API.Help.get.interfaces.CreateExample() + $spec+= $interface.name + $ipv4result = $ipv4API.get($spec) + + $interfaceResult = [pscustomobject] @{ + Inteface = $interface.name; + MAC = $interface.mac; + Status = $interface.status; + Mode = $ipv4result.mode; + IP = $ipv4result.address; + Prefix = $ipv4result.prefix; + Gateway = $ipv4result.default_gateway; + Updateable = $ipv4result.updateable + } + $netResults += $interfaceResult + } + $netResults +} + +Function Get-VAMIDisks { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves VMDK disk number to partition mapping VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return VMDK disk number to OS partition mapping + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIDisks +#> + $storageAPI = Get-CisService -Name 'com.vmware.appliance.system.storage' + $disks = $storageAPI.list() + + foreach ($disk in $disks | sort {[int]$_.disk.toString()}) { + $disk | Select Disk, Partition + } +} + +Function Start-VAMIDiskResize { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function triggers an OS partition resize after adding additional disk capacity + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function triggers OS partition resize operation + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Start-VAMIDiskResize +#> + $storageAPI = Get-CisService -Name 'com.vmware.appliance.system.storage' + Write-Host "Initiated OS partition resize operation ..." + $storageAPI.resize() +} + +Function Get-VAMIStatsList { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves list avialable monitoring metrics in VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return list of available monitoring metrics that can be queried + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIStatsList +#> + $monitoringAPI = Get-CisService -Name 'com.vmware.appliance.monitoring' + $ids = $monitoringAPI.list() | Select id | Sort-Object -Property id + + foreach ($id in $ids) { + $id + } +} + +Function Get-VAMIStorageUsed { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves the individaul OS partition storage utilization + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return individual OS partition storage utilization + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIStorageUsed +#> + $monitoringAPI = Get-CisService 'com.vmware.appliance.monitoring' + $querySpec = $monitoringAPI.help.query.item.CreateExample() + + # List of IDs from Get-VAMIStatsList to query + $querySpec.Names = @( + "storage.used.filesystem.autodeploy", + "storage.used.filesystem.boot", + "storage.used.filesystem.coredump", + "storage.used.filesystem.imagebuilder", + "storage.used.filesystem.invsvc", + "storage.used.filesystem.log", + "storage.used.filesystem.netdump", + "storage.used.filesystem.root", + "storage.used.filesystem.updatemgr", + "storage.used.filesystem.vcdb_core_inventory", + "storage.used.filesystem.vcdb_seat", + "storage.used.filesystem.vcdb_transaction_log", + "storage.totalsize.filesystem.autodeploy", + "storage.totalsize.filesystem.boot", + "storage.totalsize.filesystem.coredump", + "storage.totalsize.filesystem.imagebuilder", + "storage.totalsize.filesystem.invsvc", + "storage.totalsize.filesystem.log", + "storage.totalsize.filesystem.netdump", + "storage.totalsize.filesystem.root", + "storage.totalsize.filesystem.updatemgr", + "storage.totalsize.filesystem.vcdb_core_inventory", + "storage.totalsize.filesystem.vcdb_seat", + "storage.totalsize.filesystem.vcdb_transaction_log" + ) + + # Tuple (Filesystem Name, Used, Total) to store results + $storageStats = @{ + "autodeploy"=@{"name"="/storage/autodeploy";"used"=0;"total"=0}; + "boot"=@{"name"="/boot";"used"=0;"total"=0}; + "coredump"=@{"name"="/storage/core";"used"=0;"total"=0}; + "imagebuilder"=@{"name"="/storage/imagebuilder";"used"=0;"total"=0}; + "invsvc"=@{"name"="/storage/invsvc";"used"=0;"total"=0}; + "log"=@{"name"="/storage/log";"used"=0;"total"=0}; + "netdump"=@{"name"="/storage/netdump";"used"=0;"total"=0}; + "root"=@{"name"="/";"used"=0;"total"=0}; + "updatemgr"=@{"name"="/storage/updatemgr";"used"=0;"total"=0}; + "vcdb_core_inventory"=@{"name"="/storage/db";"used"=0;"total"=0}; + "vcdb_seat"=@{"name"="/storage/seat";"used"=0;"total"=0}; + "vcdb_transaction_log"=@{"name"="/storage/dblog";"used"=0;"total"=0} + } + + $querySpec.interval = "DAY1" + $querySpec.function = "MAX" + $querySpec.start_time = ((get-date).AddDays(-1)) + $querySpec.end_time = (Get-Date) + $queryResults = $monitoringAPI.query($querySpec) | Select * -ExcludeProperty Help + + foreach ($queryResult in $queryResults) { + # Update hash if its used storage results + if($queryResult.name -match "used") { + $key = (($queryResult.name).toString()).split(".")[-1] + $value = [Math]::Round([int]($queryResult.data[1]).toString()/1MB,2) + $storageStats[$key]["used"] = $value + # Update hash if its total storage results + } else { + $key = (($queryResult.name).toString()).split(".")[-1] + $value = [Math]::Round([int]($queryResult.data[1]).toString()/1MB,2) + $storageStats[$key]["total"] = $value + } + } + + $storageResults = @() + foreach ($key in $storageStats.keys | Sort-Object -Property name) { + $statResult = [pscustomobject] @{ + Filesystem = $storageStats[$key].name; + Used = $storageStats[$key].used; + Total = $storageStats[$key].total + } + $storageResults += $statResult + } + $storageResults +} + +Function Get-VAMIService { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves list of services in VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return list of services and their description + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIService + .EXAMPLE + Get-VAMIService -Name rbd +#> + param( + [Parameter( + Mandatory=$false, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true) + ] + [String]$Name + ) + + if($Name -ne "") { + $vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service' + + try { + $serviceStatus = $vMonAPI.get($name,0) + $serviceString = [pscustomobject] @{ + Name = $name; + State = $serviceStatus.state; + Health = ""; + Startup = $serviceStatus.startup_type + } + if($serviceStatus.health -eq $null) { $serviceString.Health = "N/A"} else { $serviceString.Health = $serviceStatus.health } + $serviceString + } catch { + Write-Error $Error[0].exception.Message + } + } else { + $vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service' + $services = $vMonAPI.list_details() + + $serviceResult = @() + foreach ($key in $services.keys | Sort-Object -Property Value) { + $serviceString = [pscustomobject] @{ + Name = $key; + State = $services[$key].state; + Health = "N/A"; + Startup = $services[$key].Startup_type + } + if($services[$key].health -eq $null) { $serviceString.Health = "N/A"} else { $serviceString.Health = $services[$key].health } + + $serviceResult += $serviceString + } + $serviceResult + } +} + +Function Start-VAMIService { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves list of services in VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return list of services and their description + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Start-VAMIService -Name rbd +#> + param( + [Parameter( + Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true) + ] + [String]$Name + ) + + $vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service' + + try { + Write-Host "Starting $name service ..." + $vMonAPI.start($name) + } catch { + Write-Error $Error[0].exception.Message + } +} + +Function Stop-VAMIService { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves list of services in VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return list of services and their description + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Stop-VAMIService -Name rbd +#> + param( + [Parameter( + Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true) + ] + [String]$Name + ) + + $vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service' + + try { + Write-Host "Stopping $name service ..." + $vMonAPI.stop($name) + } catch { + Write-Error $Error[0].exception.Message + } +} + +Function Get-VAMIBackupSize { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves the backup size of the VCSA from VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to return the current backup size of the VCSA (common and core data) + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIBackupSize +#> + $recoveryAPI = Get-CisService 'com.vmware.appliance.recovery.backup.parts' + $backupParts = $recoveryAPI.list() | select id + + $estimateBackupSize = 0 + $backupPartSizes = "" + foreach ($backupPart in $backupParts) { + $partId = $backupPart.id.value + $partSize = $recoveryAPI.get($partId) + $estimateBackupSize += $partSize + $backupPartSizes += $partId + " data is " + $partSize + " MB`n" + } + + Write-Host "Estimated Backup Size: $estimateBackupSize MB" + Write-Host $backupPartSizes +} + +Function Get-VAMIUser { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function retrieves VAMI local users using VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to retrieve VAMI local users + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIUser +#> + param( + [Parameter( + Mandatory=$false, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true) + ] + [String]$Name + ) + + $userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user' + + $userResults = @() + + if($Name -ne "") { + try { + $user = $userAPI.get($name) + + $userString = [pscustomobject] @{ + User = $user.username + Name = $user.fullname + Email = $user.email + Status = $user.status + PasswordStatus = $user.passwordstatus + Role = $user.role + } + $userResults += $userString + } catch { + Write-Error $Error[0].exception.Message + } + } else { + $users = $userAPI.list() + + foreach ($user in $users) { + $userString = [pscustomobject] @{ + User = $user.username + Name = $user.fullname + Email = $user.email + Status = $user.status + PasswordStatus = $user.passwordstatus + Role = $user.role + } + $userResults += $userString + } + } + $userResults +} + +Function New-VAMIUser { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function to create new VAMI local user using VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to create a new VAMI local user + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + New-VAMIUser -name lamw -fullname "William Lam" -role "operator" -email "lamw@virtuallyghetto.com" -password "VMware1!" +#> + param( + [Parameter( + Mandatory=$true) + ] + [String]$name, + [Parameter( + Mandatory=$true) + ] + [String]$fullname, + [Parameter( + Mandatory=$true) + ] + [ValidateSet("admin","operator","superAdmin")][String]$role, + [Parameter( + Mandatory=$false) + ] + [String]$email="", + [Parameter( + Mandatory=$true) + ] + [String]$password + ) + + $userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user' + $createSpec = $userAPI.Help.add.config.CreateExample() + + $createSpec.username = $name + $createSpec.fullname = $fullname + $createSpec.role = $role + $createSpec.email = $email + $createSpec.password = [VMware.VimAutomation.Cis.Core.Types.V1.Secret]$password + + try { + Write-Host "Creating new user $name ..." + $userAPI.add($createSpec) + } catch { + Write-Error $Error[0].exception.Message + } +} + +Function Remove-VAMIUser { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .SYNOPSIS + This function to remove VAMI local user using VAMI interface (5480) + for a VCSA node which can be an Embedded VCSA, External PSC or External VCSA. + .DESCRIPTION + Function to remove VAMI local user + .EXAMPLE + Connect-CisServer -Server 192.168.1.51 -User administrator@vsphere.local -Password VMware1! + Get-VAMIAccess +#> + param( + [Parameter( + Mandatory=$true) + ] + [String]$name, + [Parameter( + Mandatory=$false) + ] + [boolean]$confirm=$false + ) + + if(!$confirm) { + $answer = Read-Host -Prompt "Do you want to delete user $name (Y or N)" + if($answer -eq "Y" -or $answer -eq "y") { + $userAPI = Get-CisService 'com.vmware.appliance.techpreview.localaccounts.user' + + try { + Write-Host "Deleting user $name ..." + $userAPI.delete($name) + } catch { + Write-Error $Error[0].exception.Message + } + } + } +} \ No newline at end of file diff --git a/Modules/VCHA/VCHA.psm1 b/Modules/VCHA/VCHA.psm1 new file mode 100644 index 0000000..160f0e7 --- /dev/null +++ b/Modules/VCHA/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/VMCPFunctions.psm1 b/Modules/VMCPFunctions/VMCPFunctions.psm1 similarity index 100% rename from Modules/VMCPFunctions.psm1 rename to Modules/VMCPFunctions/VMCPFunctions.psm1 diff --git a/Modules/VMware.Hv.Helper/Json/Farm/AutomatedInstantCloneFarm.json b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedInstantCloneFarm.json new file mode 100644 index 0000000..605e6a5 --- /dev/null +++ b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedInstantCloneFarm.json @@ -0,0 +1,98 @@ +{ + "Type": "AUTOMATED", + "Data": { + "Name": "ICFarmJson", + "DisplayName": "FarmJsonTest", + "AccessGroup": "Root", + "Description": "created IC Farm from PS via JSON", + "Enabled": null, + "Deleting": false, + "Settings": { + "DisconnectedSessionTimeoutPolicy" : "NEVER", + "DisconnectedSessionTimeoutMinutes" : 1, + "EmptySessionTimeoutPolicy" : "AFTER", + "EmptySessionTimeoutMinutes" : 1, + "LogoffAfterTimeout" : false + }, + "Desktop": null, + "DisplayProtocolSettings": { + "DefaultDisplayProtocol" : "PCOIP", + "AllowDisplayProtocolOverride" : false, + "EnableHTMLAccess" : false + }, + "ServerErrorThreshold": null, + "MirageConfigurationOverrides": { + "OverrideGlobalSetting" : false, + "Enabled" : false, + "Url" : null + } + }, + "AutomatedFarmSpec": { + "ProvisioningType": "INSTANT_CLONE_ENGINE", + "VirtualCenter": null, + "RdsServerNamingSpec": { + "NamingMethod": "PATTERN", + "PatternNamingSettings": { + "NamingPattern": "ICFarmVMPS", + "MaxNumberOfRDSServers": 1 + } + }, + "VirtualCenterProvisioningSettings": { + "EnableProvisioning": true, + "StopProvisioningOnError": true, + "MinReadyVMsOnVComposerMaintenance": 0, + "VirtualCenterProvisioningData": { + "ParentVm": "vm-rdsh-ic", + "Snapshot": "snap_5", + "Datacenter": null, + "VmFolder": "Instant_Clone_VMs", + "HostOrCluster": "vimal-cluster", + "ResourcePool": "vimal-cluster" + }, + "VirtualCenterStorageSettings": { + "Datastores": [ + { + "Datastore": "Datastore1", + "StorageOvercommit": "UNBOUNDED" + } + ], + "UseVSan": false, + "ViewComposerStorageSettings": { + "UseSeparateDatastoresReplicaAndOSDisks": false, + "ReplicaDiskDatastore": null, + "UseNativeSnapshots": false, + "SpaceReclamationSettings": { + "ReclaimVmDiskSpace": false, + "ReclamationThresholdGB": null, + "BlackoutTimes": null + } + } + }, + "VirtualCenterNetworkingSettings": { + "Nics": null + } + }, + "VirtualCenterManagedCommonSettings": { + "TransparentPageSharingScope": "VM" + }, + "CustomizationSettings": { + "CustomizationType": "CLONE_PREP", + "DomainAdministrator": null, + "AdContainer": "CN=Computers", + "ReusePreExistingAccounts": false, + "ClonePrepCustomizationSettings": { + "InstantCloneEngineDomainAdministrator": null, + "PowerOffScriptName": null, + "PowerOffScriptParameters": null, + "PostSynchronizationScriptName": null, + "PostSynchronizationScriptParameters": null + } + }, + "RdsServerMaxSessionsData": { + "MaxSessionsType": "UNLIMITED", + "MaxSessions": null + } + }, + "ManualFarmSpec": null, + "NetBiosName" : "ad-vimalg" +} diff --git a/Modules/VMware.Hv.Helper/New-HVFarm/AutomatedLinkedCloneFarm.json b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm.json similarity index 84% rename from Modules/VMware.Hv.Helper/New-HVFarm/AutomatedLinkedCloneFarm.json rename to Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm.json index 3706374..32c3f9a 100644 --- a/Modules/VMware.Hv.Helper/New-HVFarm/AutomatedLinkedCloneFarm.json +++ b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm.json @@ -1,17 +1,31 @@ { "Type": "AUTOMATED", "Data": { - "Name": "LCFarmTest", - "DisplayName": "Ankit LC Farm Test", + "Name": "LCFarmJson", + "DisplayName": "FarmJsonTest", "AccessGroup": "Root", - "Description": "created LC Farm from PS", + "Description": "created LC Farm from PS via JSON", "Enabled": null, "Deleting": false, - "Settings": null, + "Settings": { + "DisconnectedSessionTimeoutPolicy" : "NEVER", + "DisconnectedSessionTimeoutMinutes" : 1, + "EmptySessionTimeoutPolicy" : "AFTER", + "EmptySessionTimeoutMinutes" : 1, + "LogoffAfterTimeout" : false + }, "Desktop": null, - "DisplayProtocolSettings": null, + "DisplayProtocolSettings": { + "DefaultDisplayProtocol" : "PCOIP", + "AllowDisplayProtocolOverride" : false, + "EnableHTMLAccess" : false + }, "ServerErrorThreshold": null, - "MirageConfigurationOverrides": null + "MirageConfigurationOverrides": { + "OverrideGlobalSetting" : false, + "Enabled" : false, + "Url" : null + } }, "AutomatedFarmSpec": { "ProvisioningType": "VIEW_COMPOSER", @@ -19,7 +33,7 @@ "RdsServerNamingSpec": { "NamingMethod": "PATTERN", "PatternNamingSettings": { - "NamingPattern": "LCFarmVM_PS", + "NamingPattern": "LCFarmVMPS", "MaxNumberOfRDSServers": 1 } }, @@ -28,17 +42,17 @@ "StopProvisioningOnError": true, "MinReadyVMsOnVComposerMaintenance": 0, "VirtualCenterProvisioningData": { - "ParentVm": "Win_Server_2012_R2", - "Snapshot": "Snap_RDS", + "ParentVm": "RDSServer", + "Snapshot": "RDS_SNAP1", "Datacenter": null, - "VmFolder": "AnkitPoolVM", - "HostOrCluster": "cls", - "ResourcePool": "cls" + "VmFolder": "Praveen", + "HostOrCluster": "CS-1", + "ResourcePool": "CS-1" }, "VirtualCenterStorageSettings": { "Datastores": [ { - "Datastore": "datastore1 (5)", + "Datastore": "Datastore1", "StorageOvercommit": "UNBOUNDED" } ], @@ -67,7 +81,7 @@ "AdContainer": "CN=Computers", "ReusePreExistingAccounts": false, "SysprepCustomizationSettings": { - "CustomizationSpec": "RDSH_Cust2" + "CustomizationSpec": "PraveenCust" } }, "RdsServerMaxSessionsData": { @@ -76,5 +90,5 @@ } }, "ManualFarmSpec": null, - "NetBiosName" : "adankit" + "NetBiosName" : "adviewdev" } diff --git a/Modules/VMware.Hv.Helper/New-HVFarm/ManualFarm.json b/Modules/VMware.Hv.Helper/Json/Farm/ManualFarm.json similarity index 51% rename from Modules/VMware.Hv.Helper/New-HVFarm/ManualFarm.json rename to Modules/VMware.Hv.Helper/Json/Farm/ManualFarm.json index cf674c1..3dd1678 100644 --- a/Modules/VMware.Hv.Helper/New-HVFarm/ManualFarm.json +++ b/Modules/VMware.Hv.Helper/Json/Farm/ManualFarm.json @@ -7,17 +7,31 @@ "Description": "Manual PS Test", "Enabled": null, "Deleting": false, - "Settings": null, + "Settings": { + "DisconnectedSessionTimeoutPolicy" : "NEVER", + "DisconnectedSessionTimeoutMinutes" : 1, + "EmptySessionTimeoutPolicy" : "AFTER", + "EmptySessionTimeoutMinutes" : 1, + "LogoffAfterTimeout" : false + }, "Desktop": null, - "DisplayProtocolSettings": null, + "DisplayProtocolSettings": { + "DefaultDisplayProtocol" : "PCOIP", + "AllowDisplayProtocolOverride" : false, + "EnableHTMLAccess" : false + }, "ServerErrorThreshold": null, - "MirageConfigurationOverrides": null + "MirageConfigurationOverrides": { + "OverrideGlobalSetting" : false, + "Enabled" : false, + "Url" : null + } }, "AutomatedFarmSpec": null, "ManualFarmSpec": { "RdsServers": [ { - "rdsServer": "WIN-ORKA1Q8B0P7" + "rdsServer": "RDSServer.adviewdev.eng.vmware.com" } ] } diff --git a/Modules/VMware.Hv.Helper/New-HVPool/FullClone.json b/Modules/VMware.Hv.Helper/Json/Pool/FullClone.json similarity index 82% rename from Modules/VMware.Hv.Helper/New-HVPool/FullClone.json rename to Modules/VMware.Hv.Helper/Json/Pool/FullClone.json index 2ae9539..e6d7fae 100644 --- a/Modules/VMware.Hv.Helper/New-HVPool/FullClone.json +++ b/Modules/VMware.Hv.Helper/Json/Pool/FullClone.json @@ -5,7 +5,44 @@ "AccessGroup": "Root", "Description": "create full clone via JSON" }, - "DesktopSettings": null, + "DesktopSettings": { + "enabled": true, + "deleting": false, + "connectionServerRestrictions": null, + "logoffSettings": { + "powerPolicy": "TAKE_NO_POWER_ACTION", + "automaticLogoffPolicy": "NEVER", + "automaticLogoffMinutes": 120, + "allowUsersToResetMachines": false, + "allowMultipleSessionsPerUser": false, + "deleteOrRefreshMachineAfterLogoff": "NEVER", + "refreshOsDiskAfterLogoff": "NEVER", + "refreshPeriodDaysForReplicaOsDisk": 5, + "refreshThresholdPercentageForReplicaOsDisk": 10 + }, + "displayProtocolSettings": { + "supportedDisplayProtocols": ["PCOIP", "BLAST" ], + "defaultDisplayProtocol": "BLAST", + "allowUsersToChooseProtocol": true, + "pcoipDisplaySettings": { + "renderer3D": "DISABLED", + "enableGRIDvGPUs": false, + "vRamSizeMB": 96, + "maxNumberOfMonitors": 3, + "maxResolutionOfAnyOneMonitor": "WSXGA_PLUS" + }, + "enableHTMLAccess": true + }, + "flashSettings": { + "quality": "NO_CONTROL", + "throttling": "DISABLED" + }, + "mirageConfigurationOverrides": { + "overrideGlobalSetting": false, + "enabled": false, + "url": false + } + }, "Type": "AUTOMATED", "AutomatedDesktopSpec": { "ProvisioningType": "VIRTUAL_CENTER", @@ -69,7 +106,7 @@ "NoCustomizationSettings": { "DoNotPowerOnVMsAfterCreation": false }, - "SysprepCustomizationSettings": null, + "SysprepCustomizationSettings": {"customizationSpec" : "praveencust"}, "QuickprepCustomizationSettings": null, "CloneprepCustomizationSettings": null } @@ -77,6 +114,5 @@ "ManualDesktopSpec": null, "RdsDesktopSpec": null, "GlobalEntitlementData": null, - "NetBiosName" : "adviewdev", - "SysPrepName" : "praveencust" + "NetBiosName" : "adviewdev" } diff --git a/Modules/VMware.Hv.Helper/New-HVPool/InstantClone.json b/Modules/VMware.Hv.Helper/Json/Pool/InstantClone.json similarity index 88% rename from Modules/VMware.Hv.Helper/New-HVPool/InstantClone.json rename to Modules/VMware.Hv.Helper/Json/Pool/InstantClone.json index a8da482..4c3c584 100644 --- a/Modules/VMware.Hv.Helper/New-HVPool/InstantClone.json +++ b/Modules/VMware.Hv.Helper/Json/Pool/InstantClone.json @@ -5,7 +5,44 @@ "AccessGroup": "ROOT", "Description": "create instant pool" }, - "DesktopSettings": null, + "DesktopSettings": { + "enabled": true, + "deleting": false, + "connectionServerRestrictions": null, + "logoffSettings": { + "powerPolicy": "ALWAYS_POWERED_ON", + "automaticLogoffPolicy": "NEVER", + "automaticLogoffMinutes": 120, + "allowUsersToResetMachines": false, + "allowMultipleSessionsPerUser": false, + "deleteOrRefreshMachineAfterLogoff": "DELETE", + "refreshOsDiskAfterLogoff": "NEVER", + "refreshPeriodDaysForReplicaOsDisk": 5, + "refreshThresholdPercentageForReplicaOsDisk": 10 + }, + "displayProtocolSettings": { + "supportedDisplayProtocols": ["PCOIP", "BLAST" ], + "defaultDisplayProtocol": "BLAST", + "allowUsersToChooseProtocol": true, + "pcoipDisplaySettings": { + "renderer3D": "DISABLED", + "enableGRIDvGPUs": false, + "vRamSizeMB": 96, + "maxNumberOfMonitors": 3, + "maxResolutionOfAnyOneMonitor": "WSXGA_PLUS" + }, + "enableHTMLAccess": true + }, + "flashSettings": { + "quality": "NO_CONTROL", + "throttling": "DISABLED" + }, + "mirageConfigurationOverrides": { + "overrideGlobalSetting": false, + "enabled": false, + "url": false + } + }, "Type": "AUTOMATED", "AutomatedDesktopSpec": { "ProvisioningType": "INSTANT_CLONE_ENGINE", diff --git a/Modules/VMware.Hv.Helper/New-HVPool/LinkedClone.json b/Modules/VMware.Hv.Helper/Json/Pool/LinkedClone.json similarity index 80% rename from Modules/VMware.Hv.Helper/New-HVPool/LinkedClone.json rename to Modules/VMware.Hv.Helper/Json/Pool/LinkedClone.json index 53171a6..ee3dfac 100644 --- a/Modules/VMware.Hv.Helper/New-HVPool/LinkedClone.json +++ b/Modules/VMware.Hv.Helper/Json/Pool/LinkedClone.json @@ -5,7 +5,44 @@ "AccessGroup": "Root", "Description": "created linkedclone pool from ps" }, - "DesktopSettings": null, + "DesktopSettings": { + "enabled": true, + "deleting": false, + "connectionServerRestrictions": null, + "logoffSettings": { + "powerPolicy": "TAKE_NO_POWER_ACTION", + "automaticLogoffPolicy": "NEVER", + "automaticLogoffMinutes": 120, + "allowUsersToResetMachines": false, + "allowMultipleSessionsPerUser": false, + "deleteOrRefreshMachineAfterLogoff": "NEVER", + "refreshOsDiskAfterLogoff": "NEVER", + "refreshPeriodDaysForReplicaOsDisk": 5, + "refreshThresholdPercentageForReplicaOsDisk": 10 + }, + "displayProtocolSettings": { + "supportedDisplayProtocols": ["RDP","PCOIP", "BLAST" ], + "defaultDisplayProtocol": "PCOIP", + "allowUsersToChooseProtocol": true, + "pcoipDisplaySettings": { + "renderer3D": "DISABLED", + "enableGRIDvGPUs": false, + "vRamSizeMB": 96, + "maxNumberOfMonitors": 3, + "maxResolutionOfAnyOneMonitor": "WSXGA_PLUS" + }, + "enableHTMLAccess": true + }, + "flashSettings": { + "quality": "NO_CONTROL", + "throttling": "DISABLED" + }, + "mirageConfigurationOverrides": { + "overrideGlobalSetting": false, + "enabled": false, + "url": null + } + }, "Type": "AUTOMATED", "AutomatedDesktopSpec": { "ProvisioningType": "VIEW_COMPOSER", @@ -33,7 +70,7 @@ "Template": null, "ParentVm": "Agent_pra", "Snapshot": "kb-hotfix", - "Datacenter": null, + "Datacenter": "Dev-Dc", "VmFolder": "Praveen", "HostOrCluster": "CS-1", "ResourcePool": "CS-1" @@ -52,7 +89,8 @@ "UseNativeSnapshots": false, "SpaceReclamationSettings": { "ReclaimVmDiskSpace": false, - "ReclamationThresholdGB": null + "ReclamationThresholdGB": null, + "BlackoutTimes" : null }, "PersistentDiskSettings": { "RedirectWindowsProfile": false, @@ -75,19 +113,31 @@ } }, "VirtualCenterNetworkingSettings": { - "Nics": null + "Nics": [ + { + "Nic": "nicName", + "NetworkLabelAssignmentSpecs": [ + { + "Enabled" : false, + "networkLabel" : null, + "maxLabelType" : null, + "maxLabel" : null + } + ] + } + ] } }, "VirtualCenterManagedCommonSettings": { "TransparentPageSharingScope": "VM" }, "CustomizationSettings": { - "CustomizationType": "QUICK_PREP", - "DomainAdministrator": null, + "CustomizationType": "SYS_PREP", + "DomainAdministrator": "administrator", "AdContainer": "CN=Computers", "ReusePreExistingAccounts": false, "NoCustomizationSettings": null, - "SysprepCustomizationSettings": null, + "SysprepCustomizationSettings": {"customizationSpec" : "praveencust"}, "QuickprepCustomizationSettings": { "PowerOffScriptName": null, "PowerOffScriptParameters": null, @@ -99,7 +149,6 @@ }, "ManualDesktopSpec": null, "RdsDesktopSpec": null, - "GlobalEntitlementData": null, - "NetBiosName" : "adviewdev", - "SysPrepName" : "praveencust" + "GlobalEntitlementData": null, + "NetBiosName" : "adviewdev" } diff --git a/Modules/VMware.Hv.Helper/New-HVPool/ManualSpec.json b/Modules/VMware.Hv.Helper/Json/Pool/ManualSpec.json similarity index 54% rename from Modules/VMware.Hv.Helper/New-HVPool/ManualSpec.json rename to Modules/VMware.Hv.Helper/Json/Pool/ManualSpec.json index b302bba..8b95389 100644 --- a/Modules/VMware.Hv.Helper/New-HVPool/ManualSpec.json +++ b/Modules/VMware.Hv.Helper/Json/Pool/ManualSpec.json @@ -5,7 +5,44 @@ "AccessGroup": "ROOT", "Description": "Manual pool creation" }, - "DesktopSettings": null, + "DesktopSettings": { + "enabled": true, + "deleting": false, + "connectionServerRestrictions": null, + "logoffSettings": { + "powerPolicy": "TAKE_NO_POWER_ACTION", + "automaticLogoffPolicy": "NEVER", + "automaticLogoffMinutes": 120, + "allowUsersToResetMachines": false, + "allowMultipleSessionsPerUser": false, + "deleteOrRefreshMachineAfterLogoff": "NEVER", + "refreshOsDiskAfterLogoff": "NEVER", + "refreshPeriodDaysForReplicaOsDisk": 5, + "refreshThresholdPercentageForReplicaOsDisk": 10 + }, + "displayProtocolSettings": { + "supportedDisplayProtocols": ["PCOIP", "BLAST" ], + "defaultDisplayProtocol": "BLAST", + "allowUsersToChooseProtocol": true, + "pcoipDisplaySettings": { + "renderer3D": "DISABLED", + "enableGRIDvGPUs": false, + "vRamSizeMB": 96, + "maxNumberOfMonitors": 3, + "maxResolutionOfAnyOneMonitor": "WSXGA_PLUS" + }, + "enableHTMLAccess": true + }, + "flashSettings": { + "quality": "NO_CONTROL", + "throttling": "DISABLED" + }, + "mirageConfigurationOverrides": { + "overrideGlobalSetting": false, + "enabled": false, + "url": false + } + }, "Type": "MANUAL", "AutomatedDesktopSpec": null, "ManualDesktopSpec": { @@ -16,7 +53,7 @@ "Source": "VIRTUAL_CENTER", "Machines": [ { - "Machine" : "PowerCLI-VM" + "Machine" : "Praveen_Agent" } ], "VirtualCenter": null, @@ -32,4 +69,5 @@ }, "RdsDesktopSpec": null, "GlobalEntitlementData": null + } diff --git a/Modules/VMware.Hv.Helper/Json/Pool/RdsSpec.json b/Modules/VMware.Hv.Helper/Json/Pool/RdsSpec.json new file mode 100644 index 0000000..bab0c67 --- /dev/null +++ b/Modules/VMware.Hv.Helper/Json/Pool/RdsSpec.json @@ -0,0 +1,27 @@ +{ + "Base": { + "Name" : "RdsJson", + "DisplayName": "TestRDSPS", + "AccessGroup": "Root", + "Description": "Testing PS" + }, + "DesktopSettings": { + "enabled": true, + "deleting": false, + "connectionServerRestrictions": null, + "logoffSettings": null, + "displayProtocolSettings": null, + "flashSettings": { + "quality": "NO_CONTROL", + "throttling": "DISABLED" + }, + "mirageConfigurationOverrides": null + }, + "Type": "RDS", + "AutomatedDesktopSpec": null, + "ManualDesktopSpec": null, + "RdsDesktopSpec": { + "Farm": "test1" + }, + "GlobalEntitlementData": null +} diff --git a/Modules/VMware.Hv.Helper/New-HVPool/RdsSpec.json b/Modules/VMware.Hv.Helper/New-HVPool/RdsSpec.json deleted file mode 100644 index 86b3571..0000000 --- a/Modules/VMware.Hv.Helper/New-HVPool/RdsSpec.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Base": { - "Name" : "RdsJson", - "DisplayName": "TestRDSPS", - "AccessGroup": "Root", - "Description": "Testing PS" - }, - "DesktopSettings": null, - "Type": "RDS", - "AutomatedDesktopSpec": null, - "ManualDesktopSpec": null, - "RdsDesktopSpec": { - "Farm": "Farm2" - }, - "GlobalEntitlementData": null -} diff --git a/Modules/VMware.Hv.Helper/README.md b/Modules/VMware.Hv.Helper/README.md new file mode 100644 index 0000000..fe87153 --- /dev/null +++ b/Modules/VMware.Hv.Helper/README.md @@ -0,0 +1,20 @@ +Prerequisites/Steps to use this module: + +1. This module only works for Horizon product E.g. Horizon 7.0.2 and later. +2. Install the latest version of Powershell, PowerCLI(6.5) or (later version via psgallery). +3. Import HorizonView module by running: Import-Module VMware.VimAutomation.HorizonView. +4. Import "VMware.Hv.Helper" module by running: Import-Module -Name "location of this module" or Get-Module -ListAvailable 'VMware.Hv.Helper' | Import-Module. +5. Get-Command -Module "This module Name" to list all available functions or Get-Command -Module 'VMware.Hv.Helper'. + +# Example script to connect view API service of Connection Server: + +Import-Module VMware.VimAutomation.HorizonView +# Connection to view API service +$hvServer = Connect-HVServer -server +$hvServices = $hvserver.ExtensionData +$csList = $hvServices.ConnectionServer.ConnectionServer_List() +# Load this module +Get-Module -ListAvailable 'VMware.Hv.Helper' | Import-Module +Get-Command -Module 'VMware.Hv.Helper' +# Use advanced functions of this module +New-HVPool -spec 'path to InstantClone.json file' diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.format.ps1xml b/Modules/VMware.Hv.Helper/VMware.HV.Helper.format.ps1xml index dc4cca4..7f8a6aa 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.format.ps1xml +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.format.ps1xml @@ -30,6 +30,10 @@ 8 + + + + 7 @@ -56,10 +60,23 @@ $_.desktopSummaryData.userAssignment - + + + $filterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id) + $GlobalfilterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id) + Try { + $results += Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $filterContains + $results += Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $GlobalfilterContains + } Catch { + #Do nothing + } + $results.length + + + $_.desktopSummaryData.enabled - + $_.desktopSummaryData.numSessions @@ -97,6 +114,20 @@ $_.desktopSummaryData.userAssignment + + + $filterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id) + $GlobalfilterContains = Get-HVQueryFilter localData.desktops -contains ([VMware.Hv.DesktopId[]]$_.id) + Try { + $results += Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $filterContains + $results += Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $GlobalfilterContains + } Catch { + #Do nothing + } + $results.length + + + $_.desktopSummaryData.enabled @@ -117,27 +148,27 @@ - 16 + 15 - 16 + 12 - 16 + 12 - 16 + 8 - 16 + 15 - 8 + 5 @@ -145,9 +176,8 @@ - 10 + 15 - Right @@ -169,13 +199,13 @@ $_.ManagedMachineNamesData.HostName - $_.Data.AgentVersion + $_.Base.AgentVersion $_.ManagedMachineNamesData.DatastorePaths - $_.Data.BasicState + $_.Base.BasicState @@ -212,12 +242,16 @@ $_.ManagedMachineNamesData.HostName - + + $_.Base.AgentVersion + + + $_.ManagedMachineNamesData.DatastorePaths - - $_.Data.BasicState + + $_.Base.BasicState diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 index 705cc80..42dc6aa 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 @@ -12,7 +12,7 @@ # RootModule = '' # Version number of this module. -ModuleVersion = '1.0' +ModuleVersion = '1.1' # ID used to uniquely identify this module GUID = '6d3f7fb5-4e52-43d8-91e1-f65f72532a1d' diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 6884703..aa7697f 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -1,7 +1,7 @@ #Script Module : VMware.Hv.Helper -#Version : 1.0 +#Version : 1.1 -#Copyright 2016 VMware, Inc. All Rights Reserved. +#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 @@ -48,14 +48,23 @@ function Get-ViewAPIService { return $hvServer.ExtensionData } } elseif ($global:DefaultHVServers.Length -gt 0) { - if ($pscmdlet.ShouldProcess($global:DefaultHVServers[0].uid,'hvServer not specified, use default hvServer connection?')) { - $hvServer = $global:DefaultHVServers[0] - return $hvServer.ExtensionData - } + $hvServer = $global:DefaultHVServers[0] + return $hvServer.ExtensionData } return $null } +function Get-HVConfirmFlag { + Param( + [Parameter(Mandatory = $true)] + $keys + ) + if (($keys -contains 'Confirm') -or ($keys -contains 'WhatIf')) { + return $true + } + return $false +} + function Get-VcenterID { param( [Parameter(Mandatory = $true)] @@ -177,30 +186,30 @@ The Add-HVDesktop adds virtual machines to already exiting pools by using view A View API service object of Connect-HVServer cmdlet. .EXAMPLE + Add-HVDesktop -PoolName 'ManualPool' -Machines 'manualPool1', 'manualPool2' -Confirm:$false Add managed manual VMs to existing manual pool - Add-HVDesktop -PoolName 'ManualPool' -Machines 'manualPool1', 'manualPool2'. .EXAMPLE - Add virtual machines to automated specific named dedicated pool Add-HVDesktop -PoolName 'SpecificNamed' -Machines 'vm-01', 'vm-02' -Users 'user1', 'user2' + Add virtual machines to automated specific named dedicated pool .EXAMPLE - Add machines to automated specific named Floating pool Add-HVDesktop -PoolName 'SpecificNamed' -Machines 'vm-03', 'vm-04' + Add machines to automated specific named Floating pool .EXAMPLE - Add machines to unmanged manual pool Add-HVDesktop -PoolName 'Unmanaged' -Machines 'desktop-1.eng.vmware.com' + Add machines to unmanged manual pool .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 Dependencies : Make sure pool already exists before adding VMs to it. ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -239,10 +248,11 @@ The Add-HVDesktop adds virtual machines to already exiting pools by using view A } process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys try { $desktopPool = Get-HVPoolSummary -poolName $poolName -hvServer $hvServer } catch { - Write-Error "Make sure Get-HVPool advanced function is loaded, $_" + Write-Error "Make sure Get-HVPoolSummary advanced function is loaded, $_" break } if ($desktopPool) { @@ -296,7 +306,10 @@ The Add-HVDesktop adds virtual machines to already exiting pools by using view A return } } - $desktop_service_helper.Desktop_AddMachinesToManualDesktop($services,$id,$machineList) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($machines)) { + $desktop_service_helper.Desktop_AddMachinesToManualDesktop($services,$id,$machineList) + } + return $machineList } default { Write-Error "Only Automated/Manual pool types support this add operation" @@ -347,6 +360,7 @@ function Get-MachinesByVCenter ($MachineList,$VcId) { } return $machines } + function Add-HVRDSServer { <# .SYNOPSIS @@ -365,21 +379,21 @@ function Add-HVRDSServer { View API service object of Connect-HVServer cmdlet. .EXAMPLE + Add-HVRDSServer -Farm "manualFarmTest" -RdsServers "vm-for-rds","vm-for-rds-2" -Confirm:$false Add RDSServers to manual farm - Add-HVRDSServer -Farm "manualFarmTest" -RdsServers "vm-for-rds","vm-for-rds-2" .OUTPUTS None .NOTES - Author : Ankit Gupta. - Author email : guptaa@vmware.com - Version : 1.0 + Author : praveen mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 Dependencies : Make sure farm already exists before adding RDSServers to it. ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> [CmdletBinding( @@ -407,10 +421,11 @@ function Add-HVRDSServer { } process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys try { - $farmSpecObj = Get-HVFarmSummary -farmName $farmName -hvServer $hvServer + $farmSpecObj = Get-HVFarmSummary -farmName $farmName -hvServer $hvServer -suppressInfo $true } catch { - Write-Error "Make sure Get-HVFarm advanced function is loaded, $_" + Write-Error "Make sure Get-HVFarmSummary advanced function is loaded, $_" break } if ($farmSpecObj) { @@ -430,7 +445,10 @@ function Add-HVRDSServer { 'MANUAL' { try { $serverList = Get-RegisteredRDSServer -services $services -serverList $rdsServers - $farm_service_helper.Farm_AddRDSServers($services, $id, $serverList) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($rdsServers)) { + $farm_service_helper.Farm_AddRDSServers($services, $id, $serverList) + } + return $serverList } catch { Write-Error "Failed to Add RDS Server to Farm with error: $_" break @@ -443,7 +461,8 @@ function Add-HVRDSServer { [System.gc]::collect() } } -[System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient") | Out-Null + + function Connect-HVEvent { <# @@ -464,21 +483,21 @@ function Connect-HVEvent { Password corresponds to 'dbUserName' user. .EXAMPLE - Connecting to the database with default username configured on Connection Server $hvServer. Connect-HVEvent -HvServer $hvServer + Connecting to the database with default username configured on Connection Server $hvServer. .EXAMPLE - Connecting to the database configured on Connection Server $hvServer with customised user name 'system'. $hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' + Connecting to the database configured on Connection Server $hvServer with customised user name 'system'. .EXAMPLE - Connecting to the database with customised user name and password. $hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' -DbPassword 'censored' + Connecting to the database with customised user name and password. .EXAMPLE + C:\PS>$password = Read-Host 'Database Password' -AsSecureString + C:\PS>$hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' -DbPassword $password Connecting to the database with customised user name and password, with password being a SecureString. - $password = Read-Host 'Database Password' -AsSecureString - $hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' -DbPassword $password .OUTPUTS Returns a custom object that has database connection as 'dbConnection' property. @@ -486,11 +505,11 @@ function Connect-HVEvent { .NOTES Author : Paramesh Oddepally. Author email : poddepally@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> [CmdletBinding()] @@ -506,6 +525,7 @@ function Connect-HVEvent { ) begin { + [System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient") | Out-Null # Connect to Connection Server and call the View API service $services = Get-ViewAPIService -hvServer $hvServer if ($null -eq $services) { @@ -594,8 +614,8 @@ function Disconnect-HVEvent { Connection object returned by Connect-HVEvent advanced function. This is a mandatory input. .EXAMPLE - Disconnecting the database connection on $hvDbServer. Disconnect-HVEvent -HvDbServer $hvDbServer + Disconnecting the database connection on $hvDbServer. .OUTPUTS None @@ -603,11 +623,11 @@ function Disconnect-HVEvent { .NOTES Author : Paramesh Oddepally. Author email : poddepally@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -684,15 +704,15 @@ function Get-HVEvent { String that can applied in filtering on 'Message' column. .EXAMPLE + C:\PS>$e = Get-HVEvent -hvDbServer $hvDbServer + C:\PS>$e.Events Querying all the database events on database $hvDbServer. - $e = Get-HVEvent -hvDbServer $hvDbServer - $e.Events .EXAMPLE + C:\PS>$e = Get-HVEvent -HvDbServer $hvDbServer -TimePeriod 'all' -FilterType 'startsWith' -UserFilter 'aduser' -SeverityFilter 'err' -TimeFilter 'HH:MM:SS.fff' -ModuleFilter 'broker' -MessageFilter 'aduser' + C:\PS>$e.Events | Export-Csv -Path 'myEvents.csv' -NoTypeInformation Querying all the database events where user name startswith 'aduser', severity is of 'err' type, having module name as 'broker', message starting with 'aduser' and time starting with 'HH:MM:SS.fff'. The resulting events will be exported to a csv file 'myEvents.csv'. - $e = Get-HVEvent -HvDbServer $hvDbServer -TimePeriod 'all' -FilterType 'startsWith' -UserFilter 'aduser' -SeverityFilter 'err' -TimeFilter 'HH:MM:SS.fff' -ModuleFilter 'broker' -MessageFilter 'aduser' - $e.Events | Export-Csv -Path 'myEvents.csv' -NoTypeInformation .OUTPUTS Returns a custom object that has events information in 'Events' property. Events property will have events information with five columns: UserName, Severity, EventTime, Module and Message. @@ -700,11 +720,11 @@ function Get-HVEvent { .NOTES Author : Paramesh Oddepally. Author email : poddepally@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -904,38 +924,43 @@ function Get-HVFarm { .PARAMETER Enabled search for farms which are enabled -.PARAMETER Full - Switch to get list of FarmSummaryView or FarmInfo objects in the result. If it is true a list of FarmInfo objects is returned ohterwise a list of FarmSummaryView objects is returned. +.PARAMETER SuppressInfo + Suppress text info, when no farm found with given search parameters .PARAMETER HvServer - Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered inplace of hvServer. + Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE Get-HVFarm -FarmName 'Farm-01' + Queries and returns farmInfo based on given parameter farmName .EXAMPLE Get-HVFarm -FarmName 'Farm-01' -FarmDisplayName 'Sales RDS Farm' + Queries and returns farmInfo based on given parameters farmName, farmDisplayName .EXAMPLE Get-HVFarm -FarmName 'Farm-01' -FarmType 'MANUAL' + Queries and returns farmInfo based on given parameters farmName, farmType .EXAMPLE Get-HVFarm -FarmName 'Farm-01' -FarmType 'MANUAL' -Enabled $true + Queries and returns farmInfo based on given parameters farmName, FarmType etc .EXAMPLE - Get-HVFarm -FarmName 'Farm-01' + Get-HVFarm -FarmName 'Farm-0*' + Queries and returns farmInfo based on parameter farmName with wild character * .OUTPUTs - Returns the list of FarmSummaryView or FarmInfo object matching the query criteria. + Returns the list of FarmInfo object matching the query criteria. .NOTES - Author : Ankit Gupta. - Author email : guptaa@vmware.com - Version : 1.0 + Author : praveen mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -962,6 +987,10 @@ function Get-HVFarm { [boolean] $Enabled, + [Parameter(Mandatory = $false)] + [boolean] + $SuppressInfo = $false, + [Parameter(Mandatory = $false)] $HvServer = $null ) @@ -972,6 +1001,12 @@ function Get-HVFarm { break } $farmList = Find-HVFarm -Param $PSBoundParameters + if (! $farmList) { + if (! $SuppressInfo) { + Write-Host "Get-HVFarm: No Farm Found with given search parameters" + } + return $farmList + } $farm_service_helper = New-Object VMware.Hv.FarmService $queryResults = @() foreach ($id in $farmList.id) { @@ -991,48 +1026,56 @@ function Get-HVFarmSummary { This function queries the specified Connection Server for farms which are configured on the server. If no farm is configured on the specified connection server or no farm matches the given search criteria, it will return null. .PARAMETER FarmName - farmName to be searched + FarmName to be searched .PARAMETER FarmDisplayName - farmDisplayName to be searched + FarmDisplayName to be searched .PARAMETER FarmType - farmType to be searched. It can take following values: + FarmType to be searched. It can take following values: "AUTOMATED" - search for automated farms only 'MANUAL' - search for manual farms only .PARAMETER Enabled - search for farms which are enabled + Search for farms which are enabled + +.PARAMETER SuppressInfo + Suppress text info, when no farm found with given search parameters .PARAMETER HvServer - Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered inplace of hvServer. + Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE - Get-HVFarm -FarmName 'Farm-01' + Get-HVFarmSummary -FarmName 'Farm-01' + Queries and returns farmSummary objects based on given parameter farmName .EXAMPLE - Get-HVFarm -FarmName 'Farm-01' -FarmDisplayName 'Sales RDS Farm' + Get-HVFarmSummary -FarmName 'Farm-01' -FarmDisplayName 'Sales RDS Farm' + Queries and returns farmSummary objects based on given parameters farmName, farmDisplayName .EXAMPLE - Get-HVFarm -FarmName 'Farm-01' -FarmType 'MANUAL' + Get-HVFarmSummary -FarmName 'Farm-01' -FarmType 'MANUAL' + Queries and returns farmSummary objects based on given parameters farmName, farmType .EXAMPLE - Get-HVFarm -FarmName 'Farm-01' -FarmType 'MANUAL' -Enabled $true + Get-HVFarmSummary -FarmName 'Farm-01' -FarmType 'MANUAL' -Enabled $true + Queries and returns farmSummary objects based on given parameters farmName, FarmType etc .EXAMPLE - Get-HVFarm -FarmName 'Farm-01' + Get-HVFarmSummary -FarmName 'Farm-0*' + Queries and returns farmSummary objects based on given parameter farmName with wild character * .OUTPUTs - Returns the list of FarmSummaryView or FarmInfo object matching the query criteria. + Returns the list of FarmSummary object matching the query criteria. .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -1059,6 +1102,10 @@ function Get-HVFarmSummary { [boolean] $Enabled, + [Parameter(Mandatory = $false)] + [boolean] + $SuppressInfo = $false, + [Parameter(Mandatory = $false)] $HvServer = $null ) @@ -1069,7 +1116,10 @@ function Get-HVFarmSummary { break } $farmList = Find-HVFarm -Param $PSBoundParameters - return $farmList + if (!$farmList -and !$SuppressInfo) { + Write-Host "Get-HVFarmSummary: No Farm Found with given search parameters" + } + Return $farmList } function Find-HVFarm { @@ -1087,32 +1137,56 @@ function Find-HVFarm { 'farmType' = 'data.type'; } - $parms = $Param + $params = $Param $query_service_helper = New-Object VMware.Hv.QueryServiceService $query = New-Object VMware.Hv.QueryDefinition + $wildcard = $false # build the query values + if ($params['FarmName'] -and $params['FarmName'].contains('*')) { + $wildcard = $true + } + if ($params['FarmDisplayName'] -and $params['FarmDisplayName'].contains('*')) { + $wildcard = $true + } $query.queryEntityType = 'FarmSummaryView' - [VMware.Hv.queryfilter[]]$filterSet = @() - foreach ($setting in $farmSelectors.Keys) { - if ($null -ne $parms[$setting]) { - $equalsFilter = New-Object VMware.Hv.QueryFilterEquals - $equalsFilter.memberName = $farmSelectors[$setting] - $equalsFilter.value = $parms[$setting] - $filterSet += $equalsFilter + if (! $wildcard) { + [VMware.Hv.queryfilter[]]$filterSet = @() + foreach ($setting in $farmSelectors.Keys) { + if ($null -ne $params[$setting]) { + $equalsFilter = New-Object VMware.Hv.QueryFilterEquals + $equalsFilter.memberName = $farmSelectors[$setting] + $equalsFilter.value = $params[$setting] + $filterSet += $equalsFilter + } + } + if ($filterSet.Count -gt 0) { + $queryList = New-Object VMware.Hv.QueryFilterAnd + $queryList.Filters = $filterset + $query.Filter = $queryList } - } - if ($filterSet.Count -gt 0) { - $queryList = New-Object VMware.Hv.QueryFilterAnd - $queryList.Filters = $filterset - $query.Filter = $queryList - } - $queryResults = $query_service_helper.QueryService_Query($services, $query) - $farmList = $queryResults.results - + $queryResults = $query_service_helper.QueryService_Query($services, $query) + $farmList = $queryResults.results + } elseif ($wildcard -or [string]::IsNullOrEmpty($farmList)){ + $query.Filter = $null + $queryResults = $query_service_helper.QueryService_Query($services,$query) + $strFilterSet = @() + foreach ($setting in $farmSelectors.Keys) { + if ($null -ne $params[$setting]) { + if ($wildcard -and (($setting -eq 'FarmName') -or ($setting -eq 'FarmDisplayName')) ) { + $strFilterSet += '($_.' + $farmSelectors[$setting] + ' -like "' + $params[$setting] + '")' + } else { + $strFilterSet += '($_.' + $farmSelectors[$setting] + ' -eq "' + $params[$setting] + '")' + } + } + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $farmList = $queryResults.results | where $scriptBlock + } Return $farmList } @@ -1156,33 +1230,40 @@ function Get-HVPool { If the value is true then only pools which are enabled would be returned. If the value is false then only pools which are disabled would be returned. +.PARAMETER SuppressInfo + Suppress text info, when no pool found with given search parameters + .PARAMETER HvServer Reference to Horizon View Server to query the pools from. If the value is not passed or null then - first element from global:DefaultHVServers would be considered inplace of hvServer + first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE Get-HVPool -PoolName 'mypool' -PoolType MANUAL -UserAssignment FLOATING -Enabled $true -ProvisioningEnabled $true + Queries and returns pool object(s) based on given parameters poolName, poolType etc. .EXAMPLE Get-HVPool -PoolType AUTOMATED -UserAssignment FLOATING + Queries and returns pool object(s) based on given parameters poolType and userAssignment .EXAMPLE Get-HVPool -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false + Queries and returns pool object(s) based on given parameters poolName, PoolType etc. .EXAMPLE Get-HVPool -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false -HvServer $mycs + Queries and returns pool object(s) based on given parameters poolName and HvServer etc. .OUTPUTS - Returns list of objects of type Desktop + Returns list of objects of type DesktopInfo .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -1218,6 +1299,10 @@ function Get-HVPool { [boolean] $ProvisioningEnabled, + [Parameter(Mandatory = $false)] + [boolean] + $SuppressInfo = $false, + [Parameter(Mandatory = $false)] $HvServer = $null ) @@ -1228,6 +1313,12 @@ function Get-HVPool { break } $poolList = Find-HVPool -Param $PSBoundParameters + if (! $poolList) { + if (! $SuppressInfo) { + Write-Host "Get-HVPool: No Pool Found with given search parameters" + } + return $poolList + } $queryResults = @() $desktop_helper = New-Object VMware.Hv.DesktopService foreach ($id in $poolList.id) { @@ -1278,21 +1369,28 @@ function Get-HVPoolSummary { If the value is true then only pools which are enabled would be returned. If the value is false then only pools which are disabled would be returned. +.PARAMETER SuppressInfo + Suppress text info, when no pool found with given search parameters + .PARAMETER HvServer Reference to Horizon View Server to query the pools from. If the value is not passed or null then - first element from global:DefaultHVServers would be considered inplace of hvServer + first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE Get-HVPoolSummary -PoolName 'mypool' -PoolType MANUAL -UserAssignment FLOATING -Enabled $true -ProvisioningEnabled $true + Queries and returns desktopSummaryView based on given parameters poolName, poolType etc. .EXAMPLE Get-HVPoolSummary -PoolType AUTOMATED -UserAssignment FLOATING + Queries and returns desktopSummaryView based on given parameters poolType, userAssignment. .EXAMPLE Get-HVPoolSummary -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false + Queries and returns desktopSummaryView based on given parameters poolName, poolType, userAssignment etc. .EXAMPLE Get-HVPoolSummary -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false -HvServer $mycs + Queries and returns desktopSummaryView based on given parameters poolName, HvServer etc. .OUTPUTS Returns list of DesktopSummaryView @@ -1300,11 +1398,11 @@ function Get-HVPoolSummary { .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -1340,6 +1438,10 @@ function Get-HVPoolSummary { [boolean] $ProvisioningEnabled, + [Parameter(Mandatory = $false)] + [boolean] + $SuppressInfo = $false, + [Parameter(Mandatory = $false)] $HvServer = $null ) @@ -1349,8 +1451,11 @@ function Get-HVPoolSummary { Write-Error "Could not retrieve ViewApi services from connection object" break } - $poolList = Find-HVPool -Param $psboundparameters - Return $poolList + $pool_list = Find-HVPool -Param $psboundparameters + if (!$pool_list -and !$suppressInfo) { + Write-Host "Get-HVPoolSummary: No Pool Found with given search parameters" + } + Return $pool_list } function Find-HVPool { @@ -1370,17 +1475,17 @@ function Find-HVPool { 'provisioningEnabled' = 'desktopSummaryData.provisioningEnabled' } - $parms = $Param + $params = $Param $query_service_helper = New-Object VMware.Hv.QueryServiceService $query = New-Object VMware.Hv.QueryDefinition $wildCard = $false #Only supports wild card '*' - if ($parms['PoolName'] -and $parms['PoolName'].contains('*')) { + if ($params['PoolName'] -and $params['PoolName'].contains('*')) { $wildcard = $true } - if ($parms['PoolDisplayName'] -and $parms['PoolDisplayName'].contains('*')) { + if ($params['PoolDisplayName'] -and $params['PoolDisplayName'].contains('*')) { $wildcard = $true } # build the query values @@ -1388,10 +1493,10 @@ function Find-HVPool { if (! $wildcard) { [VMware.Hv.queryfilter[]]$filterSet = @() foreach ($setting in $poolSelectors.Keys) { - if ($null -ne $parms[$setting]) { + if ($null -ne $params[$setting]) { $equalsFilter = New-Object VMware.Hv.QueryFilterEquals $equalsFilter.memberName = $poolSelectors[$setting] - $equalsFilter.value = $parms[$setting] + $equalsFilter.value = $params[$setting] $filterSet += $equalsFilter } } @@ -1408,11 +1513,11 @@ function Find-HVPool { $queryResults = $query_service_helper.QueryService_Query($services,$query) $strFilterSet = @() foreach ($setting in $poolSelectors.Keys) { - if ($null -ne $parms[$setting]) { + if ($null -ne $params[$setting]) { if ($wildcard -and (($setting -eq 'PoolName') -or ($setting -eq 'PoolDisplayName')) ) { - $strFilterSet += '($_.' + $poolSelectors[$setting] + ' -like "' + $parms[$setting] + '")' + $strFilterSet += '($_.' + $poolSelectors[$setting] + ' -like "' + $params[$setting] + '")' } else { - $strFilterSet += '($_.' + $poolSelectors[$setting] + ' -eq "' + $parms[$setting] + '")' + $strFilterSet += '($_.' + $poolSelectors[$setting] + ' -eq "' + $params[$setting] + '")' } } } @@ -1468,32 +1573,40 @@ function Get-HVQueryFilter { .EXAMPLE Get-HVQueryFilter data.name -Eq vmware + Creates queryFilterEquals with given parameters memberName(position 0) and memberValue(position 2) .EXAMPLE Get-HVQueryFilter -MemberName data.name -Eq -MemberValue vmware + Creates queryFilterEquals with given parameters memberName and memberValue .EXAMPLE Get-HVQueryFilter data.name -Ne vmware + Creates queryFilterNotEquals filter with given parameters memberName and memberValue .EXAMPLE Get-HVQueryFilter data.name -Contains vmware + Creates queryFilterContains with given parameters memberName and memberValue .EXAMPLE Get-HVQueryFilter data.name -Startswith vmware + Creates queryFilterStartsWith with given parameters memberName and memberValue .EXAMPLE - $filter = Get-HVQueryFilter data.name -Startswith vmware - Get-HVQueryFilter -Not $filter + C:\PS>$filter = Get-HVQueryFilter data.name -Startswith vmware + C:\PS>Get-HVQueryFilter -Not $filter + Creates queryFilterNot with given parameter filter .EXAMPLE - $filter1 = Get-HVQueryFilter data.name -Startswith vmware - $filter2 = Get-HVQueryFilter data.name -Contains pool - Get-HVQueryFilter -And @($filter1, $filter2) + C:\PS>$filter1 = Get-HVQueryFilter data.name -Startswith vmware + C:\PS>$filter2 = Get-HVQueryFilter data.name -Contains pool + C:\PS>Get-HVQueryFilter -And @($filter1, $filter2) + Creates queryFilterAnd with given parameter filters array .EXAMPLE - $filter1 = Get-HVQueryFilter data.name -Startswith vmware - $filter2 = Get-HVQueryFilter data.name -Contains pool - Get-HVQueryFilter -Or @($filter1, $filter2) + C:\PS>$filter1 = Get-HVQueryFilter data.name -Startswith vmware + C:\PS>$filter2 = Get-HVQueryFilter data.name -Contains pool + C:\PS>Get-HVQueryFilter -Or @($filter1, $filter2) + Creates queryFilterOr with given parameter filters array .OUTPUTS Returns the QueryFilter object @@ -1501,11 +1614,11 @@ function Get-HVQueryFilter { .NOTES Author : Kummara Ramamohan. Author email : kramamohan@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> [CmdletBinding()] @@ -1616,26 +1729,28 @@ function Get-HVQueryResult { .PARAMETER HvServer Reference to Horizon View Server to query the data from. If the value is not passed or null then - first element from global:DefaultHVServers would be considered inplace of hvServer + first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE Get-HVQueryResult DesktopSummaryView + Returns query results of entityType DesktopSummaryView(position 0) .EXAMPLE Get-HVQueryResult DesktopSummaryView (Get-HVQueryFilter data.name -Eq vmware) + Returns query results of entityType DesktopSummaryView(position 0) with given filter(position 1) .EXAMPLE Get-HVQueryResult -EntityType DesktopSummaryView -Filter (Get-HVQueryFilter desktopSummaryData.name -Eq vmware) + Returns query results of entityType DesktopSummaryView with given filter .EXAMPLE - Get-HVQueryResult -EntityType DesktopSummaryView -Filter (Get-HVQueryFilter desktopSummaryData.name -Eq vmware) -SortBy desktopSummaryData.displayName - -.EXAMPLE - $myFilter = Get-HVQueryFilter data.name -Contains vmware - Get-HVQueryResult -EntityType DesktopSummaryView -Filter $myFilter -SortBy desktopSummaryData.displayName -SortDescending $false + C:\PS>$myFilter = Get-HVQueryFilter data.name -Contains vmware + C:\PS>Get-HVQueryResult -EntityType DesktopSummaryView -Filter $myFilter -SortBy desktopSummaryData.displayName -SortDescending $false + Returns query results of entityType DesktopSummaryView with given filter and also sorted based on dispalyName .EXAMPLE Get-HVQueryResult DesktopSummaryView -Limit 10 + Returns query results of entityType DesktopSummaryView, maximum count equal to limit .OUTPUTS Returns the list of objects of entityType @@ -1643,11 +1758,11 @@ function Get-HVQueryResult { .NOTES Author : Kummara Ramamohan. Author email : kramamohan@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -1723,6 +1838,7 @@ function Get-HVQueryResult { } } + function New-HVFarm { <# .Synopsis @@ -1734,6 +1850,9 @@ function New-HVFarm { .PARAMETER LinkedClone Switch to Create Automated Linked Clone farm. +.PARAMETER InstantClone + Switch to Create Automated Instant Clone farm. + .PARAMETER Manual Switch to Create Manual farm. @@ -1758,38 +1877,38 @@ function New-HVFarm { .PARAMETER ParentVM Base image VM for RDS Servers. - Applicable only to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER SnapshotVM Base image snapshot for RDS Servers. .PARAMETER VmFolder VM folder to deploy the RDSServers to. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER HostOrCluster Host or cluster to deploy the RDSServers in. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER ResourcePool Resource pool to deploy the RDSServers. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER Datastores Datastore names to store the RDSServer. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER UseVSAN Whether to use vSphere VSAN. This is applicable for vSphere 5.5 or later. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER EnableProvisioning Set to true to enable provision of RDSServers immediately in farm. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER StopOnProvisioningError Set to true to stop provisioning of all RDSServers on error. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER TransparentPageSharingScope The transparent page sharing scope. @@ -1798,7 +1917,7 @@ function New-HVFarm { .PARAMETER NamingMethod Determines how the VMs in the farm are named. Set PATTERN to use naming pattern. - The default value is PATTERN. Curentlly only PATTERN is allowed. + The default value is PATTERN. Currently only PATTERN is allowed. .PARAMETER NamingPattern RDS Servers will be named according to the specified naming pattern. @@ -1813,26 +1932,42 @@ function New-HVFarm { .PARAMETER MaximumCount Maximum number of Servers in the farm. The default value is 1. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER AdContainer This is the Active Directory container which the Servers will be added to upon creation. The default value is 'CN=Computers'. - Applicable to Linked Clone farm. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER NetBiosName Domain Net Bios Name. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER DomainAdmin Domain Administrator user name which will be used to join the domain. Default value is null. - Applicable to Linked Clone farms. + Applicable to Linked Clone and Instant Clone farms. .PARAMETER SysPrepName The customization spec to use. Applicable to Linked Clone farms. +.PARAMETER PowerOffScriptName + Power off script. ClonePrep can run a customization script on instant-clone machines before they are powered off. Provide the path to the script on the parent virtual machine. + Applicable to Instant Clone farms. + +.PARAMETER PowerOffScriptParameters + Power off script parameters. Example: p1 p2 p3 + Applicable to Instant Clone farms. + +.PARAMETER PostSynchronizationScriptName + Post synchronization script. ClonePrep can run a customization script on instant-clone machines after they are created or recovered or a new image is pushed. Provide the path to the script on the parent virtual machine. + Applicable to Instant Clone farms. + +.PARAMETER PostSynchronizationScriptParameters + Post synchronization script parameters. Example: p1 p2 p3 + Applicable to Instant Clone farms. + .PARAMETER RdsServers List of existing registered RDS server names to add into manual farm. Applicable to Manual farms. @@ -1841,28 +1976,43 @@ function New-HVFarm { Path of the JSON specification file. .PARAMETER HvServer - Reference to Horizon View Server to query the farms from. If the value is not passed or null then first element from global:DefaultHVServers would be considered inplace of hvServer. + Reference to Horizon View Server to query the farms from. If the value is not passed or null then first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE - New-HVFarm -LinkedClone -FarmName 'LCFarmTest' -ParentVM 'Win_Server_2012_R2' -SnapshotVM 'Snap_RDS' -VmFolder 'PoolVM' -HostOrCluster 'cls' -ResourcePool 'cls' -Datastores 'datastore1 (5)' -FarmDisplayName 'LC Farm Test' -Description 'created LC Farm from PS' -EnableProvisioning $true -StopOnProvisioningError $false -NamingPattern "LCFarmVM_PS" -MinReady 1 -MaximumCount 1 -SysPrepName "RDSH_Cust2" -NetBiosName "adviewdev" + New-HVFarm -LinkedClone -FarmName 'LCFarmTest' -ParentVM 'Win_Server_2012_R2' -SnapshotVM 'Snap_RDS' -VmFolder 'PoolVM' -HostOrCluster 'cls' -ResourcePool 'cls' -Datastores 'datastore1 (5)' -FarmDisplayName 'LC Farm Test' -Description 'created LC Farm from PS' -EnableProvisioning $true -StopOnProvisioningError $false -NamingPattern "LCFarmVM_PS" -MinReady 1 -MaximumCount 1 -SysPrepName "RDSH_Cust2" -NetBiosName "adviewdev" + Creates new linkedClone farm by using naming pattern .EXAMPLE - New-HVFarm -Spec C:\VMWare\Specs\LinkedClone.json + New-HVFarm -InstantClone -FarmName 'ICFarmCL' -ParentVM 'vm-rdsh-ic' -SnapshotVM 'Snap_5' -VmFolder 'Instant_Clone_VMs' -HostOrCluster 'vimal-cluster' -ResourcePool 'vimal-cluster' -Datastores 'datastore1' -FarmDisplayName 'IC Farm using CL' -Description 'created IC Farm from PS command-line' -EnableProvisioning $true -StopOnProvisioningError $false -NamingPattern "ICFarmCL-" -NetBiosName "ad-vimalg" + Creates new linkedClone farm by using naming pattern .EXAMPLE - New-HVFarm -Manual -FarmName "manualFarmTest" -FarmDisplayName "manualFarmTest" -Description "Manual PS Test" -RdsServers "vm-for-rds.eng.vmware.com","vm-for-rds-2.eng.vmware.com" + New-HVFarm -Spec C:\VMWare\Specs\LinkedClone.json -Confirm:$false + Creates new linkedClone farm by using json file + +.EXAMPLE + New-HVFarm -Spec C:\VMWare\Specs\InstantCloneFarm.json -Confirm:$false + Creates new instantClone farm by using json file + +.EXAMPLE + New-HVFarm -Manual -FarmName "manualFarmTest" -FarmDisplayName "manualFarmTest" -Description "Manual PS Test" -RdsServers "vm-for-rds.eng.vmware.com","vm-for-rds-2.eng.vmware.com" -Confirm:$false + Creates new manual farm by using rdsServers names + +.EXAMPLE + New-HVFarm -Spec C:\VMWare\Specs\AutomatedInstantCloneFarm.json -FarmName 'InsPool' -NamingPattern 'InsFarm-' + Creates new instant clone farm by reading few parameters from json and few parameters from command line. .OUTPUTS None .NOTES - Author : Ankit Gupta. - Author email : guptaa@vmware.com - Version : 1.0 + Author : praveen mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -1876,6 +2026,10 @@ function New-HVFarm { [switch] $LinkedClone, + [Parameter(Mandatory = $true,ParameterSetName = "INSTANT_CLONE")] + [switch] + $InstantClone, + [Parameter(Mandatory = $true,ParameterSetName = 'MANUAL')] [switch] $Manual, @@ -1883,6 +2037,8 @@ function New-HVFarm { #farmSpec.farmData.name [Parameter(Mandatory = $true,ParameterSetName = 'MANUAL')] [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = "INSTANT_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'JSON_FILE')] [string] $FarmName, @@ -1906,102 +2062,274 @@ function New-HVFarm { [boolean] $Enable = $true, - #farmSpec.automatedfarmSpec.virtualCenter if LINKED_CLONE + #farmSpec.data.settings.disconnectedSessionTimeoutPolicy + [Parameter(Mandatory = $false)] + [ValidateSet("IMMEDIATE","NEVER","AFTER")] + [string] + $DisconnectedSessionTimeoutPolicy = "NEVER", + + #farmSpec.data.settings.disconnectedSessionTimeoutMinutes + [Parameter(Mandatory = $false)] + [ValidateRange(1,[Int]::MaxValue)] + [int] + $DisconnectedSessionTimeoutMinutes, + + #farmSpec.data.settings.emptySessionTimeoutPolicy + [Parameter(Mandatory = $false)] + [ValidateSet("NEVER","AFTER")] + [string] + $EmptySessionTimeoutPolicy = "AFTER", + + #farmSpec.data.settings.emptySessionTimeoutMinutes + [Parameter(Mandatory = $false)] + [ValidateSet(1,[Int]::MaxValue)] + [int] + $EmptySessionTimeoutMinutes = 1, + + #farmSpec.data.settings.logoffAfterTimeout + [Parameter(Mandatory = $false)] + [boolean] + $LogoffAfterTimeout = $false, + + #farmSpec.data.displayProtocolSettings.defaultDisplayProtocol + [Parameter(Mandatory = $false)] + [ValidateSet("RDP","PCOIP","BLAST")] + [string] + $DefaultDisplayProtocol = "PCOIP", + + #farmSpec.data.displayProtocolSettings.allowDisplayProtocolOverride + [Parameter(Mandatory = $false)] + [boolean] + $AllowDisplayProtocolOverride = $true, + + #farmSpec.data.displayProtocolSettings.enableHTMLAccess + [Parameter(Mandatory = $false)] + [boolean] + $EnableHTMLAccess = $false, + + #farmSpec.data.serverErrorThreshold + [Parameter(Mandatory = $false)] + [ValidateRange(0,[Int]::MaxValue)] + $ServerErrorThreshold = 0, + + #farmSpec.data.mirageConfigurationOverrides.overrideGlobalSetting + [Parameter(Mandatory = $false)] + [boolean] + $OverrideGlobalSetting = $false, + + #farmSpec.data.mirageConfigurationOverrides.enabled + [Parameter(Mandatory = $false)] + [boolean] + $MirageServerEnabled, + + #farmSpec.data.mirageConfigurationOverrides.url + [Parameter(Mandatory = $false)] + [string] + $Url, + + #farmSpec.automatedfarmSpec.virtualCenter if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [string] $Vcenter, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.parentVM if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.parentVM if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string] $ParentVM, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.snapshotVM if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.snapshotVM if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string] $SnapshotVM, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.vmFolder if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.vmFolder if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string] $VmFolder, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.hostOrCluster if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.hostOrCluster if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string] $HostOrCluster, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.resourcePool if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.resourcePool if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string] $ResourcePool, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastore if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.dataCenter if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string] + $dataCenter, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastore if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string[]] $Datastores, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.useVSAN if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastores.storageOvercommit if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] - [string] - $UseVSAN, + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string[]] + $StorageOvercommit = $null, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.enableProvsioning if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.useVSAN if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $UseVSAN = $false, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.enableProvsioning if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [boolean] $EnableProvisioning = $true, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.stopOnProvisioningError if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.stopOnProvisioningError if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [boolean] $StopOnProvisioningError = $true, [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [string] $TransparentPageSharingScope = 'VM', - #farmSpec.automatedfarmSpec.rdsServerNamingSpec.namingMethod if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + #farmSpec.automatedfarmSpec.rdsServerNamingSpec.namingMethod if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [ValidateSet('PATTERN')] [string] $NamingMethod = 'PATTERN', - #farmSpec.automatedfarmSpec.rdsServerNamingSpec.patternNamingSettings.namingPattern if LINKED_CLONE + #farmSpec.automatedfarmSpec.rdsServerNamingSpec.patternNamingSettings.namingPattern if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'JSON_FILE')] [string] $NamingPattern = $farmName + '{n:fixed=4}', - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [int] $MinReady = 0, - #farmSpec.automatedfarmSpec.rdsServerNamingSpec.patternNamingSettings.maxNumberOfRDSServers if LINKED_CLONE + #farmSpec.automatedfarmSpec.rdsServerNamingSpec.patternNamingSettings.maxNumberOfRDSServers if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [int] $MaximumCount = 1, - #farmSpec.automatedfarmSpec.customizationSettings.adContainer if LINKED_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.useSeparateDatastoresReplicaAndOSDisks if INSTANT_CLONE, LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $UseSeparateDatastoresReplicaAndOSDisks = $false, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.replicaDiskDatastore, if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string] + $ReplicaDiskDatastore, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.useNativeSnapshots, if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $UseNativeSnapshots = $false, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.reclaimVmDiskSpace, if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $ReclaimVmDiskSpace = $false, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.reclamationThresholdGB + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(0,[Int]::MaxValue)] + [int] + $ReclamationThresholdGB = 1, + + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.blackoutTimes + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [VMware.Hv.FarmBlackoutTime[]] + $BlackoutTimes, + + #farmSpec.automatedfarmSpec.customizationSettings.adContainer if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = "INSTANT_CLONE")] [string] $AdContainer = 'CN=Computers', #farmSpec.automatedfarmSpec.customizationSettings.domainAdministrator + #farmSpec.automatedfarmSpec.customizationSettings.cloneprepCustomizationSettings.instantCloneEngineDomainAdministrator [Parameter(Mandatory = $true,ParameterSetName = 'LINKED_CLONE')] + [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] [string] $NetBiosName, #farmSpec.automatedfarmSpec.customizationSettings.domainAdministrator + #farmSpec.automatedfarmSpec.customizationSettings.cloneprepCustomizationSettings.instantCloneEngineDomainAdministrator [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = "INSTANT_CLONE")] [string] $DomainAdmin = $null, + #farmSpec.automatedfarmSpec.customizationSettings.reusePreExistingAccounts + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [Boolean] + $ReusePreExistingAccounts = $false, + #farmSpec.automatedfarmSpec.customizationSettings.sysprepCustomizationSettings.customizationSpec if LINKED_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] [string] $SysPrepName, - ##farmSpec.manualfarmSpec.rdsServers + #desktopSpec.automatedfarmSpec.customizationSettings.cloneprepCustomizationSettings.powerOffScriptName if INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string] + $PowerOffScriptName, + + #farmSpec.automatedfarmSpec.customizationSettings.cloneprepCustomizationSettings.powerOffScriptParameters if INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string] + $PowerOffScriptParameters, + + #farmSpec.automatedfarmSpec.customizationSettings.cloneprepCustomizationSettings.postSynchronizationScriptName if INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string] + $PostSynchronizationScriptName, + + #farmSpec.automatedfarmSpec.customizationSettings.cloneprepCustomizationSettings.postSynchronizationScriptParameters if INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [string] + $PostSynchronizationScriptParameters, + + #farmSpec.automatedfarmSpec.rdsServerMaxSessionsData.maxSessionsType if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = "INSTANT_CLONE")] + [ValidateSet("UNLIMITED", "LIMITED")] + [string] + $MaxSessionsType = "UNLIMITED", + + #farmSpec.automatedfarmSpec.rdsServerMaxSessionsData.maxSessionsType if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = "INSTANT_CLONE")] + [ValidateRange(1, [int]::MaxValue)] + [int] + $MaxSessions, + + #farmSpec.manualfarmSpec.rdsServers [Parameter(Mandatory = $true,ParameterSetName = 'MANUAL')] [string[]] $RdsServers, @@ -2033,6 +2361,9 @@ function New-HVFarm { # ADContainerId # FarmSysprepCustomizationSettings # CustomizationSpecId + # FarmCloneprepCustomizationSettings + # InstantCloneEngineDomainAdministratorId + # # FarmManualfarmSpec # RDSServerId[] # @@ -2046,12 +2377,12 @@ function New-HVFarm { } process { - + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys if ($farmName) { try { - $sourceFarm = Get-HVFarm -farmName $farmName -hvServer $hvServer + $sourceFarm = Get-HVFarmSummary -farmName $farmName -hvServer $hvServer -suppressInfo $true } catch { - Write-Error "Make sure Get-HVFarm advanced function is loaded, $_" + Write-Error "Make sure Get-HVFarmSummary advanced function is loaded, $_" break } if ($sourceFarm) { @@ -2067,18 +2398,51 @@ function New-HVFarm { Write-Error "Json file exception, $_" break } + try { + Test-HVFarmSpec -PoolObject $jsonObject + } catch { + Write-Error "Json object validation failed, $_" + break + } if ($jsonObject.type -eq 'AUTOMATED') { $farmType = 'AUTOMATED' + $provisioningType = $jsonObject.ProvisioningType if ($null -ne $jsonObject.AutomatedFarmSpec.VirtualCenter) { $vCenter = $jsonObject.AutomatedFarmSpec.VirtualCenter } - $linkedClone = $true + $netBiosName = $jsonObject.NetBiosName - $adContainer = $jsonObject.AutomatedFarmSpec.CustomizationSettings.AdContainer + if (!$jsonObject.AutomatedFarmSpec.CustomizationSettings.AdContainer) { + Write-Host "adContainer was empty using CN=Computers" + } else { + $AdContainer = $jsonObject.AutomatedFarmSpec.CustomizationSettings.AdContainer + } + + #populate customization settings attributes based on the cutomizationType + if ($jsonObject.AutomatedFarmSpec.ProvisioningType -eq "INSTANT_CLONE_ENGINE") { + $InstantClone = $true + if ($null -ne $jsonObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings) { + $DomainAdmin = $jsonObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.InstantCloneEngineDomainAdministrator + $powerOffScriptName = $jsonObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.PowerOffScriptName + $powerOffScriptParameters = $jsonObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.PowerOffScriptParameters + $postSynchronizationScriptName = $jsonObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.PostSynchronizationScriptName + $postSynchronizationScriptParameters = $jsonObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.PostSynchronizationScriptParameters + } + } elseif ($jsonObject.AutomatedFarmSpec.ProvisioningType -eq "VIEW_COMPOSER") { + $LinkedClone = $true + $DomainAdmin = $jsonObject.AutomatedFarmSpec.CustomizationSettings.domainAdministrator + $reusePreExistingAccounts = $jsonObject.AutomatedFarmSpec.CustomizationSettings.ReusePreExistingAccounts + $sysPrepName = $jsonObject.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings.CustomizationSpec + } $namingMethod = $jsonObject.AutomatedFarmSpec.RdsServerNamingSpec.NamingMethod - $namingPattern = $jsonObject.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings.namingPattern + if ($NamingPattern -eq '{n:fixed=4}') { + $namingPattern = $jsonObject.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings.namingPattern + } $maximumCount = $jsonObject.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings.maxNumberOfRDSServers + $enableProvisioning = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.EnableProvisioning + $stopProvisioningOnError = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.StopProvisioningOnError + $minReady = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.MinReadyVMsOnVComposerMaintenance $transparentPageSharingScope = $jsonObject.AutomatedFarmSpec.virtualCenterManagedCommonSettings.TransparentPageSharingScope @@ -2092,10 +2456,44 @@ function New-HVFarm { $hostOrCluster = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.HostOrCluster $resourcePool = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.ResourcePool $dataStoreList = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.Datastores + foreach ($dtStore in $dataStoreList) { $datastores += $dtStore.Datastore + $storageOvercommit += $dtStore.StorageOvercommit } - $sysPrepName = $jsonObject.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings.CustomizationSpec + $useVSan = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.UseVSan + + ## ViewComposerStorageSettings for Linked-Clone farms + if ($LinkedClone -or $InstantClone) { + $useSeparateDatastoresReplicaAndOSDisks = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.UseSeparateDatastoresReplicaAndOSDisks + if ($useSeparateDatastoresReplicaAndOSDisks) { + $replicaDiskDatastore = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.ReplicaDiskDatastore + } + if ($LinkedClone) { + #For Instant clone desktops, this setting can only be set to false + $useNativeSnapshots = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.UseNativeSnapshots + $reclaimVmDiskSpace = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.SpaceReclamationSettings.ReclaimVmDiskSpace + if ($reclaimVmDiskSpace) { + $ReclamationThresholdGB = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.SpaceReclamationSettings.ReclamationThresholdGB + if ($null -ne $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.SpaceReclamationSettings.blackoutTimes) { + $blackoutTimesList = $jsonObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.ViewComposerStorageSettings.SpaceReclamationSettings.blackoutTimes + foreach ($blackout in $blackoutTimesList) { + $blackoutObj = New-Object VMware.Hv.DesktopBlackoutTime + $blackoutObj.Days = $blackout.Days + $blackoutObj.StartTime = $blackout.StartTime + $blackoutObj.EndTime = $blackoutObj.EndTime + $blackoutTimes += $blackoutObj + } + } + } + } + } + + $maxSessionsType = $jsonObject.AutomatedFarmSpec.RdsServerMaxSessionsData.MaxSessionsType + if ($maxSessionsType -eq "LIMITED") { + $maxSessions = $jsonObject.AutomatedFarmSpec.RdsServerMaxSessionsData.MaxSessions + } + } elseif ($jsonObject.type -eq 'MANUAL') { $manual = $true $farmType = 'MANUAL' @@ -2105,16 +2503,44 @@ function New-HVFarm { $rdsServers += $RdsServerObj.rdsServer } } - $farmDisplayName = $jsonObject.data.DisplayName - $description = $jsonObject.data.Description - $accessGroup = $jsonObject.data.AccessGroup - $farmName = $jsonObject.data.name + $farmDisplayName = $jsonObject.Data.DisplayName + $description = $jsonObject.Data.Description + $accessGroup = $jsonObject.Data.AccessGroup + if (! $FarmName) { + $farmName = $jsonObject.Data.name + } + if ($null -ne $jsonObject.Data.Enabled) { + $enable = $jsonObject.Data.Enabled + } + if ($null -ne $jsonObject.Data.Settings) { + $disconnectedSessionTimeoutPolicy = $jsonObject.Data.Settings.DisconnectedSessionTimeoutPolicy + $disconnectedSessionTimeoutMinutes = $jsonObject.Data.Settings.DisconnectedSessionTimeoutMinutes + $emptySessionTimeoutPolicy = $jsonObject.Data.Settings.EmptySessionTimeoutPolicy + $emptySessionTimeoutMinutes = $jsonObject.Data.Settings.EmptySessionTimeoutMinutes + $logoffAfterTimeout = $jsonObject.Data.Settings.LogoffAfterTimeout + } + if ($null -ne $jsonObject.Data.DisplayProtocolSettings) { + $defaultDisplayProtocol = $jsonObject.Data.DisplayProtocolSettings.DefaultDisplayProtocol + $allowDisplayProtocolOverride = $jsonObject.Data.DisplayProtocolSettings.AllowDisplayProtocolOverride + $enableHTMLAccess = $jsonObject.Data.DisplayProtocolSettings.EnableHTMLAccess + } + if ($null -ne $jsonObject.Data.serverErrorThreshold) { + $serverErrorThreshold = $jsonObject.Data.serverErrorThreshold + } + if ($null -ne $jsonObject.Data.MirageConfigurationOverrides) { + $overrideGlobalSetting = $jsonObject.Data.MirageConfigurationOverrides.OverrideGlobalSetting + $mirageserverEnabled = $jsonObject.Data.MirageConfigurationOverrides.Enabled + $url = $jsonObject.Data.MirageConfigurationOverrides.url + } } if ($linkedClone) { $farmType = 'AUTOMATED' $provisioningType = 'VIEW_COMPOSER' - } elseif ($manual) { + } elseif ($InstantClone) { + $farmType = 'AUTOMATED' + $provisioningType = 'INSTANT_CLONE_ENGINE' + }elseif ($manual) { $farmType = 'MANUAL' } @@ -2167,17 +2593,17 @@ function New-HVFarm { $farmVirtualCenterManagedCommonSettings = $farmSpecObj.AutomatedFarmSpec.virtualCenterManagedCommonSettings } - if (!$farmVirtualMachineNamingSpec) { + if ($farmSpecObj.AutomatedFarmSpec.RdsServerNamingSpec) { $farmSpecObj.AutomatedFarmSpec.RdsServerNamingSpec.NamingMethod = $namingMethod $farmSpecObj.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings.namingPattern = $namingPattern $farmSpecObj.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings.maxNumberOfRDSServers = $maximumCount } else { $vmNamingSpec = New-Object VMware.Hv.FarmRDSServerNamingSpec - $vmNamingSpec.NamingMethod = 'PATTERN' - + $vmNamingSpec.NamingMethod = $namingMethod $vmNamingSpec.patternNamingSettings = New-Object VMware.Hv.FarmPatternNamingSettings $vmNamingSpec.patternNamingSettings.namingPattern = $namingPattern $vmNamingSpec.patternNamingSettings.maxNumberOfRDSServers = $maximumCount + $farmSpecObj.AutomatedFarmSpec.RdsServerNamingSpec = $vmNamingSpec } # @@ -2185,8 +2611,10 @@ function New-HVFarm { # try { $farmVirtualCenterProvisioningData = Get-HVFarmProvisioningData -vc $virtualCenterID -vmObject $farmVirtualCenterProvisioningData - $hostClusterId = $farmVirtualCenterProvisioningData.HostOrCluster - $farmVirtualCenterStorageSettings = Get-HVFarmStorageObject -hostclusterID $hostClusterId -storageObject $farmVirtualCenterStorageSettings + + $HostOrCluster_helper = New-Object VMware.Hv.HostOrClusterService + $hostClusterIds = (($HostOrCluster_helper.HostOrCluster_GetHostOrClusterTree($services, $farmVirtualCenterProvisioningData.datacenter)).treeContainer.children.info).Id + $farmVirtualCenterStorageSettings = Get-HVFarmStorageObject -hostclusterIDs $hostClusterIds -storageObject $farmVirtualCenterStorageSettings $farmVirtualCenterNetworkingSettings = Get-HVFarmNetworkSetting -networkObject $farmVirtualCenterNetworkingSettings $farmCustomizationSettings = Get-HVFarmCustomizationSetting -vc $virtualCenterID -customObject $farmCustomizationSettings } catch { @@ -2195,31 +2623,20 @@ function New-HVFarm { break } - $farmSpecObj.AutomatedFarmSpec.RdsServerMaxSessionsData.MaxSessionsType = "UNLIMITED" - - if (!$FarmVirtualCenterProvisioningSettings) { - $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.enableProvisioning = $true - $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.stopProvisioningOnError = $true - $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance = 0 - $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData = $farmVirtualCenterProvisioningData - $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings = $farmVirtualCenterStorageSettings - $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterNetworkingSettings = $FarmVirtualCenterNetworkingSettings - - $farmSpecObj.AutomatedFarmSpec.CustomizationSettings = $farmCustomizationSettings - $farmSpecObj.AutomatedFarmSpec.ProvisioningType = $provisioningType - $farmSpecObj.AutomatedFarmSpec.VirtualCenter = $virtualCenterID - } else { - $FarmVirtualCenterProvisioningSettings.VirtualCenterProvisioningData = $farmVirtualCenterProvisioningData - $FarmVirtualCenterProvisioningSettings.VirtualCenterStorageSettings = $farmVirtualCenterStorageSettings - $FarmVirtualCenterProvisioningSettings.VirtualCenterNetworkingSettings = $FarmVirtualCenterNetworkingSettings - - $FarmAutomatedFarmSpec = New-Object VMware.Hv.FarmAutomatedFarmSpec - $FarmAutomatedFarmSpec.ProvisioningType = $provisioningType - $FarmAutomatedFarmSpec.VirtualCenter = $virtualCenterID - $FarmAutomatedFarmSpec.VirtualCenterProvisioningSettings = $farmVirtualCenterProvisioningSettings - $FarmAutomatedFarmSpec.virtualCenterManagedCommonSettings = $farmVirtualCenterManagedCommonSettings - $FarmAutomatedFarmSpec.CustomizationSettings = $farmCustomizationSettings + $farmSpecObj.AutomatedFarmSpec.RdsServerMaxSessionsData.MaxSessionsType = $maxSessionsType + if ($maxSessionsType -eq "LIMITED") { + $farmSpecObj.AutomatedFarmSpec.RdsServerMaxSessionsData.MaxSessionsType = $maxSessions } + $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.enableProvisioning = $enableProvisioning + $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.stopProvisioningOnError = $stopProvisioningOnError + $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance = $minReady + $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData = $farmVirtualCenterProvisioningData + $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings = $farmVirtualCenterStorageSettings + $farmSpecObj.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterNetworkingSettings = $FarmVirtualCenterNetworkingSettings + + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings = $farmCustomizationSettings + $farmSpecObj.AutomatedFarmSpec.ProvisioningType = $provisioningType + $farmSpecObj.AutomatedFarmSpec.VirtualCenter = $virtualCenterID } } @@ -2235,6 +2652,29 @@ function New-HVFarm { $farmData.name = $farmName $farmData.DisplayName = $farmDisplayName $farmData.Description = $description + if ($farmData.Settings) { + $farmData.Settings.DisconnectedSessionTimeoutPolicy = $disconnectedSessionTimeoutPolicy + if ($disconnectedSessionTimeoutPolicy -eq "AFTER") { + $farmData.Settings.DisconnectedSessionTimeoutMinutes = $disconnectedSessionTimeoutMinutes + } + $farmData.Settings.EmptySessionTimeoutPolicy = $emptySessionTimeoutPolicy + if ($emptySessionTimeoutPolicy -eq "AFTER") { + $farmData.Settings.EmptySessionTimeoutMinutes = $emptySessionTimeoutMinutes + } + $logoffAfterTimeout = $farmData.Settings.logoffAfterTimeout + } + if ($farmData.DisplayProtocolSettings) { + $farmData.DisplayProtocolSettings.DefaultDisplayProtocol = $defaultDisplayProtocol + $farmData.DisplayProtocolSettings.AllowDisplayProtocolOverride = $AllowDisplayProtocolOverride + $farmData.DisplayProtocolSettings.EnableHTMLAccess = $enableHTMLAccess + } + if ($farmData.MirageConfigurationOverrides){ + $farmData.MirageConfigurationOverrides.OverrideGlobalSetting = $overrideGlobalSetting + $farmData.MirageConfigurationOverrides.Enabled = $mirageServerEnabled + if ($url) { + $farmData.MirageConfigurationOverrides.Url = $url + } + } $farmSpecObj.type = $farmType if ($FarmAutomatedFarmSpec) { @@ -2246,10 +2686,21 @@ function New-HVFarm { # Please uncomment below code, if you want to save the json file <# -$myDebug = convertto-json -InputObject $farmSpecObj -depth 12 -$myDebug | out-file -filepath c:\temp\copiedfarm.json -#> - $farm_service_helper.Farm_Create($services, $farmSpecObj) + $myDebug = convertto-json -InputObject $farmSpecObj -depth 12 + $myDebug | out-file -filepath c:\temp\copiedfarm.json + #> + + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($farmSpecObj.data.name)) { + $Id = $farm_service_helper.Farm_Create($services, $farmSpecObj) + } else { + try { + Test-HVFarmSpec -PoolObject $farmSpecObj + } catch { + Write-Error "FarmSpec object validation failed, $_" + break + } + } + return $farmSpecObj } end { @@ -2258,6 +2709,89 @@ $myDebug | out-file -filepath c:\temp\copiedfarm.json } +function Test-HVFarmSpec { + param( + [Parameter(Mandatory = $true)] + $PoolObject + ) + if ($null -eq $PoolObject.Type) { + Throw "Specify type of farm" + } + $jsonFarmTypeArray = @('AUTOMATED','MANUAL') + if (! ($jsonFarmTypeArray -contains $PoolObject.Type)) { + Throw "Farm type must be AUTOMATED or MANUAL" + } + if ($null -eq $PoolObject.Data.Name) { + Throw "Specify farm name" + } + if ($null -eq $PoolObject.Data.AccessGroup) { + Throw "Specify horizon access group" + } + if ($PoolObject.Type -eq "AUTOMATED"){ + $jsonProvisioningType = $PoolObject.AutomatedFarmSpec.ProvisioningType + if ($null -eq $jsonProvisioningType) { + Throw "Must specify provisioningType" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.RdsServerNamingSpec.namingMethod) { + Throw "Must specify naming method to PATTERN" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings) { + Throw "Specify Naming pattern settings" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.RdsServerNamingSpec.patternNamingSettings.namingPattern) { + Throw "Specify specified naming pattern" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.virtualCenterProvisioningSettings.enableProvisioning) { + Throw "Specify Whether to enable provisioning or not" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.virtualCenterProvisioningSettings.stopProvisioningOnError) { + Throw "Specify Whether provisioning on all VMs stops on error" + } + $jsonTemplate = $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.Template + $jsonParentVm = $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.ParentVm + $jsonSnapshot = $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.Snapshot + $jsonVmFolder = $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.VmFolder + $jsonHostOrCluster = $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.HostOrCluster + $ResourcePool = $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.ResourcePool + if (!( ($null -ne $jsonTemplate) -or (($null -ne $jsonParentVm) -and ($null -ne $jsonSnapshot) )) ) { + Throw "Must specify Template or (ParentVm and Snapshot) names" + } + if ($null -eq $jsonVmFolder) { + Throw "Must specify VM folder to deploy the VMs" + } + if ($null -eq $jsonHostOrCluster) { + Throw "Must specify Host or cluster to deploy the VMs" + } + if ($null -eq $resourcePool) { + Throw "Must specify Resource pool to deploy the VMs" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.Datastores) { + Throw "Must specify datastores names" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.useVSan) { + Throw "Must specify whether to use virtual SAN or not" + } + $customizationType = $PoolObject.AutomatedFarmSpec.CustomizationSettings.customizationType + if ($null -eq $customizationType) { + Throw "Specify customization type" + } + if ($customizationType -eq 'SYS_PREP' -and $null -eq $PoolObject.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings) { + Throw "Specify sysPrep customization settings" + } + if ($customizationType -eq 'CLONE_PREP' -and $null -eq $PoolObject.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings) { + Throw "Specify clone customization settings" + } + if ($null -eq $PoolObject.AutomatedFarmSpec.RdsServerMaxSessionsData.MaxSessionsType) { + Throw "Specify MaxSessionsType" + } + } elseif ($PoolObject.Type -eq "MANUAL") { + if ($null -eq $PoolObject.manualFarmSpec.rdsServers) { + Throw "Specify rdsServers name" + } + } +} + + function Get-HVFarmProvisioningData { param( [Parameter(Mandatory = $false)] @@ -2278,6 +2812,12 @@ function Get-HVFarmProvisioningData { } $vmObject.ParentVm = $parentVMObj.id $dataCenterID = $parentVMObj.datacenter + if ($dataCenter -and $dataCenterID) { + $baseImageVmInfo = $base_imageVm_helper.BaseImageVm_ListByDatacenter($dataCenterID) + if (! ($baseImageVmInfo.Path -like "/$dataCenter/*")) { + throw "$parentVM not exists in datacenter: [$dataCenter]" + } + } $vmObject.datacenter = $dataCenterID } if ($snapshotVM) { @@ -2330,23 +2870,30 @@ function Get-HVFarmProvisioningData { return $vmObject } + function Get-HVFarmStorageObject { param( - [Parameter(Mandatory = $false)] - [VMware.Hv.FarmVirtualCenterStorageSettings]$StorageObject, [Parameter(Mandatory = $true)] - [VMware.Hv.HostOrClusterId]$HostClusterID + [VMware.Hv.HostOrClusterId[]]$HostClusterIDs, + + [Parameter(Mandatory = $false)] + [VMware.Hv.FarmVirtualCenterStorageSettings]$StorageObject ) if (!$storageObject) { $storageObject = New-Object VMware.Hv.FarmVirtualCenterStorageSettings $FarmSpaceReclamationSettings = New-Object VMware.Hv.FarmSpaceReclamationSettings -Property @{ 'reclaimVmDiskSpace' = $false } + if ($reclaimVmDiskSpace) { + $FarmSpaceReclamationSettings.ReclamationThresholdGB = $reclamationThresholdGB + if ($blackoutTimes) { + $FarmSpaceReclamationSettings.BlackoutTimes = $blackoutTimes + } + } $FarmViewComposerStorageSettingsList = @{ - 'useSeparateDatastoresReplicaAndOSDisks' = $false; - 'replicaDiskDatastore' = $FarmReplicaDiskDatastore - 'useNativeSnapshots' = $false; + 'useSeparateDatastoresReplicaAndOSDisks' = $UseSeparateDatastoresReplicaAndOSDisks; + 'useNativeSnapshots' = $useNativeSnapshots; 'spaceReclamationSettings' = $FarmSpaceReclamationSettings; } @@ -2354,18 +2901,35 @@ function Get-HVFarmStorageObject { } if ($datastores) { + if ($StorageOvercommit -and ($datastores.Length -ne $StorageOvercommit.Length) ) { + throw "Parameters datastores length: [$datastores.Length] and StorageOvercommit length: [$StorageOvercommit.Length] should be of same size" + } $Datastore_service_helper = New-Object VMware.Hv.DatastoreService - $datastoreList = $Datastore_service_helper.Datastore_ListDatastoresByHostOrCluster($services, $hostClusterID) + foreach ($hostClusterID in $hostClusterIDs) { + $datastoreList += $Datastore_service_helper.Datastore_ListDatastoresByHostOrCluster($services, $hostClusterID) + } $datastoresSelected = @() foreach ($ds in $datastores) { $datastoresSelected += ($datastoreList | Where-Object { $_.datastoredata.name -eq $ds }).id } + if (! $storageOvercommit) { + foreach ($ds in $datastoresSelected) { + $storageOvercommit += ,'UNBOUNDED' + } + } + $StorageOvercommitCnt = 0 foreach ($ds in $datastoresSelected) { $datastoresObj = New-Object VMware.Hv.FarmVirtualCenterDatastoreSettings $datastoresObj.Datastore = $ds - $datastoresObj.StorageOvercommit = 'UNBOUNDED' + $datastoresObj.StorageOvercommit = $storageOvercommit[$StorageOvercommitCnt] $StorageObject.Datastores += $datastoresObj } + if ($useSeparateDatastoresReplicaAndOSDisks) { + $StorageObject.ViewComposerStorageSettings.UseSeparateDatastoresReplicaAndOSDisks = $UseSeparateDatastoresReplicaAndOSDisks + $FarmReplicaDiskDatastore = ($datastoreList | Where-Object { $_.datastoredata.name -eq $replicaDiskDatastore }).id + $StorageObject.ViewComposerStorageSettings.ReplicaDiskDatastore = $FarmReplicaDiskDatastore + } + } if ($storageObject.Datastores.Count -eq 0) { throw "No datastores found with name: [$datastores]" @@ -2374,6 +2938,7 @@ function Get-HVFarmStorageObject { return $storageObject } + function Get-HVFarmNetworkSetting { param( [Parameter(Mandatory = $false)] @@ -2385,6 +2950,7 @@ function Get-HVFarmNetworkSetting { return $networkObject } + function Get-HVFarmCustomizationSetting { param( [Parameter(Mandatory = $false)] @@ -2394,44 +2960,98 @@ function Get-HVFarmCustomizationSetting { [VMware.Hv.VirtualCenterId]$VcID ) if (!$customObject) { - $ViewComposerDomainAdministrator_service_helper = New-Object VMware.Hv.ViewComposerDomainAdministratorService - $ViewComposerDomainAdministratorID = ($ViewComposerDomainAdministrator_service_helper.ViewComposerDomainAdministrator_List($services, $vcID) | Where-Object { $_.base.domain -match $netBiosName }) - if (! [string]::IsNullOrWhitespace($domainAdmin)) { - $ViewComposerDomainAdministratorID = ($ViewComposerDomainAdministratorID | Where-Object { $_.base.userName -ieq $domainAdmin }).id - } else { - $ViewComposerDomainAdministratorID = $ViewComposerDomainAdministratorID[0].id + # View Composer and Instant Clone Engine Active Directory container for QuickPrep and ClonePrep. This must be set for Instant Clone Engine or SVI sourced desktops. + if ($InstantClone -or $LinkedClone) { + $ad_domain_helper = New-Object VMware.Hv.ADDomainService + $ADDomains = $ad_domain_helper.ADDomain_List($services) + if ($netBiosName) { + $adDomianId = ($ADDomains | Where-Object { $_.NetBiosName -eq $netBiosName } | Select-Object -Property id) + if ($null -eq $adDomianId) { + throw "No Domain found with netBiosName: [$netBiosName]" + } + } else { + $adDomianId = ($ADDomains[0] | Select-Object -Property id) + if ($null -eq $adDomianId) { + throw "No Domain configured in view administrator UI" + } + } + $ad_container_helper = New-Object VMware.Hv.AdContainerService + $adContainerId = ($ad_container_helper.ADContainer_ListByDomain($services,$adDomianId.id) | Where-Object { $_.Rdn -eq $adContainer } | Select-Object -Property id).id + if ($null -eq $adContainerId) { + throw "No AdContainer found with name: [$adContainer]" + } + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.AdContainer = $adContainerId } - if ($null -eq $ViewComposerDomainAdministratorID) { - throw "No Composer Domain Administrator found with netBiosName: [$netBiosName]" - } - $ADDomain_service_helper = New-Object VMware.Hv.ADDomainService - $adDomianId = ($ADDomain_service_helper.ADDomain_List($services) | Where-Object { $_.NetBiosName -eq $netBiosName } | Select-Object -Property id) - if ($null -eq $adDomianId) { - throw "No Domain found with netBiosName: [$netBiosName]" - } - $ad_containder_service_helper = New-Object VMware.Hv.AdContainerService - $adContainerId = ($ad_containder_service_helper.ADContainer_ListByDomain($services, $adDomianId.id) | Where-Object { $_.Rdn -eq $adContainer } | Select-Object -Property id).id - if ($null -eq $adContainerId) { - throw "No AdContainer found with name: [$adContainer]" - } - #Support only Sysprep Customization - $sysprepCustomizationSettings = $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings - # Get SysPrep CustomizationSpec ID - $CustomizationSpec_service_helper = New-Object VMware.Hv.CustomizationSpecService - $sysPrepIds = $CustomizationSpec_service_helper.CustomizationSpec_List($services, $vcID) | Where-Object { $_.customizationSpecData.name -eq $sysPrepName } | Select-Object -Property id - if ($sysPrepIds.Count -eq 0) { - throw "No Sysprep Customization spec found with Name: [$sysPrepName]" + if ($InstantClone) { + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CustomizationType = 'CLONE_PREP' + $instantCloneEngineDomainAdministrator_helper = New-Object VMware.Hv.InstantCloneEngineDomainAdministratorService + $insDomainAdministrators = $instantCloneEngineDomainAdministrator_helper.InstantCloneEngineDomainAdministrator_List($services) + $strFilterSet = @() + if (![string]::IsNullOrWhitespace($netBiosName)) { + $strFilterSet += '$_.namesData.dnsName -match $netBiosName' + } + if (![string]::IsNullOrWhitespace($domainAdmin)) { + $strFilterSet += '$_.base.userName -eq $domainAdmin' + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $instantCloneEngineDomainAdministrator = $insDomainAdministrators | Where $scriptBlock + If ($null -ne $instantCloneEngineDomainAdministrator) { + $instantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator[0].id + } elseif ($null -ne $insDomainAdministrators) { + $instantCloneEngineDomainAdministrator = $insDomainAdministrators[0].id + } + if ($null -eq $instantCloneEngineDomainAdministrator) { + throw "No Instant Clone Engine Domain Administrator found with netBiosName: [$netBiosName]" + } + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings = New-Object VMware.Hv.FarmClonePrepCustomizationSettings + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.InstantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.powerOffScriptName = $powerOffScriptName + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.powerOffScriptParameters = $powerOffScriptParameters + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.postSynchronizationScriptName = $postSynchronizationScriptName + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CloneprepCustomizationSettings.postSynchronizationScriptParameters = $postSynchronizationScriptParameters + $customObject = $farmSpecObj.AutomatedFarmSpec.CustomizationSettings + } elseif ($LinkedClone) { + $ViewComposerDomainAdministrator_service_helper = New-Object VMware.Hv.ViewComposerDomainAdministratorService + $lcDomainAdministrators = $ViewComposerDomainAdministrator_service_helper.ViewComposerDomainAdministrator_List($services, $vcID) + $strFilterSet = @() + if (![string]::IsNullOrWhitespace($netBiosName)) { + $strFilterSet += '$_.base.domain -match $netBiosName' + } + if (![string]::IsNullOrWhitespace($domainAdmin)) { + $strFilterSet += '$_.base.userName -ieq $domainAdmin' + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $ViewComposerDomainAdministratorID = $lcDomainAdministrators | Where $scriptBlock + if ($null -ne $ViewComposerDomainAdministratorID) { + $ViewComposerDomainAdministratorID = $ViewComposerDomainAdministratorID[0].id + } elseif ($null -ne $lcDomainAdministrators) { + $ViewComposerDomainAdministratorID = $lcDomainAdministrators[0].id + } + if ($null -eq $ViewComposerDomainAdministratorID) { + throw "No Composer Domain Administrator found with netBiosName: [$netBiosName]" + } + + #Support only Sysprep Customization + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings = New-Object VMware.Hv.FarmSysprepCustomizationSettings + $sysprepCustomizationSettings = $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings + + # Get SysPrep CustomizationSpec ID + $CustomizationSpec_service_helper = New-Object VMware.Hv.CustomizationSpecService + $sysPrepIds = $CustomizationSpec_service_helper.CustomizationSpec_List($services, $vcID) | Where-Object { $_.customizationSpecData.name -eq $sysPrepName } | Select-Object -Property id + if ($sysPrepIds.Count -eq 0) { + throw "No Sysprep Customization spec found with Name: [$sysPrepName]" + } + $sysprepCustomizationSettings.CustomizationSpec = $sysPrepIds[0].id + + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CustomizationType = 'SYS_PREP' + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.DomainAdministrator = $ViewComposerDomainAdministratorID + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.ReusePreExistingAccounts = $reusePreExistingAccounts + $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings = $sysprepCustomizationSettings + $customObject = $farmSpecObj.AutomatedFarmSpec.CustomizationSettings } - $sysprepCustomizationSettings.CustomizationSpec = $sysPrepIds[0].id - - $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.CustomizationType = 'SYS_PREP' - $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.DomainAdministrator = $ViewComposerDomainAdministratorID - $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.AdContainer = $adContainerId - $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.ReusePreExistingAccounts = $false - $farmSpecObj.AutomatedFarmSpec.CustomizationSettings.SysprepCustomizationSettings = $sysprepCustomizationSettings - - $customObject = $farmSpecObj.AutomatedFarmSpec.CustomizationSettings } return $customObject } @@ -2454,12 +3074,16 @@ function Get-FarmSpec { if ($farmType -eq 'AUTOMATED') { $farm_spec_helper.getDataObject().AutomatedFarmSpec.RdsServerNamingSpec.PatternNamingSettings = $farm_helper.getFarmPatternNamingSettingsHelper().getDataObject() $farm_spec_helper.getDataObject().AutomatedFarmSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings = $farm_helper.getFarmViewComposerStorageSettingsHelper().getDataObject() - } elseif ($farmType -eq 'MANUAL') { - # No need to set + + } + $farm_spec_helper.getDataObject().Data.Settings = $farm_helper.getFarmSessionSettingsHelper().getDataObject() + $farm_spec_helper.getDataObject().Data.DisplayProtocolSettings = $farm_helper.getFarmDisplayProtocolSettingsHelper().getDataObject() + $farm_spec_helper.getDataObject().Data.MirageConfigurationOverrides = $farm_helper.getFarmMirageConfigurationOverridesHelper( ).getDataObject() return $farm_spec_helper.getDataObject() } + function New-HVPool { <# .Synopsis @@ -2518,6 +3142,78 @@ function New-HVPool { This is a list of tags that access to the desktop is restricted to. No list means that the desktop can be accessed from any connection server. +.PARAMETER PowerPolicy + Power policy for the machines in the desktop after logoff. + This setting is only relevant for managed machines + +.PARAMETER AutomaticLogoffPolicy + Automatically log-off policy after disconnect. + This property has a default value of "NEVER". + +.PARAMETER AutomaticLogoffMinutes + The timeout in minutes for automatic log-off after disconnect. + This property is required if automaticLogoffPolicy is set to "AFTER". + +.PARAMETER AllowUsersToResetMachines + Whether users are allowed to reset/restart their machines. + +.PARAMETER AllowMultipleSessionsPerUser + Whether multiple sessions are allowed per user in case of Floating User Assignment. + +.PARAMETER DeleteOrRefreshMachineAfterLogoff + Whether machines are to be deleted or refreshed after logoff in case of Floating User Assignment. + +.PARAMETER RefreshOsDiskAfterLogoff + Whether and when to refresh the OS disks for dedicated-assignment, linked-clone machines. + +.PARAMETER RefreshPeriodDaysForReplicaOsDisk + Regular interval at which to refresh the OS disk. + +.PARAMETER RefreshThresholdPercentageForReplicaOsDisk + With the 'AT_SIZE' option for refreshOsDiskAfterLogoff, the size of the linked clone's OS disk in the datastore is compared to its maximum allowable size. + +.PARAMETER SupportedDisplayProtocols + The list of supported display protocols for the desktop. + +.PARAMETER DefaultDisplayProtocol + The default display protocol for the desktop. For a managed desktop, this will default to "PCOIP". For an unmanaged desktop, this will default to "RDP". + +.PARAMETER AllowUsersToChooseProtocol + Whether the users can choose the protocol. + +.PARAMETER Renderer3D + Specify 3D rendering dependent types hardware, software, vsphere client etc. + +.PARAMETER EnableGRIDvGPUs + Whether GRIDvGPUs enabled or not + +.PARAMETER VRamSizeMB + VRAM size for View managed 3D rendering. More VRAM can improve 3D performance. + +.PARAMETER MaxNumberOfMonitors + The greater these values are, the more memory will be consumed on the associated ESX hosts + +.PARAMETER MaxResolutionOfAnyOneMonitor + The greater these values are, the more memory will be consumed on the associated ESX hosts. + +.PARAMETER EnableHTMLAccess + HTML Access, enabled by VMware Blast technology, allows users to connect to View machines from Web browsers. + +.PARAMETER Quality + This setting determines the image quality that the flash movie will render. Lower quality results in less bandwidth usage. + +.PARAMETER Throttling + This setting affects the frame rate of the flash movie. If enabled, the frames per second will be reduced based on the aggressiveness level. + +.PARAMETER OverrideGlobalSetting + Mirage configuration specified here will be used for this Desktop + +.PARAMETER Enabled + Whether a Mirage server is enabled. + +.PARAMETER Url + The URL of the Mirage server. This should be in the form "<(DNS name)|(IPv4)|(IPv6)><:(port)>". IPv6 addresses must be enclosed in square brackets. + .PARAMETER Vcenter Virtual Center server-address (IP or FQDN) where the pool virtual machines are located. This should be same as provided to the Connection Server while adding the vCenter server. @@ -2552,6 +3248,60 @@ function New-HVPool { Whether to use vSphere VSAN. This is applicable for vSphere 5.5 or later. Applicable to Full, Linked, Instant Clone Pools. +.PARAMETER UseSeparateDatastoresReplicaAndOSDisks + Whether to use separate datastores for replica and OS disks. + +.PARAMETER ReplicaDiskDatastore + Datastore to store replica disks for View Composer and Instant clone engine sourced machines. + +.PARAMETER UseNativeSnapshots + Native NFS Snapshots is a hardware feature, specify whether to use or not + +.PARAMETER ReclaimVmDiskSpace + virtual machines can be configured to use a space efficient disk format that supports reclamation of unused disk space. + +.PARAMETER ReclamationThresholdGB + Initiate reclamation when unused space on VM exceeds the threshold. + +.PARAMETER RedirectWindowsProfile + Windows profiles will be redirected to persistent disks, which are not affected by View Composer operations such as refresh, recompose and rebalance. + +.PARAMETER UseSeparateDatastoresPersistentAndOSDisks + Whether to use separate datastores for persistent and OS disks. This must be false if redirectWindowsProfile is false. + +.PARAMETER PersistentDiskDatastores + Name of the Persistent disk datastore + +.PARAMETER PersistentDiskStorageOvercommit + Storage overcommit determines how view places new VMs on the selected datastores. + +.PARAMETER DiskSizeMB + Size of the persistent disk in MB. + +.PARAMETER DiskDriveLetter + Persistent disk drive letter. + +.PARAMETER RedirectDisposableFiles + Redirect disposable files to a non-persistent disk that will be deleted automatically when a user's session ends. + +.PARAMETER NonPersistentDiskSizeMB + Size of the non persistent disk in MB. + +.PARAMETER NonPersistentDiskDriveLetter + Non persistent disk drive letter. + +.PARAMETER UseViewStorageAccelerator + Whether to use View Storage Accelerator. + +.PARAMETER ViewComposerDiskTypes + Disk types to enable for the View Storage Accelerator feature. + +.PARAMETER RegenerateViewStorageAcceleratorDays + How often to regenerate the View Storage Accelerator cache. + +.PARAMETER BlackoutTimes + A list of blackout times. + .PARAMETER StopOnProvisioningError Set to true to stop provisioning of all VMs on error. Applicable to Full, Linked, Instant Clone Pools. @@ -2637,6 +3387,22 @@ function New-HVPool { The customization spec to use. Applicable to Full, Linked Clone Pools. +.PARAMETER PowerOffScriptName + Power off script. ClonePrep/QuickPrep can run a customization script on instant/linked clone machines before they are powered off. Provide the path to the script on the parent virtual machine. + Applicable to Linked, Instant Clone pools. + +.PARAMETER PowerOffScriptParameters + Power off script parameters. Example: p1 p2 p3 + Applicable to Linked, Instant Clone pools. + +.PARAMETER PostSynchronizationScriptName + Post synchronization script. ClonePrep/QuickPrep can run a customization script on instant/linked clone machines after they are created or recovered or a new image is pushed. Provide the path to the script on the parent virtual machine. + Applicable to Linked, Instant Clone pools. + +.PARAMETER PostSynchronizationScriptParameters + Post synchronization script parameters. Example: p1 p2 p3 + Applicable to Linked, Instant Clone pools. + .PARAMETER Source Source of the Virtual machines for manual pool. Supported values are 'VIRTUAL_CENTER','UNMANAGED'. @@ -2660,37 +3426,41 @@ function New-HVPool { .PARAMETER HvServer Reference to Horizon View Server to query the pools from. If the value is not passed or null then - first element from global:DefaultHVServers would be considered inplace of hvServer. + first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE + C:\PS>New-HVPool -LinkedClone -PoolName 'vmwarepool' -UserAssignment FLOATING -ParentVM 'Agent_vmware' -SnapshotVM 'kb-hotfix' -VmFolder 'vmware' -HostOrCluster 'CS-1' -ResourcePool 'CS-1' -Datastores 'datastore1' -NamingMethod PATTERN -PoolDisplayName 'vmware linkedclone pool' -Description 'created linkedclone pool from ps' -EnableProvisioning $true -StopOnProvisioningError $false -NamingPattern "vmware2" -MinReady 0 -MaximumCount 1 -SpareCount 1 -ProvisioningTime UP_FRONT -SysPrepName vmwarecust -CustType SYS_PREP -NetBiosName adviewdev -DomainAdmin root Create new automated linked clone pool with naming method pattern - New-HVPool -LinkedClone -PoolName 'vmwarepool' -UserAssignment FLOATING -ParentVM 'Agent_vmware' -SnapshotVM 'kb-hotfix' -VmFolder 'vmware' -HostOrCluster 'CS-1' -ResourcePool 'CS-1' -Datastores 'datastore1' -NamingMethod PATTERN -PoolDisplayName 'vmware linkedclone pool' -Description 'created linkedclone pool from ps' -EnableProvisioning $true -StopOnProvisioningError $false -NamingPattern "vmware2" -MinReady 1 -MaximumCount 1 -SpareCount 1 -ProvisioningTime UP_FRONT -SysPrepName vmwarecust -CustType SYS_PREP -NetBiosName adviewdev -DomainAdmin root .EXAMPLE + New-HVPool -Spec C:\VMWare\Specs\LinkedClone.json -Confirm:$false Create new automated linked clone pool by using JSON spec file - New-HVPool -Spec C:\VMWare\Specs\LinkedClone.json .EXAMPLE - Clone new pool from automated linked (or) full clone pool - Get-HVPool -PoolName 'vmwarepool' | New-HVPool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; + C:\PS>Get-HVPool -PoolName 'vmwarepool' | New-HVPool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; (OR) - $vmwarepool = Get-HVPool -PoolName 'vmwarepool'; New-HVPool -ClonePool $vmwarepool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; + C:\PS>$vmwarepool = Get-HVPool -PoolName 'vmwarepool'; New-HVPool -ClonePool $vmwarepool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; + Clones new pool by using existing pool configuration .EXAMPLE - Create new automated instant clone pool with naming method pattern New-HVPool -InstantClone -PoolName "InsPoolvmware" -PoolDisplayName "insPool" -Description "create instant pool" -UserAssignment FLOATING -ParentVM 'Agent_vmware' -SnapshotVM 'kb-hotfix' -VmFolder 'vmware' -HostOrCluster 'CS-1' -ResourcePool 'CS-1' -NamingMethod PATTERN -Datastores 'datastore1' -NamingPattern "inspool2" -NetBiosName 'adviewdev' -DomainAdmin root + Create new automated instant clone pool with naming method pattern .EXAMPLE - Create new automated full clone pool with naming method pattern New-HVPool -FullClone -PoolName "FullClone" -PoolDisplayName "FullClonePra" -Description "create full clone" -UserAssignment DEDICATED -Template 'powerCLI-VM-TEMPLATE' -VmFolder 'vmware' -HostOrCluster 'CS-1' -ResourcePool 'CS-1' -Datastores 'datastore1' -NamingMethod PATTERN -NamingPattern 'FullCln1' -SysPrepName vmwarecust -CustType SYS_PREP -NetBiosName adviewdev -DomainAdmin root + Create new automated full clone pool with naming method pattern .EXAMPLE - Create new managed manual pool from virtual center managed VirtualMachines. New-HVPool -MANUAL -PoolName 'manualVMWare' -PoolDisplayName 'MNLPUL' -Description 'Manual pool creation' -UserAssignment FLOATING -Source VIRTUAL_CENTER -VM 'PowerCLIVM1', 'PowerCLIVM2' + Create new managed manual pool from virtual center managed VirtualMachines. .EXAMPLE - Create new unmanaged manual pool from unmanaged VirtualMachines. New-HVPool -MANUAL -PoolName 'unmangedVMWare' -PoolDisplayName 'unMngPl' -Description 'unmanaged Manual Pool creation' -UserAssignment FLOATING -Source UNMANAGED -VM 'myphysicalmachine.vmware.com' + Create new unmanaged manual pool from unmanaged VirtualMachines. + +.EXAMPLE + New-HVPool -spec 'C:\Json\InstantClone.json' -PoolName 'InsPool1'-NamingPattern 'INSPool-' + Creates new instant clone pool by reading few parameters from json and few parameters from command line. .OUTPUTS None @@ -2698,11 +3468,11 @@ function New-HVPool { .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -2746,6 +3516,7 @@ function New-HVPool { [Parameter(Mandatory = $true,ParameterSetName = 'FULL_CLONE')] [Parameter(Mandatory = $true,ParameterSetName = 'RDS')] [Parameter(Mandatory = $true,ParameterSetName = 'CLONED_POOL')] + [Parameter(Mandatory = $false,ParameterSetName = 'JSON_FILE')] [string] $PoolName, @@ -2771,7 +3542,6 @@ function New-HVPool { #desktopSpec.automatedDesktopSpec.desktopUserAssignment.userAssigment if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE #desktopSpec.manualDesktopSpec.desktopUserAssignment.userAssigment if MANUAL - [Parameter(Mandatory = $true,ParameterSetName = 'MANUAL')] [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] @@ -2798,6 +3568,120 @@ function New-HVPool { [string[]] $ConnectionServerRestrictions, + #desktopSpec.desktopSettings.deleting + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$Deleting = $false, + + #desktopSpec.desktopSettings.logoffSettings.powerPloicy + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('TAKE_NO_POWER_ACTION', 'ALWAYS_POWERED_ON', 'SUSPEND', 'POWER_OFF')] + [string]$PowerPolicy = 'TAKE_NO_POWER_ACTION', + + #desktopSpec.desktopSettings.logoffSettings.powerPloicy + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('IMMEDIATELY', 'NEVER', 'AFTER')] + [string]$AutomaticLogoffPolicy = 'NEVER', + + #desktopSpec.desktopSettings.logoffSettings.automaticLogoffMinutes + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(1,120)] + [int]$AutomaticLogoffMinutes = 120, + + #desktopSpec.desktopSettings.logoffSettings.allowUsersToResetMachines + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$allowUsersToResetMachines = $false, + + #desktopSpec.desktopSettings.logoffSettings.allowMultipleSessionsPerUser + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$allowMultipleSessionsPerUser = $false, + + #desktopSpec.desktopSettings.logoffSettings.deleteOrRefreshMachineAfterLogoff + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('NEVER', 'DELETE', 'AFTER')] + [string]$deleteOrRefreshMachineAfterLogoff = 'NEVER', + + #desktopSpec.desktopSettings.logoffSettings.refreshOsDiskAfterLogoff + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('NEVER', 'ALWAYS', 'EVERY', 'AT_SIZE')] + [string]$refreshOsDiskAfterLogoff = 'NEVER', + + #desktopSpec.desktopSettings.logoffSettings.refreshPeriodDaysForReplicaOsDisk + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [int]$refreshPeriodDaysForReplicaOsDisk = 120, + + #desktopSpec.desktopSettings.logoffSettings.refreshThresholdPercentageForReplicaOsDisk + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(1,100)] + [int]$refreshThresholdPercentageForReplicaOsDisk, + + #DesktopDisplayProtocolSettings + #desktopSpec.desktopSettings.logoffSettings.supportedDisplayProtocols + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('RDP', 'PCOIP', 'BLAST')] + [string[]]$supportedDisplayProtocols = @('RDP', 'PCOIP', 'BLAST'), + + #desktopSpec.desktopSettings.logoffSettings.defaultDisplayProtocol + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('RDP', 'PCOIP', 'BLAST')] + [string]$defaultDisplayProtocol = 'PCOIP', + + #desktopSpec.desktopSettings.logoffSettings.allowUsersToChooseProtocol + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [int]$allowUsersToChooseProtocol = $true, + + #desktopSpec.desktopSettings.logoffSettings.enableHTMLAccess + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$enableHTMLAccess = $false, + + # DesktopPCoIPDisplaySettings + #desktopSpec.desktopSettings.logoffSettings.pcoipDisplaySettings.renderer3D + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('MANAGE_BY_VSPHERE_CLIENT', 'AUTOMATIC', 'SOFTWARE', 'HARDWARE', 'DISABLED')] + [string]$renderer3D = 'DISABLED', + + #desktopSpec.desktopSettings.logoffSettings.pcoipDisplaySettings.enableGRIDvGPUs + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$enableGRIDvGPUs = $false, + + #desktopSpec.desktopSettings.logoffSettings.pcoipDisplaySettings.vRamSizeMB + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(64,512)] + [int]$vRamSizeMB = 96, + + #desktopSpec.desktopSettings.logoffSettings.pcoipDisplaySettings.maxNumberOfMonitors + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(1,4)] + [int]$maxNumberOfMonitors = 2, + + #desktopSpec.desktopSettings.logoffSettings.pcoipDisplaySettings.maxResolutionOfAnyOneMonitor + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('WUXGA', 'WSXGA_PLUS', 'WQXGA', 'UHD')] + [string]$maxResolutionOfAnyOneMonitor = 'WUXGA', + + # flashSettings + #desktopSpec.desktopSettings.flashSettings.quality + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('NO_CONTROL', 'LOW', 'MEDIUM', 'HIGH')] + [string]$quality = 'NO_CONTROL', + + #desktopSpec.desktopSettings.flashSettings.throttling + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateSet('DISABLED', 'CONSERVATIVE', 'MODERATE', 'AGGRESSIVE')] + [string]$throttling = 'DISABLED', + + #mirageConfigurationOverrides + #desktopSpec.desktopSettings.mirageConfigurationOverrides.overrideGlobalSetting + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$overrideGlobalSetting = $false, + + #desktopSpec.desktopSettings.mirageConfigurationOverrides.enabled + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean]$enabled = $true, + + #desktopSpec.desktopSettings.mirageConfigurationOverrides.url + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [string]$url = $true, + #desktopSpec.automatedDesktopSpec.virtualCenter if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE #desktopSpec.manualDesktopSpec.virtualCenter if MANUAL [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] @@ -2845,6 +3729,13 @@ function New-HVPool { [string] $ResourcePool, + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.datacenter if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] + [string] + $datacenter, + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastore if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE [Parameter(Mandatory = $true,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $true,ParameterSetName = 'INSTANT_CLONE')] @@ -2852,12 +3743,127 @@ function New-HVPool { [string[]] $Datastores, + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastores.storageOvercommit if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] + [string[]] + $StorageOvercommit = $null, + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.useVSAN if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] + [boolean] + $UseVSAN = $false, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.useSeparateDatastoresReplicaAndOSDisks if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $UseSeparateDatastoresReplicaAndOSDisks = $false, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.replicaDiskDatastore if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [string] - $UseVSAN, + $ReplicaDiskDatastore, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.UseNativeSnapshots if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $UseNativeSnapshots = $false, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.reclaimVmDiskSpace if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $ReclaimVmDiskSpace = $false, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.reclamationThresholdGB if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(0,[Int]::MaxValue)] + [int] + $ReclamationThresholdGB = 1, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.persistentDiskSettings.redirectWindowsProfile if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [boolean] + $RedirectWindowsProfile = $true, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.persistentDiskSettings.useSeparateDatastoresPersistentAndOSDisks if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean] + $UseSeparateDatastoresPersistentAndOSDisks = $false, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.persistentDiskSettings.PersistentDiskDatastores if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [string[]] + $PersistentDiskDatastores, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.persistentDiskSettings.PersistentDiskDatastores if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [string[]] + $PersistentDiskStorageOvercommit = $null, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.persistentDiskSettings.diskSizeMB if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(128,[Int]::MaxValue)] + [int] + $DiskSizeMB = 2048, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.persistentDiskSettings.diskDriveLetter if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidatePattern("^[D-Z]$")] + [string] + $DiskDriveLetter = "D", + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.nonPersistentDiskSettings.redirectDisposableFiles if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean] + $redirectDisposableFiles, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.nonPersistentDiskSettings.diskSizeMB if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(512,[Int]::MaxValue)] + [int] + $NonPersistentDiskSizeMB = 4096, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.nonPersistentDiskSettings.diskDriveLetter if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidatePattern("^[D-Z]|Auto$")] + [string] + $NonPersistentDiskDriveLetter = "Auto", + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewStorageAcceleratorSettings.useViewStorageAccelerator if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [boolean] + $UseViewStorageAccelerator = $false, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewStorageAcceleratorSettings.useViewStorageAccelerator if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [string] + $ViewComposerDiskTypes = "OS_DISKS", + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewStorageAcceleratorSettings.regenerateViewStorageAcceleratorDays if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [ValidateRange(1,999)] + [int] + $RegenerateViewStorageAcceleratorDays = 7, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewStorageAcceleratorSettings.blackoutTimes if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [VMware.Hv.DesktopBlackoutTime[]] + $BlackoutTimes, + + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterNetworkingSettings.nics + [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] + [VMware.Hv.DesktopNetworkInterfaceCardSettings[]] + $Nics, #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.enableProvsioning if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] @@ -2894,6 +3900,7 @@ function New-HVPool { [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = 'CLONED_POOL')] + [Parameter(Mandatory = $false,ParameterSetName = 'JSON_FILE')] [string] $NamingPattern = $poolName + '{n:fixed=4}', @@ -2963,6 +3970,8 @@ function New-HVPool { [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] [string]$NetBiosName, + #desktopSpec.automatedDesktopSpec.customizationSettings.domainAdministrator + #desktopSpec.automatedDesktopSpec.customizationSettings.cloneprepCustomizationSettings.instantCloneEngineDomainAdministrator [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] [string]$DomainAdmin = $null, @@ -2974,12 +3983,50 @@ function New-HVPool { [string] $CustType, + #desktopSpec.automatedDesktopSpec.customizationSettings.reusePreExistingAccounts if LINKED_CLONE + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [Boolean] + $ReusePreExistingAccounts = $false, + #desktopSpec.automatedDesktopSpec.customizationSettings.sysprepCustomizationSettings.customizationSpec if LINKED_CLONE, FULL_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $false,ParameterSetName = "FULL_CLONE")] [string] $SysPrepName, + #desktopSpec.automatedDesktopSpec.customizationSettings.noCustomizationSettings.doNotPowerOnVMsAfterCreation if FULL_CLONE + [Parameter(Mandatory = $false,ParameterSetName = "FULL_CLONE")] + [boolean] + $DoNotPowerOnVMsAfterCreation = $false, + + #desktopSpec.automatedDesktopSpec.customizationSettings.quickprepCustomizationSettings.powerOffScriptName if LINKED_CLONE, INSTANT_CLONE + #desktopSpec.automatedDesktopSpec.customizationSettings.cloneprepCustomizationSettings.powerOffScriptName + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [string] + $PowerOffScriptName, + + #desktopSpec.automatedDesktopSpec.customizationSettings.quickprepCustomizationSettings.powerOffScriptParameters + #desktopSpec.automatedDesktopSpec.customizationSettings.cloneprepCustomizationSettings.powerOffScriptParameters + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [string] + $PowerOffScriptParameters, + + #desktopSpec.automatedDesktopSpec.customizationSettings.quickprepCustomizationSettings.postSynchronizationScriptName + #desktopSpec.automatedDesktopSpec.customizationSettings.cloneprepCustomizationSettings.postSynchronizationScriptName + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [string] + $PostSynchronizationScriptName, + + #desktopSpec.automatedDesktopSpec.customizationSettings.quickprepCustomizationSettings.postSynchronizationScriptParameters + #desktopSpec.automatedDesktopSpec.customizationSettings.cloneprepCustomizationSettings.postSynchronizationScriptParameters + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [string] + $PostSynchronizationScriptParameters, + #manual desktop [Parameter(Mandatory = $true,ParameterSetName = 'MANUAL')] [ValidateSet('VIRTUAL_CENTER','UNMANAGED')] @@ -2988,10 +4035,13 @@ function New-HVPool { [Parameter(Mandatory = $true,ParameterSetName = 'MANUAL')] [Parameter(Mandatory = $false,ParameterSetName = "JSON_FILE")] + [Parameter(Mandatory = $false,ParameterSetName = 'CLONED_POOL')] [string[]]$VM, #farm [Parameter(Mandatory = $false,ParameterSetName = 'RDS')] + [Parameter(Mandatory = $false,ParameterSetName = 'CLONED_POOL')] + [string] $Farm, @@ -3057,12 +4107,12 @@ function New-HVPool { } process { - + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys if ($poolName) { try { - $sourcePool = Get-HVPoolSummary -poolName $poolName -hvServer $hvServer + $sourcePool = Get-HVPoolSummary -poolName $poolName -suppressInfo $true -hvServer $hvServer } catch { - Write-Error "Make sure Get-HVPool advanced function is loaded, $_" + Write-Error "Make sure Get-HVPoolSummary advanced function is loaded, $_" break } if ($sourcePool) { @@ -3078,6 +4128,14 @@ function New-HVPool { Write-Error "Json file exception, $_" break } + + try { + #Json object validation + Test-HVPoolSpec -PoolObject $jsonObject + } catch { + Write-Error "Json object validation failed, $_" + break + } if ($jsonObject.type -eq "AUTOMATED") { $poolType = 'AUTOMATED' if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenter) { @@ -3094,18 +4152,43 @@ function New-HVPool { $custType = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CustomizationType if ($jsonObject.AutomatedDesktopSpec.ProvisioningType -eq "INSTANT_CLONE_ENGINE") { $InstantClone = $true + if ($null -ne $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings) { + $domainAdmin = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.InstantCloneEngineDomainAdministrator + $powerOffScriptName = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.PowerOffScriptName + $powerOffScriptParameters = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.PowerOffScriptParameters + $postSynchronizationScriptName = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.PostSynchronizationScriptName + $postSynchronizationScriptParameters = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.PostSynchronizationScriptParameters + } } else { if ($jsonObject.AutomatedDesktopSpec.ProvisioningType -eq "VIEW_COMPOSER") { $LinkedClone = $true - } else { + $domainAdmin = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.domainAdministrator + } elseIf($jsonObject.AutomatedDesktopSpec.ProvisioningType -eq "VIRTUAL_CENTER") { $FullClone = $true } - $sysPrepName = $jsonObject.SysPrepName + switch ($custType) { + 'SYS_PREP' { + $sysprepCustomizationSettings = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.SysprepCustomizationSettings + $sysPrepName = $sysprepCustomizationSettings.customizationSpec + $reusePreExistingAccounts = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.reusePreExistingAccounts + } + 'QUICK_PREP' { + $powerOffScriptName = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.PowerOffScriptName + $powerOffScriptParameters = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.PowerOffScriptParameters + $postSynchronizationScriptName = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.PostSynchronizationScriptName + $postSynchronizationScriptParameters = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.PostSynchronizationScriptParameters + } + 'NONE' { + $doNotPowerOnVMsAfterCreation = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.NoCustomizationSettings.DoNotPowerOnVMsAfterCreation + } + } } $namingMethod = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.NamingMethod $transparentPageSharingScope = $jsonObject.AutomatedDesktopSpec.virtualCenterManagedCommonSettings.TransparentPageSharingScope if ($namingMethod -eq "PATTERN") { - $namingPattern = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.namingPattern + if ($NamingPattern -eq '{n:fixed=4}') { + $namingPattern = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.namingPattern + } $maximumCount = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.maxNumberOfMachines $spareCount = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.numberOfSpareMachines $provisioningTime = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings.provisioningTime @@ -3114,6 +4197,9 @@ function New-HVPool { $startInMaintenanceMode = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.SpecificNamingSpec.startMachinesInMaintenanceMode $numUnassignedMachinesKeptPoweredOn = $jsonObject.AutomatedDesktopSpec.VmNamingSpec.SpecificNamingSpec.numUnassignedMachinesKeptPoweredOn } + $enableProvisioning = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.EnableProvisioning + $stopProvisioningOnError = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.stopProvisioningOnError + $minReady = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.Template) { $template = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.Template } @@ -3123,14 +4209,87 @@ function New-HVPool { if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.Snapshot) { $snapshotVM = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.Snapshot } + $dataCenter = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.dataCenter $vmFolder = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.VmFolder $hostOrCluster = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.HostOrCluster $resourcePool = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.ResourcePool $dataStoreList = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.Datastores foreach ($dtStore in $dataStoreList) { $datastores += $dtStore.Datastore + $storageOvercommit += $dtStore.StorageOvercommit } - } elseif ($jsonObject.type -eq "MANUAL") { + $useVSan = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.UseVSan + if ($LinkedClone -or $InstantClone) { + $useSeparateDatastoresReplicaAndOSDisks = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.UseSeparateDatastoresReplicaAndOSDisks + if ($useSeparateDatastoresReplicaAndOSDisks) { + $replicaDiskDatastore = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.replicaDiskDatastore + } + if ($LinkedClone) { + #For Instant clone desktops, this setting can only be set to false + $useNativeSnapshots = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.useNativeSnapshots + $reclaimVmDiskSpace = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.spaceReclamationSettings.reclaimVmDiskSpace + if ($reclaimVmDiskSpace) { + $reclamationThresholdGB = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.spaceReclamationSettings.reclamationThresholdGB + } + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings) { + $redirectWindowsProfile = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.RedirectWindowsProfile + if ($redirectWindowsProfile) { + $useSeparateDatastoresPersistentAndOSDisks = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.UseSeparateDatastoresPersistentAndOSDisks + } + $dataStoreList = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.persistentDiskDatastores + foreach ($dtStore in $dataStoreList) { + $persistentDiskDatastores += $dtStore.Datastore + $PersistentDiskStorageOvercommit += $dtStore.StorageOvercommit + } + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.DiskSizeMB) { + $diskSizeMB = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.DiskSizeMB + } + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.DiskDriveLetter) { + $diskDriveLetter = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.PersistentDiskSettings.DiskDriveLetter + } + } + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.nonPersistentDiskSettings) { + $redirectDisposableFiles = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.NonPersistentDiskSettings.RedirectDisposableFiles + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.NonPersistentDiskSettings.DiskSizeMB) { + $nonPersistentDiskSizeMB = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.NonPersistentDiskSettings.DiskSizeMB + } + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.NonPersistentDiskSettings.DiskDriveLetter) { + $nonPersistentDiskDriveLetter = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings.NonPersistentDiskSettings.DiskDriveLetter + } + } + } else { + $useNativeSnapshots = $false + $redirectWindowsProfile = $false + } + } + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings) { + $useViewStorageAccelerator = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.UseViewStorageAccelerator + if ($useViewStorageAccelerator -and $LinkedClone) { + $viewComposerDiskTypes = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.ViewComposerDiskTypes + } + if (! $InstantClone -and $useViewStorageAccelerator) { + $regenerateViewStorageAcceleratorDays = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.RegenerateViewStorageAcceleratorDays + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.blackoutTimes) { + $blackoutTimesList =$jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.blackoutTimes + foreach ($blackout in $blackoutTimesList) { + $blackoutObj = New-Object VMware.Hv.DesktopBlackoutTime + $blackoutObj.Days = $blackout.Days + $blackoutObj.StartTime = $blackout.StartTime + $blackoutObj.EndTime = $blackoutObj.EndTime + $blackoutTimes += $blackoutObj + } + } + } + } + <# ToDo Nic + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.nics) { + $nicList = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.nics + foreach($nicObj in $nicList) { + $nic = New-Object VMware.Hv.DesktopNetworkInterfaceCardSettings + } + } + #> + } elseIf ($jsonObject.type -eq "MANUAL") { $MANUAL = $true $poolType = 'MANUAL' $userAssignment = $jsonObject.ManualDesktopSpec.userAssignment.userAssignment @@ -3149,21 +4308,87 @@ function New-HVPool { $poolDisplayName = $jsonObject.base.DisplayName $description = $jsonObject.base.Description $accessGroup = $jsonObject.base.AccessGroup - $poolName = $jsonObject.base.name + if (!$poolName) { + $poolName = $jsonObject.base.name + } + + <# + # Populate desktop settings + #> + if ($null -ne $jsonObject.DesktopSettings) { + $Enable = $jsonObject.DesktopSettings.enabled + $deleting = $jsonObject.DesktopSettings.deleting + if ($null -ne $jsonObject.DesktopSettings.connectionServerRestrictions) { + $ConnectionServerRestrictions = $jsonObject.DesktopSettings.connectionServerRestrictions + } + if ($poolType -ne 'RDS') { + if ($null -ne $jsonObject.DesktopSettings.logoffSettings) { + $powerPolicy = $jsonObject.DesktopSettings.logoffSettings.powerPolicy + $automaticLogoffPolicy = $jsonObject.DesktopSettings.logoffSettings.automaticLogoffPolicy + if ($null -ne $jsonObject.DesktopSettings.logoffSettings.automaticLogoffMinutes) { + $automaticLogoffMinutes = $jsonObject.DesktopSettings.logoffSettings.automaticLogoffMinutes + } + $allowUsersToResetMachines = $jsonObject.DesktopSettings.logoffSettings.allowUsersToResetMachines + $allowMultipleSessionsPerUser = $jsonObject.DesktopSettings.logoffSettings.allowMultipleSessionsPerUser + $deleteOrRefreshMachineAfterLogoff = $jsonObject.DesktopSettings.logoffSettings.deleteOrRefreshMachineAfterLogoff + $refreshOsDiskAfterLogoff = $jsonObject.DesktopSettings.logoffSettings.refreshOsDiskAfterLogoff + if ($jsonObject.DesktopSettings.logoffSettings.refreshPeriodDaysForReplicaOsDisk) { + $refreshPeriodDaysForReplicaOsDisk = $jsonObject.DesktopSettings.logoffSettings.refreshPeriodDaysForReplicaOsDisk + } + if ($jsonObject.DesktopSettings.logoffSettings.refreshThresholdPercentageForReplicaOsDisk) { + $refreshThresholdPercentageForReplicaOsDisk = $jsonObject.DesktopSettings.logoffSettings.refreshThresholdPercentageForReplicaOsDisk + } + } + + if ($null -ne $jsonObject.DesktopSettings.displayProtocolSettings) { + $supportedDisplayProtocols = $jsonObject.DesktopSettings.displayProtocolSettings.supportedDisplayProtocols + $defaultDisplayProtocol = $jsonObject.DesktopSettings.displayProtocolSettings.defaultDisplayProtocol + $allowUsersToChooseProtocol = $jsonObject.DesktopSettings.displayProtocolSettings.allowUsersToChooseProtocol + if ($null -ne $jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings) { + $renderer3D = $jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings.renderer3D + $enableGRIDvGPUs = $jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings.enableGRIDvGPUs + if ($jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings.vRamSizeMB) { + $vRamSizeMB = $jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings.vRamSizeMB + } + $maxNumberOfMonitors = $jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings.maxNumberOfMonitors + $maxResolutionOfAnyOneMonitor = $jsonObject.DesktopSettings.displayProtocolSettings.pcoipDisplaySettings.maxResolutionOfAnyOneMonitor + } + $enableHTMLAccess = $jsonObject.DesktopSettings.displayProtocolSettings.enableHTMLAccess + } + + if ($null -ne $jsonObject.DesktopSettings.mirageConfigurationOverrides) { + $overrideGlobalSetting = $jsonObject.DesktopSettings.mirageConfigurationOverrides.overrideGlobalSetting + if ($jsonObject.DesktopSettings.mirageConfigurationOverrides.enabled) { + $enabled = $jsonObject.DesktopSettings.mirageConfigurationOverrides.enabled + } + if ($jsonObject.DesktopSettings.mirageConfigurationOverrides.url) { + $url = $jsonObject.DesktopSettings.mirageConfigurationOverrides.url + } + } + } + if ($null -ne $jsonObject.DesktopSettings.flashSettings) { + $quality = $jsonObject.DesktopSettings.flashSettings.quality + $throttling = $jsonObject.DesktopSettings.flashSettings.throttling + } + #desktopsettings ends + } + if ($null -ne $jsonObject.GlobalEntitlementData) { + $globalEntitlement = $jsonObject.GlobalEntitlementData.globalEntitlement + } } if ($PSCmdlet.MyInvocation.ExpectingInput -or $clonePool) { if ($clonePool -and ($clonePool.GetType().name -eq 'DesktopSummaryView')) { $clonePool = Get-HVPool -poolName $clonePool.desktopsummarydata.name - } elseif (!($clonePool -and ($clonePool.GetType().name -eq 'DesktopInfo'))) { + } elseIf (!($clonePool -and ($clonePool.GetType().name -eq 'DesktopInfo'))) { Write-Error "In pipeline did not get object of expected type DesktopSummaryView/DesktopInfo" return } $poolType = $clonePool.type $desktopBase = $clonePool.base $desktopSettings = $clonePool.DesktopSettings - $provisioningType = $null + $provisioningType = $clonePool.source if ($clonePool.AutomatedDesktopData) { $provisioningType = $clonePool.AutomatedDesktopData.ProvisioningType $virtualCenterID = $clonePool.AutomatedDesktopData.VirtualCenter @@ -3173,11 +4398,30 @@ function New-HVPool { $DesktopVirtualCenterProvisioningData = $DesktopVirtualCenterProvisioningSettings.VirtualCenterProvisioningData $DesktopVirtualCenterStorageSettings = $DesktopVirtualCenterProvisioningSettings.VirtualCenterStorageSettings $DesktopVirtualCenterNetworkingSettings = $DesktopVirtualCenterProvisioningSettings.VirtualCenterNetworkingSettings - $desktopVirtualCenterManagedCommonSettings = $clonePool.AutomatedDesktopData.virtualCenterManagedCommonSettings - $desktopCustomizationSettings = $clonePool.AutomatedDesktopData.CustomizationSettings + $DesktopVirtualCenterManagedCommonSettings = $clonePool.AutomatedDesktopData.virtualCenterManagedCommonSettings + $DesktopCustomizationSettings = $clonePool.AutomatedDesktopData.CustomizationSettings + $CurrentImageState =` + $clonePool.AutomatedDesktopData.provisioningStatusData.instantCloneProvisioningStatusData.instantCloneCurrentImageState } - if (($null -eq $provisioningType) -or ($provisioningType -eq 'INSTANT_CLONE_ENGINE')) { - Write-Error "Only Automated linked clone or full clone pool support cloning" + elseIf ($clonePool.ManualDesktopData) { + if (! $VM) { + Write-Error "ManualDesktop pool cloning requires list of machines, parameter VM is empty" + break + } + $source = $clonePool.source + $virtualCenterID = $clonePool.ManualDesktopData.VirtualCenter + $desktopUserAssignment = $clonePool.ManualDesktopData.userAssignment + $desktopVirtualCenterStorageSettings = $clonePool.ManualDesktopData.viewStorageAcceleratorSettings + $desktopVirtualCenterManagedCommonSettings = $clonePool.ManualDesktopData.virtualCenterManagedCommonSettings + } + elseIf($clonePool.RdsDesktopData) { + if (! $Farm) { + Write-Error "RdsDesktop pool cloning requires farm, parameter Farm is not set" + break + } + } + if ($provisioningType -eq 'INSTANT_CLONE_ENGINE' -and $poolType -eq 'AUTOMATED' -and $CurrentImageState -ne 'READY') { + Write-Error "Instant clone pool's Current Image State should be in 'READY' state, otherwise cloning is not supported" break } } else { @@ -3186,19 +4430,19 @@ function New-HVPool { $poolType = 'AUTOMATED' $provisioningType = 'INSTANT_CLONE_ENGINE' } - elseif ($LinkedClone) { + elseIf ($LinkedClone) { $poolType = 'AUTOMATED' $provisioningType = 'VIEW_COMPOSER' } - elseif ($FullClone) { + elseIf ($FullClone) { $poolType = 'AUTOMATED' $provisioningType = 'VIRTUAL_CENTER' } - elseif ($Manual) { $poolType = 'MANUAL' } - elseif ($RDS) { $poolType = 'RDS' } + elseIf ($Manual) { $poolType = 'MANUAL' } + elseIf ($RDS) { $poolType = 'RDS' } } - $script:desktopSpecObj = Get-HVDesktopSpec -poolType $poolType -provisioningType $provisioningType -namingMethod $namingMethod + $script:desktopSpecObj = Get-DesktopSpec -poolType $poolType -provisioningType $provisioningType -namingMethod $namingMethod # # accumulate properties that are shared among various type @@ -3256,8 +4500,8 @@ function New-HVPool { { 'RDS' { <# - Query FarmId from Farm Name - #> + Query FarmId from Farm Name + #> $QueryFilterEquals = New-Object VMware.Hv.QueryFilterEquals $QueryFilterEquals.memberName = 'data.name' $QueryFilterEquals.value = $farm @@ -3289,6 +4533,9 @@ function New-HVPool { $machineList = Get-RegisteredPhysicalMachine -services $services -machinesList $VM } $desktopSpecObj.ManualDesktopSpec.Machines = $machineList + if ($desktopUserAssignment) { + $desktopSpecObj.ManualDesktopSpec.userAssignment = $desktopUserAssignment + } } default { if (!$desktopVirtualMachineNamingSpec) { @@ -3332,7 +4579,9 @@ function New-HVPool { try { $desktopVirtualCenterProvisioningData = Get-HVPoolProvisioningData -vc $virtualCenterID -vmObject $desktopVirtualCenterProvisioningData $hostClusterId = $desktopVirtualCenterProvisioningData.HostOrCluster - $desktopVirtualCenterStorageSettings = Get-HVPoolStorageObject -hostclusterID $hostClusterId -storageObject $desktopVirtualCenterStorageSettings + $hostOrCluster_helper = New-Object VMware.Hv.HostOrClusterService + $hostClusterIds = (($hostOrCluster_helper.HostOrCluster_GetHostOrClusterTree($services, $desktopVirtualCenterProvisioningData.datacenter)).treeContainer.children.info).Id + $desktopVirtualCenterStorageSettings = Get-HVPoolStorageObject -hostClusterIds $hostClusterId -storageObject $desktopVirtualCenterStorageSettings $DesktopVirtualCenterNetworkingSettings = Get-HVPoolNetworkSetting -networkObject $DesktopVirtualCenterNetworkingSettings $desktopCustomizationSettings = Get-HVPoolCustomizationSetting -vc $virtualCenterID -customObject $desktopCustomizationSettings } catch { @@ -3341,10 +4590,10 @@ function New-HVPool { break } - if (!$DesktopVirtualCenterProvisioningSettings) { - $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.enableProvisioning = $true - $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.stopProvisioningOnError = $true - $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance = 0 + if (! $DesktopVirtualCenterProvisioningSettings) { + $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.enableProvisioning = $enableProvisioning + $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.stopProvisioningOnError = $stopProvisioningOnError + $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.minReadyVMsOnVComposerMaintenance = $minReady $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData = $desktopVirtualCenterProvisioningData $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings = $desktopVirtualCenterStorageSettings $desktopSpecObj.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterNetworkingSettings = $DesktopVirtualCenterNetworkingSettings @@ -3385,8 +4634,83 @@ function New-HVPool { $desktopSpecObj.base.Description = $description $desktopSpecObj.type = $poolType - if ($desktopSettings) { $desktopSpecObj.DesktopSettings = $desktopSettings } + if (! $desktopSettings) { + $desktopSettingsService = New-Object VMware.Hv.DesktopService + $desktopSettingsHelper = $desktopSettingsService.getDesktopSettingsHelper() + $desktopSettingsHelper.setEnabled($Enable) + $desktopSettingsHelper.setConnectionServerRestrictions($ConnectionServerRestrictions) + #$desktopLogoffSettings = New-Object VMware.Hv.DesktopLogoffSettings + $desktopLogoffSettings = $desktopSettingsService.getDesktopLogoffSettingsHelper() + if ($InstantClone) { + $deleteOrRefreshMachineAfterLogoff = "DELETE" + $powerPolicy = "ALWAYS_POWERED_ON" + } + $desktopLogoffSettings.setPowerPolicy($powerPolicy) + $desktopLogoffSettings.setAutomaticLogoffPolicy($automaticLogoffPolicy) + $desktopLogoffSettings.setAutomaticLogoffMinutes($automaticLogoffMinutes) + $desktopLogoffSettings.setAllowUsersToResetMachines($allowUsersToResetMachines) + $desktopLogoffSettings.setAllowMultipleSessionsPerUser($allowMultipleSessionsPerUser) + $desktopLogoffSettings.setDeleteOrRefreshMachineAfterLogoff($deleteOrRefreshMachineAfterLogoff) + $desktopLogoffSettings.setRefreshOsDiskAfterLogoff($refreshOsDiskAfterLogoff) + $desktopLogoffSettings.setRefreshPeriodDaysForReplicaOsDisk($refreshPeriodDaysForReplicaOsDisk) + if ($refreshThresholdPercentageForReplicaOsDisk -and $refreshOsDiskAfterLogoff -eq "AT_SIZE") { + $desktopLogoffSettings.setRefreshThresholdPercentageForReplicaOsDisk($refreshThresholdPercentageForReplicaOsDisk) + } + if ($poolType -ne 'RDS') { + $desktopSettingsHelper.setLogoffSettings($desktopLogoffSettings.getDataObject()) + + $desktopDisplayProtocolSettings = $desktopSettingsService.getDesktopDisplayProtocolSettingsHelper() + #setSupportedDisplayProtocols is not exists, because this property cannot be updated. + $desktopDisplayProtocolSettings.getDataObject().SupportedDisplayProtocols = $supportedDisplayProtocols + $desktopDisplayProtocolSettings.setDefaultDisplayProtocol($defaultDisplayProtocol) + $desktopDisplayProtocolSettings.setEnableHTMLAccess($enableHTMLAccess) + $desktopDisplayProtocolSettings.setAllowUsersToChooseProtocol($allowUsersToChooseProtocol) + + $desktopPCoIPDisplaySettings = $desktopSettingsService.getDesktopPCoIPDisplaySettingsHelper() + $desktopPCoIPDisplaySettings.setRenderer3D($renderer3D) + #setEnableGRIDvGPUs is not exists, because this property cannot be updated. + $desktopPCoIPDisplaySettings.getDataObject().EnableGRIDvGPUs = $enableGRIDvGPUs + $desktopPCoIPDisplaySettings.setVRamSizeMB($vRamSizeMB) + $desktopPCoIPDisplaySettings.setMaxNumberOfMonitors($maxNumberOfMonitors) + $desktopPCoIPDisplaySettings.setMaxResolutionOfAnyOneMonitor($maxResolutionOfAnyOneMonitor) + $desktopDisplayProtocolSettings.setPcoipDisplaySettings($desktopPCoIPDisplaySettings.getDataObject()) + $desktopSettingsHelper.setDisplayProtocolSettings($desktopDisplayProtocolSettings.getDataObject()) + + $desktopMirageConfigOverrides = $desktopSettingsService.getDesktopMirageConfigurationOverridesHelper() + $desktopMirageConfigOverrides.setEnabled($enabled) + $desktopMirageConfigOverrides.setOverrideGlobalSetting($overrideGlobalSetting) + $desktopMirageConfigOverrides.setUrl($url) + $desktopSettingsHelper.setMirageConfigurationOverrides($desktopMirageConfigOverrides.getDataObject()) + $desktopSettings = $desktopSettingsHelper.getDataObject() + } + $desktopFlashSettings = $desktopSettingsService.getDesktopAdobeFlashSettingsHelper() + $desktopFlashSettings.setQuality($quality) + $desktopFlashSettings.setThrottling($throttling) + $desktopSettingsHelper.setFlashSettings($desktopFlashSettings.getDataObject()) + } + + $desktopSpecObj.DesktopSettings = $desktopSettings + $info = $services.PodFederation.PodFederation_get() + if ($globalEntitlement -and ("ENABLED" -eq $info.localPodStatus.status)) { + $QueryFilterEquals = New-Object VMware.Hv.QueryFilterEquals + $QueryFilterEquals.memberName = 'base.displayName' + $QueryFilterEquals.value = $globalEntitlement + $defn = New-Object VMware.Hv.QueryDefinition + $defn.queryEntityType = 'GlobalEntitlementSummaryView' + $defn.Filter = $QueryFilterEquals + $query_service_helper = New-Object VMware.Hv.QueryServiceService + try { + $queryResults = $query_service_helper.QueryService_Query($services,$defn) + $globalEntitlementid = $queryResults.Results.id + if ($globalEntitlementid.length -eq 1) { + $desktopGlobalEntitlementData = New-Object VMware.Hv.DesktopGlobalEntitlementData -Property @{'globalEntitlement'= $globalEntitlementid;} + } + } + catch { + Write-Host "GlobalEntitlement " $_ + } + } if ($desktopAutomatedDesktopSpec) { $desktopSpecObj.AutomatedDesktopSpec = $desktopAutomatedDesktopSpec } @@ -3396,18 +4720,28 @@ function New-HVPool { # Please uncomment below code, if you want save desktopSpec object to json file <# - $myDebug = convertto-json -InputObject $desktopSpecObj -depth 12 - $myDebug | out-file -filepath c:\temp\copieddesktop.json - #> + $myDebug = convertto-json -InputObject $desktopSpecObj -depth 12 + $myDebug | out-file -filepath c:\temp\copieddesktop.json + #> $desktop_helper = New-Object VMware.Hv.DesktopService - $desktop_helper.Desktop_create($services,$desktopSpecObj) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($desktopSpecObj.base.name)) { + $id = $desktop_helper.Desktop_create($services,$desktopSpecObj) + } else { + try { + #DesktopSpec validation + Test-HVPoolSpec -PoolObject $desktopSpecObj + } catch { + Write-Error "DesktopSpec object validation failed, $_" + break + } + } + return $desktopSpecObj } end { $desktopSpecObj = $null [System.gc]::collect() } - } function Get-HVPoolProvisioningData { @@ -3428,6 +4762,12 @@ function Get-HVPoolProvisioningData { } $vmObject.Template = $templateVM.id $dataCenterID = $templateVM.datacenter + if ($dataCenter -and $dataCenterID) { + $VmTemplateInfo = $vm_template_helper.VmTemplate_ListByDatacenter($dataCenterID) + if (! ($VmTemplateInfo.Path -like "/$dataCenter/*")) { + throw "$template not exists in datacenter: [$dataCenter]" + } + } $vmObject.datacenter = $dataCenterID } if ($parentVM) { @@ -3457,7 +4797,9 @@ function Get-HVPoolProvisioningData { $folderList += $folders while ($folderList.Length -gt 0) { $item = $folderList[0] - if ($item -and !$_.folderdata.incompatiblereasons.inuse -and !$_.folderdata.incompatiblereasons.viewcomposerreplicafolder -and ($item.folderdata.name -eq $vmFolder)) { + if ($item -and !$_.folderdata.incompatiblereasons.inuse -and ` + !$_.folderdata.incompatiblereasons.viewcomposerreplicafolder -and ` + (($item.folderdata.path -eq $vmFolder) -or ($item.folderdata.name -eq $vmFolder))) { $vmObject.VmFolder = $item.id break } @@ -3473,7 +4815,7 @@ function Get-HVPoolProvisioningData { if ($hostOrCluster) { $vmFolder_helper = New-Object VMware.Hv.HostOrClusterService $hostClusterList = ($vmFolder_helper.HostOrCluster_GetHostOrClusterTree($services,$vmobject.datacenter)).treeContainer.children.info - $hostClusterObj = $hostClusterList | Where-Object { $_.name -eq $hostOrCluster } + $hostClusterObj = $hostClusterList | Where-Object { ($_.path -eq $hostOrCluster) -or ($_.name -eq $hostOrCluster) } if ($null -eq $hostClusterObj) { throw "No hostOrCluster found with Name: [$hostOrCluster]" } @@ -3482,7 +4824,7 @@ function Get-HVPoolProvisioningData { if ($resourcePool) { $resourcePool_helper = New-Object VMware.Hv.ResourcePoolService $resourcePoolList = $resourcePool_helper.ResourcePool_GetResourcePoolTree($services,$vmobject.HostOrCluster) - $resourcePoolObj = $resourcePoolList | Where-Object { $_.resourcepooldata.name -eq $resourcePool } + $resourcePoolObj = $resourcePoolList | Where-Object { ($_.resourcepooldata.path -eq $resourcePool) -or ($_.resourcepooldata.name -eq $resourcePool) } if ($null -eq $resourcePoolObj) { throw "No hostOrCluster found with Name: [$resourcePool]" } @@ -3493,26 +4835,54 @@ function Get-HVPoolProvisioningData { function Get-HVPoolStorageObject { param( - [Parameter(Mandatory = $false)] - [VMware.Hv.DesktopVirtualCenterStorageSettings]$StorageObject, - [Parameter(Mandatory = $true)] - [VMware.Hv.HostOrClusterId]$HostClusterID + [VMware.Hv.HostOrClusterId[]]$HostClusterIDs, + + [Parameter(Mandatory = $false)] + [VMware.Hv.DesktopVirtualCenterStorageSettings]$StorageObject ) + $datastoreList = $null if (!$storageObject) { + $datastore_helper = New-Object VMware.Hv.DatastoreService + foreach ($hostClusterID in $hostClusterIDs){ + $datastoreList += $datastore_helper.Datastore_ListDatastoresByHostOrCluster($services,$hostClusterID) + } $storageObject = New-Object VMware.Hv.DesktopVirtualCenterStorageSettings $storageAcceleratorList = @{ - 'useViewStorageAccelerator' = $false + 'useViewStorageAccelerator' = $useViewStorageAccelerator } $desktopViewStorageAcceleratorSettings = New-Object VMware.Hv.DesktopViewStorageAcceleratorSettings -Property $storageAcceleratorList $storageObject.viewStorageAcceleratorSettings = $desktopViewStorageAcceleratorSettings - $desktopSpaceReclamationSettings = New-Object VMware.Hv.DesktopSpaceReclamationSettings -Property @{ 'reclaimVmDiskSpace' = $false } + $desktopSpaceReclamationSettings = New-Object VMware.Hv.DesktopSpaceReclamationSettings -Property @{ 'reclaimVmDiskSpace' = $reclaimVmDiskSpace; 'reclamationThresholdGB' = $reclamationThresholdGB} $desktopPersistentDiskSettings = New-Object VMware.Hv.DesktopPersistentDiskSettings -Property @{ 'redirectWindowsProfile' = $false } $desktopNonPersistentDiskSettings = New-Object VMware.Hv.DesktopNonPersistentDiskSettings -Property @{ 'redirectDisposableFiles' = $false } + if ($LinkedClone) { + if ($blackoutTimes) { + $storageObject.viewStorageAcceleratorSettings.BlackoutTimes = $blackoutTimes + } + if ($useViewStorageAccelerator) { + $storageObject.viewStorageAcceleratorSettings.ViewComposerDiskTypes = $viewComposerDiskTypes + $storageObject.viewStorageAcceleratorSettings.RegenerateViewStorageAcceleratorDays = $regenerateViewStorageAcceleratorDays + } + $desktopPersistentDiskSettings.RedirectWindowsProfile = $redirectWindowsProfile + if ($redirectWindowsProfile) { + $desktopPersistentDiskSettings.UseSeparateDatastoresPersistentAndOSDisks = $useSeparateDatastoresPersistentAndOSDisks + $desktopPersistentDiskSettings.DiskSizeMB = $diskSizeMB + $desktopPersistentDiskSettings.DiskDriveLetter = $diskDriveLetter + } + if ($useSeparateDatastoresPersistentAndOSDisks) { + if ($persistentDiskStorageOvercommit -and ($persistentDiskDatastores.Length -ne $persistentDiskStorageOvercommit.Length) ) { + throw "Parameters persistentDiskDatastores length: [$persistentDiskDatastores.Length] and persistentDiskStorageOvercommit length: [$persistentDiskStorageOvercommit.Length] should be of same size" + } + $desktopPersistentDiskSettings.PersistentDiskDatastores = Get_Datastore -DatastoreInfoList $datastoreList -DatastoreNames $PersistentDiskDatastores -DsStorageOvercommit $persistentDiskStorageOvercommit + } + $desktopNonPersistentDiskSettings.RedirectDisposableFiles = $redirectDisposableFiles + $desktopNonPersistentDiskSettings.DiskSizeMB = $nonPersistentDiskSizeMB + $desktopNonPersistentDiskSettings.DiskDriveLetter = $nonPersistentDiskDriveLetter + } $desktopViewComposerStorageSettingsList = @{ - 'useSeparateDatastoresReplicaAndOSDisks' = $false; - 'useNativeSnapshots' = $false; + 'useNativeSnapshots' = $useNativeSnapshots; 'spaceReclamationSettings' = $desktopSpaceReclamationSettings; 'persistentDiskSettings' = $desktopPersistentDiskSettings; 'nonPersistentDiskSettings' = $desktopNonPersistentDiskSettings @@ -3522,17 +4892,13 @@ function Get-HVPoolStorageObject { } } if ($datastores) { - $datastore_helper = New-Object VMware.Hv.DatastoreService - $datastoreList = $datastore_helper.Datastore_ListDatastoresByHostOrCluster($services,$hostClusterID) - $datastoresSelected = @() - foreach ($ds in $datastores) { - $datastoresSelected += ($datastoreList | Where-Object { $_.datastoredata.name -eq $ds }).id + if ($StorageOvercommit -and ($datastores.Length -ne $StorageOvercommit.Length) ) { + throw "Parameters datastores length: [$datastores.Length] and StorageOvercommit length: [$StorageOvercommit.Length] should be of same size" } - foreach ($ds in $datastoresSelected) { - $myDatastores = New-Object VMware.Hv.DesktopVirtualCenterDatastoreSettings - $myDatastores.Datastore = $ds - $mydatastores.StorageOvercommit = 'UNBOUNDED' - $storageObject.Datastores += $myDatastores + $storageObject.Datastores = Get-HVDatastore -DatastoreInfoList $datastoreList -DatastoreNames $datastores -DsStorageOvercommit $StorageOvercommit + if ($useSeparateDatastoresReplicaAndOSDisks) { + $storageObject.ViewComposerStorageSettings.UseSeparateDatastoresReplicaAndOSDisks = $UseSeparateDatastoresReplicaAndOSDisks + $storageObject.ViewComposerStorageSettings.ReplicaDiskDatastore = ($datastoreInfoList | Where-Object { ($_.datastoredata.name -eq $replicaDiskDatastore) -or ($_.datastoredata.path -eq $replicaDiskDatastore)}).id } } if ($storageObject.Datastores.Count -eq 0) { @@ -3542,6 +4908,40 @@ function Get-HVPoolStorageObject { return $storageObject } +function Get-HVDatastore { + param( + [Parameter(Mandatory = $true)] + [VMware.Hv.DatastoreInfo[]] + $DatastoreInfoList, + + [Parameter(Mandatory = $true)] + [string[]] + $DatastoreNames, + + [Parameter(Mandatory = $false)] + [string[]] + $DsStorageOvercommit + + ) + $datastoresSelected = @() + foreach ($ds in $datastoreNames) { + $datastoresSelected += ($datastoreInfoList | Where-Object { ($_.DatastoreData.Path -eq $ds) -or ($_.datastoredata.name -eq $ds) }).id + } + $Datastores = $null + if (! $DsStorageOvercommit) { + $DsStorageOvercommit += 'UNBOUNDED' + } + $StorageOvercommitCnt = 0 + foreach ($ds in $datastoresSelected) { + $myDatastores = New-Object VMware.Hv.DesktopVirtualCenterDatastoreSettings + $myDatastores.Datastore = $ds + $mydatastores.StorageOvercommit = $DsStorageOvercommit[$StorageOvercommitCnt] + $Datastores += $myDatastores + $StorageOvercommitCnt++ + } + return $Datastores +} + function Get-HVPoolNetworkSetting { param( [Parameter(Mandatory = $false)] @@ -3565,9 +4965,17 @@ function Get-HVPoolCustomizationSetting { # View Composer and Instant Clone Engine Active Directory container for QuickPrep and ClonePrep. This must be set for Instant Clone Engine or SVI sourced desktops. if ($InstantClone -or $LinkedClone) { $ad_domain_helper = New-Object VMware.Hv.ADDomainService - $adDomianId = ($ad_domain_helper.ADDomain_List($services) | Where-Object { $_.NetBiosName -eq $netBiosName } | Select-Object -Property id) - if ($null -eq $adDomianId) { - throw "No Domain found with netBiosName: [$netBiosName]" + $ADDomains = $ad_domain_helper.ADDomain_List($services) + if ($netBiosName) { + $adDomianId = ($ADDomains | Where-Object { $_.NetBiosName -eq $netBiosName } | Select-Object -Property id) + if ($null -eq $adDomianId) { + throw "No Domain found with netBiosName: [$netBiosName]" + } + } else { + $adDomianId = ($ADDomains[0] | Select-Object -Property id) + if ($null -eq $adDomianId) { + throw "No Domain configured in view administrator UI" + } } $ad_container_helper = New-Object VMware.Hv.AdContainerService $adContainerId = ($ad_container_helper.ADContainer_ListByDomain($services,$adDomianId.id) | Where-Object { $_.Rdn -eq $adContainer } | Select-Object -Property id).id @@ -3579,29 +4987,53 @@ function Get-HVPoolCustomizationSetting { if ($InstantClone) { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = 'CLONE_PREP' $instantCloneEngineDomainAdministrator_helper = New-Object VMware.Hv.InstantCloneEngineDomainAdministratorService - $instantCloneEngineDomainAdministrator = ($instantCloneEngineDomainAdministrator_helper.InstantCloneEngineDomainAdministrator_List($services) | Where-Object { $_.namesData.dnsName -match $netBiosName }) + $insDomainAdministrators = $instantCloneEngineDomainAdministrator_helper.InstantCloneEngineDomainAdministrator_List($services) + $strFilterSet = @() + if (![string]::IsNullOrWhitespace($netBiosName)) { + $strFilterSet += '$_.namesData.dnsName -match $netBiosName' + } if (![string]::IsNullOrWhitespace($domainAdmin)) { - $instantCloneEngineDomainAdministrator = ($instantCloneEngineDomainAdministrator | Where-Object { $_.base.userName -eq $domainAdmin }).id - } else { + $strFilterSet += '$_.base.userName -eq $domainAdmin' + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $instantCloneEngineDomainAdministrator = $insDomainAdministrators | Where $scriptBlock + If ($null -ne $instantCloneEngineDomainAdministrator) { $instantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator[0].id + } elseif ($null -ne $insDomainAdministrators) { + $instantCloneEngineDomainAdministrator = $insDomainAdministrators[0].id } if ($null -eq $instantCloneEngineDomainAdministrator) { throw "No Instant Clone Engine Domain Administrator found with netBiosName: [$netBiosName]" } $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings = Get-CustomizationObject $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.InstantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.powerOffScriptName = $powerOffScriptName + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.powerOffScriptParameters = $powerOffScriptParameters + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.postSynchronizationScriptName = $postSynchronizationScriptName + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.postSynchronizationScriptParameters = $postSynchronizationScriptParameters } else { if ($LinkedClone) { $viewComposerDomainAdministrator_helper = New-Object VMware.Hv.ViewComposerDomainAdministratorService - $ViewComposerDomainAdministratorID = ($viewComposerDomainAdministrator_helper.ViewComposerDomainAdministrator_List($services,$vcID) | Where-Object { $_.base.domain -match $netBiosName }) + $lcDomainAdministrators = $viewComposerDomainAdministrator_helper.ViewComposerDomainAdministrator_List($services,$vcID) + $strFilterSet = @() + if (![string]::IsNullOrWhitespace($netBiosName)) { + $strFilterSet += '$_.base.domain -match $netBiosName' + } if (![string]::IsNullOrWhitespace($domainAdmin)) { - $ViewComposerDomainAdministratorID = ($ViewComposerDomainAdministratorID | Where-Object { $_.base.userName -ieq $domainAdmin }).id - } else { - $ViewComposerDomainAdministratorID = $ViewComposerDomainAdministratorID[0].id + $strFilterSet += '$_.base.userName -ieq $domainAdmin' + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $ViewComposerDomainAdministratorID = $lcDomainAdministrators | Where $scriptBlock + If ($null -ne $ViewComposerDomainAdministratorID) { + $ViewComposerDomainAdministratorID = $ViewComposerDomainAdministratorID[0].id + } elseif ($null -ne $lcDomainAdministrators) { + $ViewComposerDomainAdministratorID = $lcDomainAdministrators[0].id } if ($null -eq $ViewComposerDomainAdministratorID) { - throw "No Composer Domain Administrator found with netBiosName: [$netBiosName]" + throw "No Composer Domain Administrator found with netBiosName: [$netBiosName]" } if ($custType -eq 'SYS_PREP') { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = 'SYS_PREP' @@ -3614,14 +5046,19 @@ function Get-HVPoolCustomizationSetting { throw "No Sysprep Customization Spec found with Name: [$sysPrepName]" } $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.SysprepCustomizationSettings.CustomizationSpec = $sysPrepIds[0].id - } elseif ($custType -eq 'QUICK_PREP') { + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.ReusePreExistingAccounts = $reusePreExistingAccounts + } elseIf ($custType -eq 'QUICK_PREP') { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = 'QUICK_PREP' $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings = Get-CustomizationObject + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.powerOffScriptName = $powerOffScriptName + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.powerOffScriptParameters = $powerOffScriptParameters + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.postSynchronizationScriptName = $postSynchronizationScriptName + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.postSynchronizationScriptParameters = $postSynchronizationScriptParameters } else { throw "The customization type: [$custType] is not supported for LinkedClone Pool" } $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.DomainAdministrator = $ViewComposerDomainAdministratorID - } elseif ($FullClone) { + } elseIf ($FullClone) { if ($custType -eq 'SYS_PREP') { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = 'SYS_PREP' $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.SysprepCustomizationSettings = Get-CustomizationObject @@ -3632,7 +5069,7 @@ function Get-HVPoolCustomizationSetting { throw "No Sysprep Customization Spec found with Name: [$sysPrepName]" } $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.SysprepCustomizationSettings.CustomizationSpec = $sysPrepIds[0].id - } elseif ($custType -eq 'NONE') { + } elseIf ($custType -eq 'NONE') { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.NoCustomizationSettings = Get-CustomizationObject $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.NoCustomizationSettings.DoNotPowerOnVMsAfterCreation = $false $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = "NONE" @@ -3649,7 +5086,7 @@ function Get-HVPoolCustomizationSetting { function Get-CustomizationObject { if ($InstantClone) { return New-Object VMware.Hv.DesktopCloneprepCustomizationSettings - } elseif ($LinkedClone) { + } elseIf ($LinkedClone) { if ($custType -eq 'QUICK_PREP') { return New-Object VMware.Hv.DesktopQuickPrepCustomizationSettings } else { @@ -3664,7 +5101,7 @@ function Get-CustomizationObject { } } -function Get-HVDesktopSpec { +function Get-DesktopSpec { param( [Parameter(Mandatory = $true)] @@ -3688,7 +5125,7 @@ function Get-HVDesktopSpec { if ($provisioningType -ne 'VIRTUAL_CENTER') { $desktop_spec_helper.getDataObject().AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.ViewComposerStorageSettings = $desktop_helper.getDesktopViewComposerStorageSettingsHelper().getDataObject() } - } elseif ($poolType -eq 'MANUAL') { + } elseIf ($poolType -eq 'MANUAL') { $desktop_spec_helper.getDataObject().ManualDesktopSpec.userAssignment = $desktop_helper.getDesktopUserAssignmentHelper().getDataObject() $desktop_spec_helper.getDataObject().ManualDesktopSpec.viewStorageAcceleratorSettings = $desktop_helper.getDesktopViewStorageAcceleratorSettingsHelper().getDataObject() $desktop_spec_helper.getDataObject().ManualDesktopSpec.virtualCenterManagedCommonSettings = $desktop_helper.getDesktopVirtualCenterManagedCommonSettingsHelper().getDataObject() @@ -3699,6 +5136,119 @@ function Get-HVDesktopSpec { } +function Test-HVPoolSpec { + param( + [Parameter(Mandatory = $true)] + $PoolObject + ) + if ($null -eq $PoolObject.type) { + Throw "Pool type is empty, need to be configured" + } + if ($null -eq $PoolObject.Base.Name) { + Throw "Pool name is empty, need to be configured" + } + if ($null -eq $PoolObject.Base.AccessGroup) { + Throw "AccessGroup of pool is empty, need to be configured" + } + if ($PoolObject.type -eq "AUTOMATED") { + if (! (($PoolObject.AutomatedDesktopSpec.UserAssignment.UserAssignment -eq "FLOATING") -or ($PoolObject.AutomatedDesktopSpec.UserAssignment.UserAssignment -eq "DEDICATED")) ) { + Throw "UserAssignment must be FLOATING or DEDICATED" + } + if ($PoolObject.AutomatedDesktopSpec.ProvisioningType -eq $null) { + Throw "Pool Provisioning type is empty, need to be configured" + } + $provisionTypeArray = @('VIRTUAL_CENTER', 'VIEW_COMPOSER', 'INSTANT_CLONE_ENGINE') + if (! ($provisionTypeArray -contains $PoolObject.AutomatedDesktopSpec.provisioningType)) { + Throw "ProvisioningType of pool is invalid" + } + if ($null -eq $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.EnableProvisioning) { + Throw "Whether to enable provisioning immediately or not, need to be configured" + } + if ($null -eq $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.StopProvisioningOnError) { + Throw "Whether to stop provisioning immediately or not on error, need to be configured" + } + if ($null -eq $PoolObject.AutomatedDesktopSpec.VmNamingSpec.NamingMethod) { + Throw "Determines how the VMs in the desktop are named, need to be configured" + } + if ($null -ne $PoolObject.AutomatedDesktopSpec.VmNamingSpec.NamingMethod) { + $namingMethodArray = @('PATTERN','SPECIFIED') + if (! ($namingMethodArray -contains $PoolObject.AutomatedDesktopSpec.VmNamingSpec.NamingMethod)) { + Throw "NamingMethod property must to be one of these SPECIFIED or PATTERN" + } + if (($null -eq $PoolObject.AutomatedDesktopSpec.VmNamingSpec.patternNamingSettings) -and ($null -eq $PoolObject.AutomatedDesktopSpec.VmNamingSpec.specificNamingSpec)) { + Throw "Naming pattern (or) Specified name settings need to be configured" + } + } + if ($null -eq $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.UseVSan) { + Throw "Must specify whether to use virtual SAN or not" + } + $jsonTemplate = $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.Template + $jsonParentVm = $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.ParentVm + $jsonSnapshot = $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.Snapshot + $jsonVmFolder = $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.VmFolder + $jsonHostOrCluster = $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.HostOrCluster + $ResourcePool = $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.virtualCenterProvisioningData.ResourcePool + if (! (($null -ne $jsonTemplate) -or (($null -ne $jsonParentVm) -and ($null -ne $jsonSnapshot) ))) { + Throw "Must specify Template or (ParentVm and Snapshot) names" + } + if ($null -eq $jsonVmFolder) { + Throw "Must specify VM folder to deploy the VMs" + } + if ($null -eq $jsonHostOrCluster) { + Throw "Must specify HostOrCluster to deploy the VMs" + } + if ($null -eq $resourcePool) { + Throw "Must specify Resource pool to deploy the VMs" + } + if ($null -eq $PoolObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.Datastores) { + Throw "Must specify datastores names" + } + if ($null -eq $PoolObject.AutomatedDesktopSpec.VirtualCenterManagedCommonSettings.transparentPageSharingScope) { + Throw "Must specify transparent page sharing scope" + } + $jsonCustomizationType = $PoolObject.AutomatedDesktopSpec.CustomizationSettings.CustomizationType + switch ($jsonCustomizationType) { + "NONE" { + if ($null -eq $PoolObject.AutomatedDesktopSpec.CustomizationSettings.noCustomizationSettings) { + Throw "Specify noCustomization Settings" + } + } + "QUICK_PREP" { + if ($null -eq $PoolObject.AutomatedDesktopSpec.CustomizationSettings.quickprepCustomizationSettings) { + Throw "Specify quickPrep customizationSettings" + } + } + "SYS_PREP" { + if ($null -eq $PoolObject.AutomatedDesktopSpec.CustomizationSettings.sysprepCustomizationSettings) { + Throw "Specify sysPrep customizationSettings" + } + } + "CLONE_PREP" { + if ($null -eq $PoolObject.AutomatedDesktopSpec.CustomizationSettings.cloneprepCustomizationSettings) { + Throw "Specify clonePrep customizationSettings" + } + } + } + } elseIf ($PoolObject.Type -eq "MANUAL") { + $jsonUserAssignment = $PoolObject.ManualDesktopSpec.UserAssignment.UserAssignment + if (! (($jsonUserAssignment -eq "FLOATING") -or ($jsonUserAssignment -eq "DEDICATED")) ) { + Throw "UserAssignment must be FLOATING or DEDICATED" + } + $jsonSource = @('VIRTUAL_CENTER','UNMANAGED') + if (! ($jsonSource -contains $PoolObject.ManualDesktopSpec.Source)) { + Throw "The Source of machines must be VIRTUAL_CENTER or UNMANAGED" + } + if ($null -eq $PoolObject.ManualDesktopSpec.Machines) { + Throw "Specify list of virtual machines to be added to this pool" + } + } + elseIf ($PoolObject.type -eq "RDS") { + if ($null -eq $PoolObject.RdsDesktopSpec.Farm) { + Throw "Specify farm needed to create RDS desktop" + } + } +} + function Remove-HVFarm { <# .SYNOPSIS @@ -3714,29 +5264,32 @@ function Remove-HVFarm { Object(s) of the farm to be deleted. Object(s) should be of type FarmSummaryView/FarmInfo. .PARAMETER HvServer - Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered inplace of hvServer. + Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE - Remove-HVFarm -FarmName 'Farm-01' -HvServer $hvServer + Remove-HVFarm -FarmName 'Farm-01' -HvServer $hvServer -Confirm:$false + Delete a given farm. For an automated farm, all the RDS Server VMs are deleted from disk whereas for a manual farm only the RDS Server associations are removed. .EXAMPLE $farm_array | Remove-HVFarm -HvServer $hvServer + Deletes a given Farm object(s). For an automated farm, all the RDS Server VMs are deleted from disk whereas for a manual farm only the RDS Server associations are removed. .EXAMPLE - $farm1 = Get-HVFarm -FarmName 'Farm-01' - Remove-HVFarm -Farm $farm1 + C:\PS>$farm1 = Get-HVFarm -FarmName 'Farm-01' + C:\PS>Remove-HVFarm -Farm $farm1 + Deletes a given Farm object. For an automated farm, all the RDS Server VMs are deleted from disk whereas for a manual farm only the RDS Server associations are removed. .OUTPUTS None .NOTES - Author : Ankit Gupta. - Author email : guptaa@vmware.com - Version : 1.0 + Author : praveen mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -3765,26 +5318,27 @@ function Remove-HVFarm { } } process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys $farmList = @() if ($farmName) { try { - $farmSpecObj = Get-HVFarm -farmName $farmName -hvServer $hvServer + $farmSpecObj = Get-HVFarm -farmName $farmName -hvServer $hvServer -SuppressInfo $true } catch { Write-Error "Make sure Get-HVFarm advanced function is loaded, $_" break } if ($farmSpecObj) { foreach ($farmObj in $farmSpecObj) { - $farmList += $farmObj.id + $farmList += @{"id" = $farmObj.id; "Name" = $farmObj.data.name} } } else { Write-Error "Unable to retrieve FarmSummaryView with given farmName [$farmName]" break } - } elseif ($PSCmdlet.MyInvocation.ExpectingInput) { + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Farm) { foreach ($item in $farm) { - if ($item.GetType().name -eq 'FarmInfo' -or $item.GetType().name -eq 'FarmSummaryView') { - $farmList += $item.id + if (($item.GetType().name -eq 'FarmInfo') -or ($item.GetType().name -eq 'FarmSummaryView')) { + $farmList += @{"id" = $item.id; "Name" = $item.data.name} } else { Write-Error "In pipeline did not get object of expected type FarmSummaryView/FarmInfo" @@ -3795,10 +5349,11 @@ function Remove-HVFarm { } $farm_service_helper = New-Object VMware.Hv.FarmService foreach ($item in $farmList) { - $farm_service_helper.Farm_Delete($services, $item) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($item.Name)) { + $farm_service_helper.Farm_Delete($services, $item.id) + } + Write-Host "Farm Deleted: " $item.Name } - Write-Host "Farm Deleted" - } end { [System.gc]::collect() @@ -3830,13 +5385,16 @@ function Remove-HVPool { Logs off a session forcibly to virtual machine(s). This operation will also log off a locked session. .EXAMPLE - Remove-HVPool -HvServer $hvServer -PoolName 'FullClone' -DeleteFromDisk + Remove-HVPool -HvServer $hvServer -PoolName 'FullClone' -DeleteFromDisk -Confirm:$false + Deletes pool from disk with given parameters PoolName etc. .EXAMPLE $pool_array | Remove-HVPool -HvServer $hvServer -DeleteFromDisk + Deletes specified pool from disk .EXAMPLE Remove-HVPool -Pool $pool1 + Deletes specified pool and VM(s) associations are removed from view Manager .OUTPUTS None @@ -3844,11 +5402,11 @@ function Remove-HVPool { .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -3857,7 +5415,7 @@ function Remove-HVPool { ConfirmImpact = 'High' )] param( - [Parameter(Mandatory = $false,ParameterSetName = 'option')] + [Parameter(Mandatory = $true,ParameterSetName = 'option')] [string] $poolName, # PoolObject @@ -3883,26 +5441,30 @@ function Remove-HVPool { } process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys $poolList = @() if ($poolName) { try { - $myPools = Get-HVPoolSummary -poolName $poolName -hvServer $hvServer + $myPools = Get-HVPoolSummary -poolName $poolName -suppressInfo $true -hvServer $hvServer } catch { - Write-Error "Make sure Get-HVPool advanced function is loaded, $_" + Write-Error "Make sure Get-HVPoolSummary advanced function is loaded, $_" break } if ($myPools) { foreach ($poolObj in $myPools) { - $poolList += $poolObj.id + $poolList += @{id = $poolObj.id; name = $poolObj.desktopSummaryData.name} } } else { Write-Error "No desktopsummarydata found with pool name: [$pool]" break } - } elseif ($PSCmdlet.MyInvocation.ExpectingInput) { + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Pool) { foreach ($item in $pool) { - if (($item.GetType().name -eq 'DesktopInfo') -or ($item.GetType().name -eq 'DesktopSummaryView')) { - $poolList += $item.id + if ($item.GetType().name -eq 'DesktopSummaryView') { + $poolList += @{id = $item.id; name = $item.desktopSummaryData.name} + } + elseif ($item.GetType().name -eq 'DesktopInfo') { + $poolList += @{id = $item.id; name = $item.base.name} } else { Write-Error "In pipeline did not get object of expected type DesktopSummaryView/DesktopInfo" @@ -3917,9 +5479,8 @@ function Remove-HVPool { foreach ($item in $poolList) { if ($terminateSession) { #Terminate session - $queryResults = Get-HVQueryResults MachineSummaryView (Get-HVQueryFilter base.desktop -eq $item) + $queryResults = Get-HVQueryResult MachineSummaryView (Get-HVQueryFilter base.desktop -eq $item.id) $sessions += $queryResults.base.session - if ($null -ne $sessions) { $session_service_helper = New-Object VMware.Hv.SessionService try { @@ -3932,8 +5493,10 @@ function Remove-HVPool { Write-Host "No session found." } } - Write-Host "Deleting Pool" - $desktop_service_helper.Desktop_Delete($services,$item,$deleteSpec) + Write-Host "Deleting Pool: " $item.Name + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($item.Name)) { + $desktop_service_helper.Desktop_Delete($services,$item.id,$deleteSpec) + } } } @@ -3978,34 +5541,39 @@ function Set-HVFarm { Path of the JSON specification file containing key/value pair. .PARAMETER HvServer - Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered inplace of hvServer. + Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE - Set-HVFarm -FarmName 'Farm-o1' -Spec 'C:\Edit-HVFarm\ManualEditFarm.json' + Set-HVFarm -FarmName 'Farm-01' -Spec 'C:\Edit-HVFarm\ManualEditFarm.json' -Confirm:$false + Updates farm configuration by using json file .EXAMPLE - Set-HVFarm -FarmName 'Farm-o1' -Key 'base.description' -Value 'updated description' + Set-HVFarm -FarmName 'Farm-01' -Key 'base.description' -Value 'updated description' + Updates farm configuration with given parameters key and value .EXAMPLE $farm_array | Set-HVFarm -Key 'base.description' -Value 'updated description' + Updates farm(s) configuration with given parameters key and value .EXAMPLE Set-HVFarm -farm 'Farm2' -Start + Enables provisioning to specified farm .EXAMPLE Set-HVFarm -farm 'Farm2' -Enable + Enables specified farm .OUTPUTS None .NOTES - Author : Ankit Gupta. - Author email : guptaa@vmware.com - Version : 1.0 + Author : praveen mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -4054,12 +5622,13 @@ function Set-HVFarm { } process { - $farmList = @() + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + $farmList = @{} if ($farmName) { try { - $farmSpecObj = Get-HVFarmSummary -farmName $farmName -hvServer $hvServer + $farmSpecObj = Get-HVFarmSummary -farmName $farmName -hvServer $hvServer -suppressInfo $true } catch { - Write-Error "Make sure Get-HVFarm advanced function is loaded, $_" + Write-Error "Make sure Get-HVFarmSummary advanced function is loaded, $_" break } if ($farmSpecObj) { @@ -4068,7 +5637,7 @@ function Set-HVFarm { Write-Error "Start/Stop operation is not supported for farm with name : [$farmObj.Data.Name]" return } - $farmList += $farmObj.id + $farmList.add($farmObj.id, $farmObj.data.name) } } else { Write-Error "Unable to retrieve FarmSummaryView with given farmName [$farmName]" @@ -4081,14 +5650,14 @@ function Set-HVFarm { Write-Error "Start/Stop operation is not supported for farm with name : [$item.Data.Name]" return } - $farmList += $item.id + $farmList.add($item.id, $item.data.name) } elseif ($item.GetType().name -eq 'FarmInfo') { if (($Start -or $Stop) -and ("AUTOMATED" -ne $item.Type)) { Write-Error "Start/Stop operation is not supported for farm with name : [$item.Data.Name]" return } - $farmList += $item.id + $farmList.add($item.id, $item.data.name) } else { Write-Error "In pipeline did not get object of expected type FarmSummaryView/FarmInfo" @@ -4125,8 +5694,11 @@ function Set-HVFarm { -value $false } $farm_service_helper = New-Object VMware.Hv.FarmService - foreach ($item in $farmList) { - $farm_service_helper.Farm_Update($services,$item,$updates) + foreach ($item in $farmList.Keys) { + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($farmList.$item)) { + $farm_service_helper.Farm_Update($services,$item,$updates) + } + Write-Host "Update successful for farm: " $farmList.$item } } @@ -4175,22 +5747,28 @@ function Set-HVPool { Path of the JSON specification file containing key/value pair. .EXAMPLE - Set-HVPool -PoolName 'ManualPool' -Spec 'C:\Edit-HVPool\EditPool.json' + Set-HVPool -PoolName 'ManualPool' -Spec 'C:\Edit-HVPool\EditPool.json' -Confirm:$false + Updates pool configuration by using json file .EXAMPLE Set-HVPool -PoolName 'RDSPool' -Key 'base.description' -Value 'update description' + Updates pool configuration with given parameters key and value .Example Set-HVPool -PoolName 'LnkClone' -Disable + Disables specified pool .Example Set-HVPool -PoolName 'LnkClone' -Enable + Enables specified pool .Example Set-HVPool -PoolName 'LnkClone' -Start + Enables provisioning to specified pool .Example Set-HVPool -PoolName 'LnkClone' -Stop + Disables provisioning to specified pool .OUTPUTS None @@ -4198,11 +5776,11 @@ function Set-HVPool { .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -4253,12 +5831,13 @@ function Set-HVPool { } process { - $poolList = @() + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + $poolList = @{} if ($poolName) { try { - $desktopPools = Get-HVPoolSummary -poolName $poolName -hvServer $hvServer + $desktopPools = Get-HVPoolSummary -poolName $poolName -suppressInfo $true -hvServer $hvServer } catch { - Write-Error "Make sure Get-HVPool advanced function is loaded, $_" + Write-Error "Make sure Get-HVPoolSummary advanced function is loaded, $_" break } if ($desktopPools) { @@ -4267,24 +5846,27 @@ function Set-HVPool { Write-Error "Start/Stop operation is not supported for Poll with name : [$item.DesktopSummaryData.Name]" return } - $poolList += $desktopObj.id + $poolList.add($desktopObj.id, $desktopObj.DesktopSummaryData.Name) } + } else { + Write-Error "No desktopsummarydata found with pool name: [$poolName]" + break } - } elseif ($PSCmdlet.MyInvocation.ExpectingInput) { + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Pool) { foreach ($item in $pool) { if ($item.GetType().name -eq 'DesktopInfo') { if (($Start -or $Stop) -and ("AUTOMATED" -ne $item.Type)) { Write-Error "Start/Stop operation is not supported for Pool with name : [$item.Base.Name]" return } - $poolList += $item.id + $poolList.add($item.id, $item.Base.Name) } elseif ($item.GetType().name -eq 'DesktopSummaryView') { if (($Start -or $Stop) -and ("AUTOMATED" -ne $item.DesktopSummaryData.Type)) { Write-Error "Start/Stop operation is not supported for Poll with name : [$item.DesktopSummaryData.Name]" return } - $poolList += $item.id + $poolList.add($item.id, $item.DesktopSummaryData.Name) } else { Write-Error "In pipeline did not get object of expected type DesktopSummaryView/DesktopInfo" @@ -4325,8 +5907,11 @@ function Set-HVPool { -value $false } $desktop_helper = New-Object VMware.Hv.DesktopService - foreach ($item in $poolList) { - $desktop_helper.Desktop_Update($services,$item,$updates) + foreach ($item in $poolList.Keys) { + Write-Host "Updating the Pool: " $poolList.$item + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + $desktop_helper.Desktop_Update($services,$item,$updates) + } } } @@ -4338,10 +5923,10 @@ function Set-HVPool { function Start-HVFarm { <# .SYNOPSIS - Perform maintenance tasks on the farm(s). + Performs maintenance tasks on the farm(s). .DESCRIPTION - This function is used to perform maintenance tasks like enable/disable, start/stop and recompose the farm. + This function is used to perform maintenance tasks like enable/disable, start/stop and recompose the farm. This function is also used for scheduling maintenance operation on instant-clone farm(s). .PARAMETER Farm Name/Object(s) of the farm. Object(s) should be of type FarmSummaryView/FarmInfo. @@ -4349,16 +5934,23 @@ function Start-HVFarm { .PARAMETER Recompose Switch for recompose operation. Requests a recompose of RDS Servers in the specified 'AUTOMATED' farm. This marks the RDS Servers for recompose, which is performed asynchronously. +.PARAMETER ScheduleMaintenance + Switch for ScheduleMaintenance operation. Requests for scheduling maintenance operation on RDS Servers in the specified Instant clone farm. This marks the RDS Servers for scheduled maintenance, which is performed according to the schedule. + +.PARAMETER CancelMaintenance + Switch for cancelling maintenance operation. Requests for cancelling a scheduled maintenance operation on the specified Instant clone farm. This stops further maintenance operation on the given farm. + .PARAMETER StartTime - Specifies when to start the operation. If unset, the operation will begin immediately. + Specifies when to start the recompose/ScheduleMaintenance operation. If unset, the recompose operation will begin immediately. + For IMMEDIATE maintenance if unset, maintenance will begin immediately. For RECURRING maintenance if unset, will be calculated based on recurring maintenance configuration. If in the past, maintenance will begin immediately. .PARAMETER LogoffSetting Determines when to perform the operation on machines which have an active session. This property will be one of: - "FORCE_LOGOFF" - Users will be forced to log off when the system is ready to operate on their RDS Servers. Before being forcibly logged off, users may have a grace period in which to save their work (Global Settings). + "FORCE_LOGOFF" - Users will be forced to log off when the system is ready to operate on their RDS Servers. Before being forcibly logged off, users may have a grace period in which to save their work (Global Settings). This is the default value. "WAIT_FOR_LOGOFF" - Wait for connected users to disconnect before the task starts. The operation starts immediately on RDS Servers without active sessions. .PARAMETER StopOnFirstError - Indicates that the operation should stop on first error. + Indicates that the operation should stop on first error. Defaults to true. .PARAMETER Servers The RDS Server(s) id to recompose. Provide a comma separated list for multiple RDSServerIds. @@ -4372,27 +5964,65 @@ function Start-HVFarm { .PARAMETER Vcenter Virtual Center server-address (IP or FQDN) of the given farm. This should be same as provided to the Connection Server while adding the vCenter server. +.PARAMETER MaintenanceMode + The mode of schedule maintenance for Instant Clone Farm. This property will be one of: + "IMMEDIATE" - All server VMs will be refreshed once, immediately or at user scheduled time. + "RECURRING" - All server VMs will be periodically refreshed based on MaintenancePeriod and MaintenanceStartTime. + +.PARAMETER MaintenanceStartTime + Configured start time for the recurring maintenance. This property must be in the form hh:mm in 24 hours format. + +.PARAMETER MaintenancePeriod + This represents the frequency at which to perform recurring maintenance. This property will be one of: + "DAILY" - Daily recurring maintenance + "WEEKLY" - Weekly recurring maintenance + "MONTHLY" - Monthly recurring maintenance + +.PARAMETER StartInt + Start index for weekly or monthly maintenance. Weekly: 1-7 (Sun-Sat), Monthly: 1-31. + This property is required if maintenancePeriod is set to "WEEKLY"or "MONTHLY". + This property has values 1-7 for maintenancePeriod "WEEKLY". + This property has values 1-31 for maintenancePeriod "MONTHLY". + +.PARAMETER EveryInt + How frequently to repeat maintenance, expressed as a multiple of the maintenance period. e.g. Every 2 weeks. + This property has a default value of 1. This property has values 1-100. + .PARAMETER HvServer - Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered inplace of hvServer. + Reference to Horizon View Server to query the data from. If the value is not passed or null then first element from global:DefaultHVServers would be considered in-place of hvServer. .EXAMPLE - Start-HVFarm -Recompose -Farm 'Farm-01' -LogoffSetting FORCE_LOGOFF -ParentVM 'View-Agent-Win8' -SnapshotVM 'Snap_USB' + Start-HVFarm -Recompose -Farm 'Farm-01' -LogoffSetting FORCE_LOGOFF -ParentVM 'View-Agent-Win8' -SnapshotVM 'Snap_USB' -Confirm:$false + Requests a recompose of RDS Servers in the specified automated farm .EXAMPLE - $myTime = Get-Date '10/03/2016 12:30:00' - Start-HVFarm -Farm 'Farm-01' -Recompose -LogoffSetting 'FORCE_LOGOFF' -ParentVM 'ParentVM' -SnapshotVM 'SnapshotVM' -StartTime $myTime + C:\PS>$myTime = Get-Date '10/03/2016 12:30:00' + C:\PS>Start-HVFarm -Farm 'Farm-01' -Recompose -LogoffSetting 'FORCE_LOGOFF' -ParentVM 'ParentVM' -SnapshotVM 'SnapshotVM' -StartTime $myTime + Requests a recompose task for automated farm in specified time + +.EXAMPLE + Start-HVFarm -Farm 'ICFarm-01' -ScheduleMaintenance -MaintenanceMode IMMEDIATE + Requests a ScheduleMaintenance task for instant-clone farm. Schedules an IMMEDIATE maintenance. + +.EXAMPLE + Start-HVFarm -ScheduleMaintenance -Farm 'ICFarm-01' -MaintenanceMode RECURRING -MaintenancePeriod WEEKLY -MaintenanceStartTime '11:30' -StartInt 6 -EveryInt 1 -ParentVM 'vm-rdsh-ic' -SnapshotVM 'Snap_Updated' + Requests a ScheduleMaintenance task for instant-clone farm. Schedules a recurring weekly maintenace every Saturday night at 23:30 and updates the parentVM and snapshot. + +.EXAMPLE + Start-HVFarm -CancelMaintenance -Farm 'ICFarm-01' -MaintenanceMode RECURRING + Requests a CancelMaintenance task for instant-clone farm. Cancels recurring maintenance. .OUTPUTS None .NOTES - Author : Ankit Gupta. - Author email : guptaa@vmware.com - Version : 1.0 + Author : praveen mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -4407,28 +6037,61 @@ function Start-HVFarm { [Parameter(Mandatory = $false,ParameterSetName = 'RECOMPOSE')] [switch]$Recompose, + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] + [switch]$ScheduleMaintenance, + + [Parameter(Mandatory = $false,ParameterSetName = 'CANCELMAINTENANCE')] + [switch]$CancelMaintenance, + [Parameter(Mandatory = $false,ParameterSetName = 'RECOMPOSE')] + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] [System.DateTime]$StartTime, [Parameter(Mandatory = $true,ParameterSetName = 'RECOMPOSE')] + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] [ValidateSet('FORCE_LOGOFF','WAIT_FOR_LOGOFF')] - [string]$LogoffSetting, + [string]$LogoffSetting = 'FORCE_LOGOFF', [Parameter(Mandatory = $false,ParameterSetName = 'RECOMPOSE')] + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] [boolean]$StopOnFirstError = $true, [Parameter(Mandatory = $false,ParameterSetName = 'RECOMPOSE')] [string []]$Servers, [Parameter(Mandatory = $true,ParameterSetName = 'RECOMPOSE')] + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] [string]$ParentVM, [Parameter(Mandatory = $true,ParameterSetName = 'RECOMPOSE')] + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] [string]$SnapshotVM, [Parameter(Mandatory = $false,ParameterSetName = 'RECOMPOSE')] + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] [string]$Vcenter, + [Parameter(Mandatory = $true,ParameterSetName = 'SCHEDULEMAINTENANCE')] + [Parameter(Mandatory = $true,ParameterSetName = 'CANCELMAINTENANCE')] + [ValidateSet('IMMEDIATE','RECURRING')] + [string]$MaintenanceMode, + + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] + [ValidatePattern('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')] + [string]$MaintenanceStartTime, + + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] + [ValidateSet('DAILY','WEEKLY','MONTHLY')] + [string]$MaintenancePeriod, + + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] + [ValidateRange(1, 31)] + [int]$StartInt, + + [Parameter(Mandatory = $false,ParameterSetName = 'SCHEDULEMAINTENANCE')] + [ValidateRange(1, 100)] + [int]$EveryInt = 1, + [Parameter(Mandatory = $false)] $HvServer = $null ) @@ -4442,6 +6105,7 @@ function Start-HVFarm { } process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys $farmList = @{} $farmType = @{} $farmSource = @{} @@ -4451,15 +6115,17 @@ function Start-HVFarm { $id = $farm.id $name = $farm.data.name $type = $farm.type + $source = $farm.source } elseif ($farm.GetType().name -eq 'FarmSummaryView') { $id = $farm.id $name = $farm.data.name $type = $farm.data.type + $source = $farm.data.source } elseif ($farm.GetType().name -eq 'String') { try { - $farmSpecObj = Get-HVFarm -farmName $farm -hvServer $hvServer + $farmSpecObj = Get-HVFarm -farmName $farm -hvServer $hvServer -SuppressInfo $true } catch { Write-Error "Make sure Get-HVFarm advanced function is loaded, $_" break @@ -4467,7 +6133,8 @@ function Start-HVFarm { if ($farmSpecObj) { $id = $farmSpecObj.id $name = $farmSpecObj.data.name - $type = $farmSpecObj.data.type + $type = $farmSpecObj.type + $source = $farmSpecObj.source } else { Write-Error "Unable to retrieve FarmSummaryView with given farmName [$farm]" break @@ -4476,7 +6143,7 @@ function Start-HVFarm { Write-Error "In pipeline did not get object of expected type FarmSummaryView/FarmInfo" break } - if ($type -eq 'AUTOMATED') { + if (!$source) { $source = 'VIEW_COMPOSER' } $farmList.Add($id,$name) @@ -4519,12 +6186,73 @@ function Start-HVFarm { $updates = @() $updates += Get-MapEntry -key 'automatedFarmData.virtualCenterProvisioningSettings.virtualCenterProvisioningData.parentVm' -value $spec.ParentVM $updates += Get-MapEntry -key 'automatedFarmData.virtualCenterProvisioningSettings.virtualCenterProvisioningData.snapshot' -value $spec.Snapshot - $farm_service_helper.Farm_Update($services,$item,$updates) - - $farm_service_helper.Farm_Recompose($services,$item,$spec) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($farmList.$item)) { + $farm_service_helper.Farm_Update($services,$item,$updates) + $farm_service_helper.Farm_Recompose($services,$item,$spec) + } + Write-Host "Performed recompose task on farm: " $farmList.$item + } + } + 'SCHEDULEMAINTENANCE' { + if ($farmSource.$item -ne 'INSTANT_CLONE_ENGINE') { + Write-Error "SCHEDULEMAINTENANCE operation is not supported for farm with name [$farmList.$item]. It is only supported for instant-clone farms." + break + } else { + $spec = New-Object VMware.Hv.FarmMaintenanceSpec + $spec.MaintenanceMode = $MaintenanceMode + if ($startTime) { + $spec.ScheduledTime = $StartTime + } + $spec.LogoffSetting = $LogoffSetting + $spec.StopOnFirstError = $StopOnFirstError + if ($MaintenanceMode -eq "RECURRING") { + $spec.RecurringMaintenanceSettings = New-Object VMware.Hv.FarmRecurringMaintenanceSettings + $spec.RecurringMaintenanceSettings.MaintenancePeriod = $MaintenancePeriod + $spec.RecurringMaintenanceSettings.EveryInt = $EveryInt + if (!$MaintenanceStartTime) { + Write-Error "MaintenanceStartTime must be defined for MaintenanceMode = RECURRING." + break; + } else { + $spec.RecurringMaintenanceSettings.StartTime = $MaintenanceStartTime + } + if ($MaintenancePeriod -ne 'DAILY') { + if (!$StartInt) { + Write-Error "StartInt must be defined for MaintenancePeriod WEEKLY or MONTHLY." + break; + } else { + $spec.RecurringMaintenanceSettings.StartInt = $StartInt + } + } + } + #image settings are specified + if ($ParentVM -and $SnapshotVM) { + $spec.ImageMaintenanceSettings = New-Object VMware.Hv.FarmImageMaintenanceSettings + $vcId = Get-VcenterID -services $services -vCenter $Vcenter + if ($null -eq $vcId) { + Write-Error "VCenter is required if you specify ParentVM name." + break + } + try { + $spec.ImageMaintenanceSettings = Set-HVFarmSpec -vcId $vcId -spec $spec.ImageMaintenanceSettings + } catch { + Write-Error "SCHEDULEMAINTENANCE task failed with error: $_" + break + } + } + # call scheduleMaintenance service on farm + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($farmList.$item)) { + $farm_service_helper.Farm_ScheduleMaintenance($services, $item, $spec) + Write-Host "Performed SCHEDULEMAINTENANCE task on farm: " $farmList.$item + } + } + } + 'CANCELMAINTENANCE' { + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($farmList.$item)) { + $farm_service_helper.Farm_CancelScheduleMaintenance($services, $item, $MaintenanceMode) + Write-Host "Performed CANCELMAINTENANCE task on farm: " $farmList.$item + } } } - } return } } @@ -4645,19 +6373,24 @@ function Start-HVPool { .EXAMPLE Start-HVPool -Recompose -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -ParentVM 'View-Agent-Win8' -SnapshotVM 'Snap_USB' + Requests a recompose of machines in the specified pool .EXAMPLE - Start-HVPool -Refresh -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF + Start-HVPool -Refresh -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -Confirm:$false + Requests a refresh of machines in the specified pool .EXAMPLE - $myTime = Get-Date '10/03/2016 12:30:00' - Start-HVPool -Rebalance -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -StartTime $myTime + C:\PS>$myTime = Get-Date '10/03/2016 12:30:00' + C:\PS>Start-HVPool -Rebalance -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -StartTime $myTime + Requests a rebalance of machines in a pool with specified time .EXAMPLE Start-HVPool -SchedulePushImage -Pool 'InstantPool' -LogoffSetting FORCE_LOGOFF -ParentVM 'InsParentVM' -SnapshotVM 'InsSnapshotVM' + Requests an update of push image operation on the specified Instant Clone Engine sourced pool .EXAMPLE Start-HVPool -CancelPushImage -Pool 'InstantPool' + Requests a cancellation of the current scheduled push image operation on the specified Instant Clone Engine sourced pool .OUTPUTS None @@ -4665,11 +6398,11 @@ function Start-HVPool { .NOTES Author : Praveen Mathamsetty. Author email : pmathamsetty@vmware.com - Version : 1.0 + Version : 1.1 ===Tested Against Environment==== - Horizon View Server Version : 7.0.2 - PowerCLI Version : PowerCLI 6.5 + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> @@ -4747,7 +6480,7 @@ function Start-HVPool { } process { - + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys $poolList = @{} $poolType = @{} $poolSource = @{} @@ -4765,9 +6498,9 @@ function Start-HVPool { $type = $item.desktopsummarydata.type } elseif ($item.GetType().name -eq 'String') { try { - $poolObj = Get-HVPoolSummary -poolName $item -hvServer $hvServer + $poolObj = Get-HVPoolSummary -poolName $item -suppressInfo $true -hvServer $hvServer } catch { - Write-Error "Make sure Get-HVPool advanced function is loaded, $_" + Write-Error "Make sure Get-HVPoolSummary advanced function is loaded, $_" break } if ($poolObj) { @@ -4800,14 +6533,20 @@ function Start-HVPool { $spec = Get-HVTaskSpec -Source $poolSource.$item -poolName $poolList.$item -operation $operation -taskSpecName 'DesktopRebalanceSpec' -desktopId $item if ($null -ne $spec) { # make sure current task on VMs, must be None - $desktop_helper.Desktop_Rebalance($services,$item,$spec) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + $desktop_helper.Desktop_Rebalance($services,$item,$spec) + } + Write-Host "Performed rebalance task on Pool: " $PoolList.$item } } 'REFRESH' { $spec = Get-HVTaskSpec -Source $poolSource.$item -poolName $poolList.$item -operation $operation -taskSpecName 'DesktopRefreshSpec' -desktopId $item if ($null -ne $spec) { # make sure current task on VMs, must be None - $desktop_helper.Desktop_Refresh($services,$item,$spec) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + $desktop_helper.Desktop_Refresh($services,$item,$spec) + } + Write-Host "Performed refresh task on Pool: " $PoolList.$item } } 'RECOMPOSE' { @@ -4823,8 +6562,10 @@ function Start-HVPool { $updates = @() $updates += Get-MapEntry -key 'automatedDesktopData.virtualCenterProvisioningSettings.virtualCenterProvisioningData.parentVm' -value $spec.ParentVM $updates += Get-MapEntry -key 'automatedDesktopData.virtualCenterProvisioningSettings.virtualCenterProvisioningData.snapshot' -value $spec.Snapshot - $desktop_helper.Desktop_Update($services,$item,$updates) - + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + $desktop_helper.Desktop_Update($services,$item,$updates) + } + Write-Host "Performed recompose task on Pool: " $PoolList.$item } } 'PUSH_IMAGE' { @@ -4839,7 +6580,10 @@ function Start-HVPool { $spec.Settings.LogoffSetting = $logoffSetting $spec.Settings.StopOnFirstError = $stopOnFirstError if ($startTime) { $spec.Settings.startTime = $startTime } - $desktop_helper.Desktop_SchedulePushImage($services,$item,$spec) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + $desktop_helper.Desktop_SchedulePushImage($services,$item,$spec) + } + Write-Host "Performed push_image task on Pool: " $PoolList.$item } } 'CANCEL_PUSH_IMAGE' { @@ -4847,7 +6591,10 @@ function Start-HVPool { Write-Error "$poolList.$item is not a INSTANT CLONE pool" break } else { - $desktop_helper.Desktop_CancelScheduledPushImage($services,$item) + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + $desktop_helper.Desktop_CancelScheduledPushImage($services,$item) + } + Write-Host "Performed cancel_push_image task on Pool: " $PoolList.$item } } } @@ -4943,4 +6690,2296 @@ function Get-HVTaskSpec { return $spec } -Export-ModuleMember Add-HVDesktop,Add-HVRDSServer,Connect-HVEvent,Disconnect-HVEvent,Get-HVEvent,Get-HVFarm,Get-HVFarmSummary,Get-HVPool,Get-HVPoolSummary,Get-HVQueryResult,Get-HVQueryFilter,New-HVFarm,New-HVPool,Remove-HVFarm,Remove-HVPool,Set-HVFarm,Set-HVPool,Start-HVFarm,Start-HVPool +function Find-HVMachine { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + $Param + ) + + $params = $Param + + try { + if ($params['PoolName']) { + $poolObj = Get-HVPoolSummary -poolName $params['PoolName'] -suppressInfo $true -hvServer $params['HvServer'] + if ($poolObj.Length -ne 1) { + Write-Host "Failed to retrieve specific pool object with given PoolName : " $params['PoolName'] + break; + } else { + $desktopId = $poolObj.Id + } + } + } catch { + Write-Error "Make sure Get-HVPoolSummary advanced function is loaded, $_" + break + } + # + # This translates the function arguments into the View API properties that must be queried + $machineSelectors = @{ + 'PoolName' = 'base.desktop'; + 'MachineName' = 'base.name'; + 'DnsName' = 'base.dnsName'; + 'State' = 'base.basicState'; + } + + + $query_service_helper = New-Object VMware.Hv.QueryServiceService + $query = New-Object VMware.Hv.QueryDefinition + + $wildCard = $false + #Only supports wild card '*' + if ($params['MachineName'] -and $params['MachineName'].contains('*')) { + $wildcard = $true + } + if ($params['DnsName'] -and $params['DnsName'].contains('*')) { + $wildcard = $true + } + # build the query values, MachineNamesView is having more info than + # MachineSummaryView + $query.queryEntityType = 'MachineNamesView' + if (! $wildcard) { + [VMware.Hv.queryfilter[]]$filterSet = @() + foreach ($setting in $machineSelectors.Keys) { + if ($null -ne $params[$setting]) { + $equalsFilter = New-Object VMware.Hv.QueryFilterEquals + $equalsFilter.memberName = $machineSelectors[$setting] + if ($equalsFilter.memberName -eq 'base.desktop') { + $equalsFilter.value = $desktopId + } else { + $equalsFilter.value = $params[$setting] + } + $filterSet += $equalsFilter + } + } + if ($filterSet.Count -gt 0) { + $andFilter = New-Object VMware.Hv.QueryFilterAnd + $andFilter.Filters = $filterset + $query.Filter = $andFilter + } + $queryResults = $query_service_helper.QueryService_Query($services,$query) + $machineList = $queryResults.results + } + if ($wildcard -or [string]::IsNullOrEmpty($machineList)) { + $query.Filter = $null + $queryResults = $query_service_helper.QueryService_Query($services,$query) + $strFilterSet = @() + foreach ($setting in $machineSelectors.Keys) { + if ($null -ne $params[$setting]) { + if ($wildcard -and (($setting -eq 'MachineName') -or ($setting -eq 'DnsName')) ) { + $strFilterSet += '($_.' + $machineSelectors[$setting] + ' -like "' + $params[$setting] + '")' + } else { + $strFilterSet += '($_.' + $machineSelectors[$setting] + ' -eq "' + $params[$setting] + '")' + } + } + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $machineList = $queryResults.results | where $scriptBlock + } + return $machineList +} + + +function Get-HVMachine { +<# +.Synopsis + Gets virtual Machine(s) information with given search parameters. + +.DESCRIPTION + Queries and returns virtual machines information, the machines list would be determined + based on queryable fields poolName, dnsName, machineName, state. When more than one + fields are used for query the virtual machines which satisfy all fields criteria would be returned. + +.PARAMETER PoolName + Pool name to query for. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has name same as value will be returned. + +.PARAMETER MachineName + The name of the Machine to query for. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has display name same as value will be returned. + +.PARAMETER DnsName + DNS name for the Machine to filter with. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has display name same as value will be returned. + +.PARAMETER State + The basic state of the Machine to filter with. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has display name same as value will be returned. + +.PARAMETER HvServer + Reference to Horizon View Server to query the virtual machines from. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Get-HVMachine -PoolName 'ManualPool' + Queries VM(s) with given parameter poolName + +.EXAMPLE + Get-HVMachine -MachineName 'PowerCLIVM' + Queries VM(s) with given parameter machineName + +.EXAMPLE + Get-HVMachine -State CUSTOMIZING + Queries VM(s) with given parameter vm state + +.EXAMPLE + Get-HVMachine -DnsName 'powercli-*' + Queries VM(s) with given parameter dnsName with wildcard character * + +.OUTPUTS + Returns list of objects of type MachineInfo + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + + param( + [Parameter(Mandatory = $false)] + [string] + $PoolName, + + [Parameter(Mandatory = $false)] + [string] + $MachineName, + + [Parameter(Mandatory = $false)] + [string] + $DnsName, + + [Parameter(Mandatory = $false)] + [ValidateSet('PROVISIONING','PROVISIONING_ERROR','WAIT_FOR_AGENT','CUSTOMIZING', + 'DELETING','MAINTENANCE','ERROR','PROVISIONED','AGENT_UNREACHABLE','UNASSIGNED_USER_CONNECTED', + 'CONNECTED','UNASSIGNED_USER_DISCONNECTED','DISCONNECTED','AGENT_ERR_STARTUP_IN_PROGRESS', + 'AGENT_ERR_DISABLED','AGENT_ERR_INVALID_IP','AGENT_ERR_NEED_REBOOT','AGENT_ERR_PROTOCOL_FAILURE', + 'AGENT_ERR_DOMAIN_FAILURE','AGENT_CONFIG_ERROR','ALREADY_USED','AVAILABLE','IN_PROGRESS','DISABLED', + 'DISABLE_IN_PROGRESS','VALIDATING','UNKNOWN')] + [string] + $State, + + [Parameter(Mandatory = $false)] + [string] + $JsonFilePath, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + + $machineList = Find-HVMachine -Param $PSBoundParameters + if (!$machineList) { + Write-Host "Get-HVMachine: No Virtual Machine(s) Found with given search parameters" + break + } + $queryResults = @() + $desktop_helper = New-Object VMware.Hv.MachineService + foreach ($id in $machineList.id) { + $info = $desktop_helper.Machine_Get($services,$id) + $queryResults += $info + } + $machineList = $queryResults + return $machineList +} + +function Get-HVMachineSummary { +<# +.Synopsis + Gets virtual Machine(s) summary with given search parameters. + +.DESCRIPTION + Queries and returns virtual machines information, the machines list would be determined + based on queryable fields poolName, dnsName, machineName, state. When more than one + fields are used for query the virtual machines which satisfy all fields criteria would be returned. + +.PARAMETER PoolName + Pool name to query for. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has name same as value will be returned. + +.PARAMETER MachineName + The name of the Machine to query for. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has display name same as value will be returned. + +.PARAMETER DnsName + DNS name for the Machine to filter with. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has display name same as value will be returned. + +.PARAMETER State + The basic state of the Machine to filter with. + If the value is null or not provided then filter will not be applied, + otherwise the virtual machines which has display name same as value will be returned. + +.PARAMETER SuppressInfo + Suppress text info, when no machine found with given search parameters + +.PARAMETER HvServer + Reference to Horizon View Server to query the virtual machines from. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Get-HVMachineSummary -PoolName 'ManualPool' + Queries VM(s) with given parameter poolName + +.EXAMPLE + Get-HVMachineSummary -MachineName 'PowerCLIVM' + Queries VM(s) with given parameter machineName + +.EXAMPLE + Get-HVMachineSummary -State CUSTOMIZING + Queries VM(s) with given parameter vm state + +.EXAMPLE + Get-HVMachineSummary -DnsName 'powercli-*' + Queries VM(s) with given parameter dnsName with wildcard character * + +.OUTPUTS + Returns list of objects of type MachineNamesView + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + + param( + [Parameter(Mandatory = $false)] + [string] + $PoolName, + + [Parameter(Mandatory = $false)] + [string] + $MachineName, + + [Parameter(Mandatory = $false)] + [string] + $DnsName, + + [Parameter(Mandatory = $false)] + [ValidateSet('PROVISIONING','PROVISIONING_ERROR','WAIT_FOR_AGENT','CUSTOMIZING', + 'DELETING','MAINTENANCE','ERROR','PROVISIONED','AGENT_UNREACHABLE','UNASSIGNED_USER_CONNECTED', + 'CONNECTED','UNASSIGNED_USER_DISCONNECTED','DISCONNECTED','AGENT_ERR_STARTUP_IN_PROGRESS', + 'AGENT_ERR_DISABLED','AGENT_ERR_INVALID_IP','AGENT_ERR_NEED_REBOOT','AGENT_ERR_PROTOCOL_FAILURE', + 'AGENT_ERR_DOMAIN_FAILURE','AGENT_CONFIG_ERROR','ALREADY_USED','AVAILABLE','IN_PROGRESS','DISABLED', + 'DISABLE_IN_PROGRESS','VALIDATING','UNKNOWN')] + [string] + $State, + + [Parameter(Mandatory = $false)] + [string] + $JsonFilePath, + + [Parameter(Mandatory = $false)] + [boolean] + $SuppressInfo = $false, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + + $machineList = Find-HVMachine -Param $PSBoundParameters + if (!$machineList -and !$SuppressInfo) { + Write-Host "Get-HVMachineSummary: No machine(s) found with given search parameters" + } + return $machineList +} + +function Get-HVPoolSpec { +<# +.Synopsis + Gets desktop specification + +.DESCRIPTION + Converts DesktopInfo Object to DesktopSpec. Also Converts view API Ids to human readable names + +.PARAMETER DesktopInfo + An object with detailed description of a desktop instance. + +.PARAMETER HvServer + Reference to Horizon View Server to query the virtual machines from. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Get-HVPoolSpec -DesktopInfo $DesktopInfoObj + Converts DesktopInfo to DesktopSpec + +.EXAMPLE + Get-HVPool -PoolName 'LnkClnJson' | Get-HVPoolSpec -FilePath "C:\temp\LnkClnJson.json" + Converts DesktopInfo to DesktopSpec and also dumps json object + +.OUTPUTS + Returns desktop specification + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + + param( + [Parameter(Mandatory = $true, ValueFromPipeline = $true)] + [VMware.HV.DesktopInfo] + $DesktopInfo, + + [Parameter(Mandatory = $false)] + [String] + $FilePath, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + $DesktopSpec = New-Object VMware.HV.DesktopSpec + $DesktopPsObj = (($DesktopSpec | ConvertTo-Json -Depth 14) | ConvertFrom-Json) + $DesktopInfoPsObj = (($DesktopInfo | ConvertTo-Json -Depth 14) | ConvertFrom-Json) + $DesktopPsObj.Type = $DesktopInfoPsObj.Type + $DesktopPsObj.DesktopSettings = $DesktopInfoPsObj.DesktopSettings + + $entityId = New-Object VMware.HV.EntityId + $entityId.Id = $DesktopInfoPsObj.Base.AccessGroup.Id + $DesktopPsObj.Base = New-Object PsObject -Property @{ + name = $DesktopInfoPsObj.Base.Name; + displayName = $DesktopInfoPsObj.Base.displayName; + accessGroup = (Get-HVInternalName -EntityId $entityId); + description = $DesktopInfoPsObj.Base.description; + } + + if (! $DesktopInfoPsObj.GlobalEntitlementData.GlobalEntitlement) { + $DesktopPsObj.GlobalEntitlementData = $null + } else { + $entityId.Id = $DesktopInfoPsObj.GlobalEntitlementData.GlobalEntitlement.Id + $DesktopPsObj.GlobalEntitlementData = Get-HVInternalName -EntityId $entityId + } + + Switch ($DesktopInfo.Type) { + "AUTOMATED" { + $specificNamingSpecObj = $null + if ("SPECIFIED" -eq $DesktopInfoPsObj.AutomatedDesktopData.vmNamingSettings.NamingMethod) { + $specificNamingSpecObj = New-Object PsObject -Property @{ + specifiedNames = $null; + startMachinesInMaintenanceMode = $DesktopInfoPsObj.AutomatedDesktopData.vmNamingSettings.SpecificNamingSettings.StartMachinesInMaintenanceMode; + numUnassignedMachinesKeptPoweredOn = $DesktopInfoPsObj.AutomatedDesktopData.vmNamingSettings.SpecificNamingSettings.NumUnassignedMachinesKeptPoweredOn; + } + } + $vmNamingSpecObj = New-Object PsObject -Property @{ + namingMethod = $DesktopInfoPsObj.AutomatedDesktopData.vmNamingSettings.NamingMethod; + patternNamingSettings = $DesktopInfoPsObj.AutomatedDesktopData.VmNamingSettings.PatternNamingSettings; + specificNamingSpec = $specificNamingSpecObj; + } + $virtualCenterProvisioningDataObj = New-Object PsObject @{ + template = $null; + parentVm = $null; + snapshot = $null; + datacenter = $null; + vmFolder = $null; + hostOrCluster = $null; + resourcePool= $null; + } + $ProvisioningSettingsObj = $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.Datacenter){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.Datacenter.Id + $virtualCenterProvisioningDataObj.Datacenter = Get-HVInternalName -EntityId $entityId + } + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.HostOrCluster){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.HostOrCluster.Id + $virtualCenterProvisioningDataObj.HostOrCluster = Get-HVInternalName -EntityId $entityId + } + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.ResourcePool){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.ResourcePool.Id + $virtualCenterProvisioningDataObj.ResourcePool = Get-HVInternalName -EntityId $entityId + } + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.ParentVm){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.ParentVm.Id + $virtualCenterProvisioningDataObj.ParentVm = Get-HVInternalName -EntityId $entityId ` + -VcId $DesktopInfo.AutomatedDesktopData.virtualCenter + } + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.Snapshot){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.Snapshot.Id + $virtualCenterProvisioningDataObj.Snapshot = Get-HVInternalName -EntityId $entityId ` + -BaseImageVmId $DesktopInfo.AutomatedDesktopData.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData.ParentVm + } + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.Template){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.Template.Id + $virtualCenterProvisioningDataObj.Template = Get-HVInternalName -EntityId $entityId + } + if ($ProvisioningSettingsObj.VirtualCenterProvisioningData.VmFolder){ + $entityId.Id = $ProvisioningSettingsObj.VirtualCenterProvisioningData.VmFolder.Id + $virtualCenterProvisioningDataObj.VmFolder = Get-HVInternalName -EntityId $entityId + } + + $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings.VirtualCenterProvisioningData = ` + $virtualCenterProvisioningDataObj + $datastores = $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.datastores + $dataStoresObj = Get-DataStoreName -datastores $datastores + $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.datastores = ` + $dataStoresObj + $virtualCenterStorageSettingsObj = ` + $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings.virtualCenterStorageSettings + if($virtualCenterStorageSettingsObj.replicaDiskDatastore) { + $entityId.Id = $virtualCenterStorageSettingsObj.replicaDiskDatastore.Id + $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.replicaDiskDatastore =` + Get-HVInternalName -EntityId $entityId + } + if($virtualCenterStorageSettingsObj.persistentDiskSettings) { + $datastores = $virtualCenterStorageSettingsObj.persistentDiskSettings.persistentDiskDatastores + $dataStoresObj = Get-DataStoreName -datastores $datastores + $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings.virtualCenterStorageSettings.persistentDiskSettings.persistentDiskDatastores = ` + $dataStoresObj + } + if ($DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.domainAdministrator) { + $entityId.Id = $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.domainAdministrator.Id + $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.domainAdministrator = Get-HVInternalName -EntityId $entityId + } + if ($DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.adContainer) { + $entityId.Id = $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.adContainer.Id + $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.adContainer = Get-HVInternalName -EntityId $entityId + } + if ($DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.sysprepCustomizationSettings) { + $entityId.Id = ` + $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.sysprepCustomizationSettings.customizationSpec.Id + $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.sysprepCustomizationSettings.customizationSpec = ` + Get-HVInternalName -EntityId $entityId + } + if ($DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.cloneprepCustomizationSettings) { + $entityId.Id = ` + $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.cloneprepCustomizationSettings.instantCloneEngineDomainAdministrator.Id + $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings.cloneprepCustomizationSettings.instantCloneEngineDomainAdministrator = ` + Get-HVInternalName -EntityId $entityId + } + + $DesktopPsObj.AutomatedDesktopSpec = New-Object PsObject -Property @{ + provisioningType = $DesktopInfoPsObj.AutomatedDesktopData.ProvisioningType; + virtualCenter = $null; + userAssignment = $DesktopInfoPsObj.AutomatedDesktopData.UserAssignment; + virtualCenterProvisioningSettings = $DesktopInfoPsObj.AutomatedDesktopData.VirtualCenterProvisioningSettings; + virtualCenterManagedCommonSettings = $DesktopInfoPsObj.AutomatedDesktopData.virtualCenterManagedCommonSettings; + customizationSettings = $DesktopInfoPsObj.AutomatedDesktopData.customizationSettings; + vmNamingSpec = $VmNamingSpecObj; + } + if ($DesktopInfoPsObj.AutomatedDesktopData.virtualCenter) { + $entityId.Id = $DesktopInfoPsObj.AutomatedDesktopData.virtualCenter.Id + $DesktopPsObj.AutomatedDesktopSpec.virtualCenter = Get-HVInternalName ` + -EntityId $entityId + } + break + } + "MANUAL" { + $DesktopPsObj.ManualDesktopSpec = New-Object PsObject -Property @{ + userAssignment = $DesktopInfoPsObj.ManualDesktopData.UserAssignment; + source = $DesktopInfoPsObj.ManualDesktopData.Source; + virtualCenter = $null; + machines = $null; + viewStorageAcceleratorSettings = $DesktopInfoPsObj.ManualDesktopData.ViewStorageAcceleratorSettings; + virtualCenterManagedCommonSettings = $DesktopInfoPsObj.ManualDesktopData.VirtualCenterManagedCommonSettings; + } + if ($DesktopInfoPsObj.ManualDesktopData.virtualCenter) { + $entityId.Id = $DesktopInfoPsObj.ManualDesktopData.virtualCenter.Id + $DesktopPsObj.ManualDesktopSpec.virtualCenter = Get-HVInternalName ` + -EntityId $entityId + } + break + } + "RDS" { + $DesktopPsObj.rdsDesktopSpec = New-Object PsObject -Property @{ + farm = $null; + } + break + } + } + $DesktopSpecJson = ($DesktopPsObj | ConvertTo-Json -Depth 14) + if ($filePath) { + $DesktopSpecJson | Out-File -FilePath $filePath + } + return $DesktopSpecJson +} + +function Get-DataStoreName { + param( + [Parameter(Mandatory = $true)] + $datastores + ) + $dataStoresObj = @() + $entityId = New-Object VMware.Hv.EntityId + $datastores | % { + $entityId.Id = $_.datastore.Id + $dataStoresObj += , (New-Object PsObject -Property @{ + datastore = Get-HVInternalName -EntityId $entityId; + storageOvercommit = $_.storageOvercommit; + }) + } + return $dataStoresObj +} + +function Get-HVInternalName { +<# +.Synopsis + Gets human readable name + +.DESCRIPTION + Converts Horizon API Ids to human readable names. Horizon API Ids are base64 encoded, this function + will decode and returns internal/human readable names. + +.PARAMETER EntityId + Representation of a manageable entity id. + +.PARAMETER HvServer + Reference to Horizon View Server to query the virtual machines from. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Get-HVInternalName -EntityId $entityId + Decodes Horizon API Id and returns human readable name + +.OUTPUTS + Returns human readable name + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [VMware.HV.EntityId] + $EntityId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [VMware.HV.VirtualCenterId] + $VcId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [VMware.HV.BaseImageVmId] + $BaseImageVmId, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $tokens = ($EntityId.id -split "/") + $serviceName = $tokens[0] + Switch ($serviceName) { + 'VirtualCenter' { + $vc_id = New-Object VMware.HV.VirtualCenterId + $vc_id.Id = $EntityId.Id + return ($services.VirtualCenter.VirtualCenter_Get($vc_id)).serverSpec.serverName + } + 'InstantCloneEngineDomainAdministrator' { + $Icid = New-Object VMware.HV.InstantCloneEngineDomainAdministratorId + $Icid.Id = $EntityId.Id + $Info = $services.InstantCloneEngineDomainAdministrator.InstantCloneEngineDomainAdministrator_Get($Icid) + return $Info.Base.Username + } + 'BaseImageVm' { + $info = $services.BaseImageVm.BaseImageVm_List($VcId) | where { $_.id.id -eq $EntityId.id } + return $info.name + } + 'BaseImageSnapshot' { + $info = $services.BaseImageSnapshot.BaseImageSnapshot_List($BaseImageVmId) | where { $_.id.id -eq $EntityId.id } + return $info.name + } + 'VmTemplate' { + $info = $services.VmTemplate.VmTemplate_List($VcId) | where { $_.id.id -eq $EntityId.id } + return $info.name + } + 'ViewComposerDomainAdministrator' { + $AdministratorId = New-Object VMware.HV.ViewComposerDomainAdministratorId + $AdministratorId.id = $EntityId.id + $info = $services.ViewComposerDomainAdministrator.ViewComposerDomainAdministrator_Get($AdministratorId) + return $info.base.userName + } + default { + $base64String = $tokens[$tokens.Length-1] + $mod = $base64String.Length % 4 + if ($mod -ne 0) { + #Length of a string must be multiples of 4 + $base64String = $base64String.PadRight(($base64String.Length + (4 - $mod)), "=") + } + #Convert 4 bytes to 3 bytes base64 decoding + return ([System.Text.Encoding]::ASCII.GetString([System.Convert]:: ` + FromBase64String($base64String))) + } + } + } + end { + [System.gc]::collect() + } +} + + +function Get-UserInfo { + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true)] + [ValidatePattern("^.+?[@\\].+?$")] + [String] + $UserName + ) + + if ($UserName -match '^.+?[@].+?$') { + $info = $UserName -split "@" + $Domain = $info[1] + $Name = $Info[0] + } else { + $info = $UserName -split "\\" + $Domain = $info[0] + $Name = $Info[1] + } + return @{'Name' = $Name; 'Domain' = $Domain} +} + +function New-HVEntitlement { +<# +.Synopsis + Associates a user/group with a resource + +.DESCRIPTION + This represents a simple association between a single user/group and a resource that they can be assigned. + +.PARAMETER User + User principal name of user or group + +.PARAMETER ResourceName + The resource(Application, Desktop etc.) name. + Supports only wildcard character '*' when resource type is desktop. + +.PARAMETER Resource + Object(s) of the resource(Application, Desktop etc.) to entitle + +.PARAMETER ResourceType + Type of Resource(Application, Desktop etc) + +.PARAMETER Type + Whether or not this is a group or a user. + +.PARAMETER HvServer + Reference to Horizon View Server. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + New-HVEntitlement -User 'administrator@adviewdev.eng.vmware.com' -ResourceName 'InsClnPol' -Confirm:$false + Associate a user/group with a pool + +.EXAMPLE + New-HVEntitlement -User 'adviewdev\administrator' -ResourceName 'Calculator' -ResourceType Application + Associate a user/group with a application + +.EXAMPLE + New-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'UrlSetting1' -ResourceType URLRedirection + Associate a user/group with a URLRedirection settings + +.EXAMPLE + New-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'GE1' -ResourceType GlobalEntitlement + Associate a user/group with a desktop entitlement + +.EXAMPLE + New-HVEntitlement -User 'adviewdev\administrator' -ResourceName 'GEAPP1' -ResourceType GlobalApplicationEntitlement + Associate a user/group with a application entitlement + +.EXAMPLE + $pools = Get-HVPool; $pools | New-HVEntitlement -User 'adviewdev\administrator' -Confirm:$false + Associate a user/group with list of pools + + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true)] + [ValidatePattern("^.+?[@\\].+?$")] + [String] + $User, + + [Parameter(Mandatory = $true,ParameterSetName ='Default')] + [ValidateNotNullOrEmpty()] + [String] + $ResourceName, + + [Parameter(Mandatory = $true,ValueFromPipeline = $true,ParameterSetName ='PipeLine')] + $Resource, + + [Parameter(Mandatory = $false)] + [ValidateSet('Application','Desktop','GlobalApplicationEntitlement','GlobalEntitlement', + 'URLRedirection')] + [String] + $ResourceType = 'Desktop', + + [Parameter(Mandatory = $false)] + [ValidateSet('User','Group')] + [String] + $Type = 'User', + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + $userInfo = Get-UserInfo -UserName $User + $UserOrGroupName = $userInfo.Name + $Domain = $userInfo.Domain + $IsGroup = ($Type -eq 'Group') + $filter1 = Get-HVQueryFilter 'base.name' -Eq $UserOrGroupName + $filter2 = Get-HVQueryFilter 'base.domain' -Eq $Domain + $filter3 = Get-HVQueryFilter 'base.group' -Eq $IsGroup + $andFilter = Get-HVQueryFilter -And -Filters @($filter1, $filter2, $filter3) + $results = Get-HVQueryResult -EntityType ADUserOrGroupSummaryView -Filter $andFilter -HvServer $HvServer + if ($results.length -ne 1) { + Write-Host "Unable to find specific user or group with given search parameters" + return + } + $ResourceObjs = $null + $info = $services.PodFederation.PodFederation_get() + switch($ResourceType){ + "Desktop" { + if ($ResourceName) { + $ResourceObjs = Get-HVPool -PoolName $ResourceName -suppressInfo $true -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No pool found with given resourceName: " $ResourceName + return + } + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Resource) { + foreach ($item in $Resource) { + if ($item.GetType().name -eq 'DesktopInfo') { + $ResourceObjs += ,$item + } + elseif ($item.GetType().name -eq 'DesktopSummaryView') { + $ResourceObjs += ,$item + } + else { + Write-Error "In pipeline didn't received object(s) of expected type DesktopSummaryView/DesktopInfo" + return + } + } + } + } + "Application" { + if ($ResourceName) { + $eqFilter = Get-HVQueryFilter 'data.name' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType ApplicationInfo -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No Application found with given resourceName: " $ResourceName + return + } + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Resource) { + foreach ($item in $Resource) { + if ($item.GetType().name -eq 'ApplicationInfo') { + $ResourceObjs += ,$item + + } else { + Write-Error "In pipeline didn't received object(s) of expected type ApplicationInfo" + return + } + } + } + } + "URLRedirection" { + if ($ResourceName) { + $UrlRedirectionList = $services.URLRedirection.URLRedirection_List() + $ResourceObjs = $UrlRedirectionList | Where-Object { $_.urlRedirectionData.displayName -like $ResourceName} + if (! $ResourceObjs) { + Write-Host "No URLRedirectionData found with given resourceName: " $ResourceName + return + } + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Resource) { + foreach ($item in $Resource) { + if ($item.GetType().name -eq 'URLRedirectionInfo') { + $ResourceObjs += ,$item + } else { + Write-Error "In pipeline didn't received object(s) of expected type URLRedirectionInfo" + return + } + } + } + } + "GlobalApplicationEntitlement" { + if ("ENABLED" -eq $info.localPodStatus.status) { + if ($ResourceName) { + $eqFilter = Get-HVQueryFilter 'base.displayName' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType GlobalApplicationEntitlementInfo -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No globalApplicationEntitlementInfo found with given resourceName: " $ResourceName + return + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Resource) { + foreach ($item in $Resource) { + if ($item.GetType().name -eq 'GlobalApplicationEntitlementInfo') { + $ResourceObjs += ,$item + } else { + Write-Error "In pipeline didn't received object(s) of expected type globalApplicationEntitlementInfo" + return + } + } + } + } + } else { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + } + "GlobalEntitlement" { + if ("ENABLED" -eq $info.localPodStatus.status) { + if ($ResourceName) { + $eqFilter = Get-HVQueryFilter 'base.displayName' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType GlobalEntitlementSummaryView -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No globalEntitlementSummary found with given resourceName: " $ResourceName + return + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Resource) { + foreach ($item in $Resource) { + if ($item.GetType().name -eq 'GlobalEntitlementSummaryView') { + $ResourceObjs += ,$item + } else { + Write-Error "In pipeline didn't received object(s) of expected type GlobalEntitlementSummaryView" + return + } + } + } + } + } else { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + } + } + $base = New-Object VMware.HV.UserEntitlementBase + $base.UserOrGroup = $results.id + Write-host $ResourceObjs.Length " resource(s) will be entitled with UserOrGroup: " $User + foreach ($ResourceObj in $ResourceObjs) { + $base.Resource = $ResourceObj.id + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $id = $services.UserEntitlement.UserEntitlement_Create($base) + } + } + } + end { + [System.gc]::collect() + } +} + + +function Get-HVEntitlement { +<# +.Synopsis + Gets association data between a user/group and a resource + +.DESCRIPTION + Provides entitlement Info between a single user/group and a resource that they can be assigned. + +.PARAMETER User + User principal name of user or group + +.PARAMETER ResourceName + The resource(Application, Desktop etc.) name. + Supports only wildcard character '*' when resource type is desktop. + +.PARAMETER Resource + Object(s) of the resource(Application, Desktop etc.) to entitle + +.PARAMETER ResourceType + Type of Resource(Application, Desktop etc.) + +.PARAMETER Type + Whether or not this is a group or a user. + +.PARAMETER HvServer + Reference to Horizon View Server. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Get-HVEntitlement -ResourceType Application + Gets all the entitlements related to application pool + +.EXAMPLE + Get-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'calculator' -ResourceType Application + Gets entitlements specific to user or group name and application resource + +.EXAMPLE + Get-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'UrlSetting1' -ResourceType URLRedirection + Gets entitlements specific to user or group and URLRedirection resource + +.EXAMPLE + Get-HVEntitlement -User 'administrator@adviewdev.eng.vmware.com' -ResourceName 'GE1' -ResourceType GlobalEntitlement + Gets entitlements specific to user or group and GlobalEntitlement resource + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $false)] + [ValidatePattern("^.+?[@\\].+?$")] + [String] + $User, + + [Parameter(Mandatory = $false)] + [ValidateSet('User','Group')] + [String] + $Type = 'User', + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [String] + $ResourceName, + + [Parameter(Mandatory = $false)] + [ValidateSet('Application','Desktop','GlobalApplicationEntitlement','GlobalEntitlement', + 'URLRedirection')] + [String] + $ResourceType = 'Desktop', + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $AndFilter = @() + $results = @() + $ResourceObjs = $null + if ($User) { + $userInfo = Get-UserInfo -UserName $User + $UserOrGroupName = $userInfo.Name + $Domain = $userInfo.Domain + $nameFilter = Get-HVQueryFilter 'base.name' -Eq $UserOrGroupName + $AndFilter += $nameFilter + $doaminFilter = Get-HVQueryFilter 'base.domain' -Eq $Domain + $AndFilter += $doaminFilter + } + $IsGroup = ($Type -eq 'Group') + $groupFilter = Get-HVQueryFilter 'base.group' -Eq $IsGroup + $AndFilter += $groupFilter + $info = $services.PodFederation.PodFederation_get() + $cpaEnabled = ("ENABLED" -eq $info.localPodStatus.status) + switch($ResourceType) { + "Desktop" { + if ($ResourceName) { + $ResourceObjs = Get-HVPool -PoolName $ResourceName -suppressInfo $true -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No pool found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'localData.desktops' -Contains ([VMware.Hv.DesktopId[]]$ResourceObjs.Id) + } + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $AndFilter -HvServer $HvServer) + $results = $results | where {$_.localData.desktops -ne $null} + } + "Application" { + if ($ResourceName) { + $eqFilter = Get-HVQueryFilter 'data.name' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType ApplicationInfo -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No Application found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'localData.applications' -Contains ([VMware.Hv.ApplicationId[]]$ResourceObjs.Id) + } + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $AndFilter -HvServer $HvServer) + $results = $results | where {$_.localData.applications -ne $null} + } + "URLRedirection" { + $localFilter = @() + $globalFilter = @() + $localFilter += $AndFilter + $globalFilter += $AndFilter + if ($ResourceName) { + $UrlRedirectionList = $services.URLRedirection.URLRedirection_List() + $ResourceObjs = $UrlRedirectionList | Where-Object { $_.urlRedirectionData.displayName -like $ResourceName} + if (! $ResourceObjs) { + Write-Host "No URLRedirectionData found with given resourceName: " $ResourceName + return + } + $localFilter += Get-HVQueryFilter 'localData.urlRedirectionSettings' -Contains ([VMware.Hv.URLRedirectionId[]]$ResourceObjs.Id) + if ($cpaEnabled) { + $globalFilter += Get-HVQueryFilter 'globalData.urlRedirectionSettings' -Contains ([VMware.Hv.URLRedirectionId[]]$ResourceObjs.Id) + } + } + $localFilter = Get-HVQueryFilter -And -Filters $localFilter + $localResults = Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $localFilter -HvServer $HvServer + $results += ($localResults | where {$_.localData.urlRedirectionSettings -ne $null}) + if ($cpaEnabled) { + $globalFilter = Get-HVQueryFilter -And -Filters $globalFilter + $globalResults = Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $globalFilter -HvServer $HvServer + $globalResults = $globalResults | where {$_.globalData.urlRedirectionSettings -ne $null} + $results += $globalResults + } + } + "GlobalApplicationEntitlement" { + if (! $cpaEnabled) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + if ($ResourceName) { + $eqFilter = Get-HVQueryFilter 'base.displayName' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType GlobalApplicationEntitlementInfo -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No globalApplicationEntitlementInfo found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'globalData.globalApplicationEntitlements' -Contains ([VMware.Hv.GlobalApplicationEntitlementId[]]$ResourceObjs.Id) + } + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer) + $results = $results| where {$_.globalData.globalApplicationEntitlements -ne $null} + } + "GlobalEntitlement" { + if (! $cpaEnabled) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + if ($ResourceName) { + $eqFilter = Get-HVQueryFilter 'base.displayName' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType GlobalEntitlementSummaryView -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No globalEntitlementSummary found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'globalData.globalEntitlements' -Contains ([VMware.Hv.GlobalEntitlementId[]]$ResourceObjs.Id) + } + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer) + $results = $results | where {$_.globalData.globalEntitlements -ne $null} + } + } + if (! $results) { + Write-Host "Get-HVEntitlement: No entitlements found with given search parameters" + break + } + return $results + } + end { + [System.gc]::collect() + } +} + +function Remove-HVEntitlement { +<# +.Synopsis + Deletes association data between a user/group and a resource + +.DESCRIPTION + Removes entitlement between a single user/group and a resource that already been assigned. + +.PARAMETER User + User principal name of user or group + +.PARAMETER ResourceName + The resource(Application, Desktop etc.) name. + Supports only wildcard character '*' when resource type is desktop. + +.PARAMETER Resource + Object(s) of the resource(Application, Desktop etc.) to entitle + +.PARAMETER ResourceType + Type of Resource(Application, Desktop etc) + +.PARAMETER Type + Whether or not this is a group or a user. + +.PARAMETER HvServer + Reference to Horizon View Server. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Remove-HVEntitlement -User 'administrator@adviewdev' -ResourceName LnkClnJSon -Confirm:$false + Deletes entitlement between a user/group and a pool resource + +.EXAMPLE + Remove-HVEntitlement -User 'adviewdev\puser2' -ResourceName 'calculator' -ResourceType Application + Deletes entitlement between a user/group and a Application resource + +.EXAMPLE + Remove-HVEntitlement -User 'adviewdev\administrator' -ResourceName 'GEAPP1' -ResourceType GlobalApplicationEntitlement + Deletes entitlement between a user/group and a GlobalApplicationEntitlement resource + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true)] + [ValidatePattern("^.+?[@\\].+?$")] + [String] + $User, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [String] + $ResourceName, + + [Parameter(Mandatory = $false)] + [ValidateSet('User','Group')] + [String] + $Type = 'User', + + [Parameter(Mandatory = $false)] + [ValidateSet('Application','Desktop','GlobalApplicationEntitlement','GlobalEntitlement', + 'URLRedirection')] + [String] + $ResourceType = 'Desktop', + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + $AndFilter = @() + $results = $null + $userInfo = Get-UserInfo -UserName $User + $UserOrGroupName = $userInfo.Name + $Domain = $userInfo.Domain + $nameFilter = Get-HVQueryFilter 'base.name' -Eq $UserOrGroupName + $doaminFilter = Get-HVQueryFilter 'base.domain' -Eq $Domain + $IsGroup = ($Type -eq 'Group') + $groupFilter = Get-HVQueryFilter 'base.group' -Eq $IsGroup + [VMware.Hv.UserEntitlementId[]] $userEntitlements = $null + if ($ResourceName) { + $info = $services.PodFederation.PodFederation_get() + switch($ResourceType) { + "Desktop" { + $ResourceObjs = Get-HVPool -PoolName $ResourceName -suppressInfo $true -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No pool found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'localData.desktops' -Contains ([VMware.HV.DesktopId[]] $ResourceObjs.Id) + $filters = Get-HVQueryFilter -And -Filters $AndFilter + $results = Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $filters -HvServer $HvServer + if ($results) { + foreach ($result in $Results) { + $userEntitlements = $result.localData.desktopUserEntitlements + Write-Host $userEntitlements.Length " desktopUserEntitlement(s) will be removed for UserOrGroup " $user + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements) + } + } + } + } + "Application" { + $eqFilter = Get-HVQueryFilter 'data.name' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType ApplicationInfo -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No Application found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'localData.applications' -Contains ([VMware.HV.ApplicationId[]] $ResourceObjs.Id) + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $AndFilter -HvServer $HvServer + if ($results) { + foreach ($result in $Results) { + $userEntitlements = $result.localData.applicationUserEntitlements + Write-Host $userEntitlements.Length " applicationUserEntitlement(s) will be removed for UserOrGroup " $user + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements) + } + } + } + } + "URLRedirection" { + $UrlRedirectionList = $services.URLRedirection.URLRedirection_List() + $ResourceObjs = $UrlRedirectionList | Where-Object { $_.urlRedirectionData.displayName -like $ResourceName} + if (! $ResourceObjs) { + Write-Host "No URLRedirectionData found with given resourceName: " $ResourceName + return + } + $localFilter = @() + $localFilter += $AndFilter + $localFilter += (Get-HVQueryFilter 'localData.urlRedirectionSettings' -Contains ([VMware.HV.URLRedirectionId[]]$ResourceObjs.Id)) + $localFilter = Get-HVQueryFilter -And -Filters $localFilter + $results = Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $localFilter -HvServer $HvServer + if ("ENABLED" -eq $info.localPodStatus.status) { + $globalFilter = @() + $globalFilter += $AndFilter + $globalFilter += Get-HVQueryFilter 'globalData.urlRedirectionSettings' -Contains ([VMware.HV.URLRedirectionId[]]$ResourceObjs.Id) + $globalFilter = Get-HVQueryFilter -And -Filters $globalFilter + $results += Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $globalFilter -HvServer $HvServer + } + if ($results) { + foreach ($result in $Results) { + if ($result.GetType().Name -eq 'EntitledUserOrGroupLocalSummaryView') { + $userEntitlements = $result.localData.urlRedirectionUserEntitlements + Write-Host $userEntitlements.Length " urlRedirectionUserEntitlement(s) will be removed for UserOrGroup " $user + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements) + } + } else { + $userEntitlements = $result.globalData.urlRedirectionUserEntitlements + Write-Host $userEntitlements.Length " urlRedirectionUserEntitlement(s) will be removed for UserOrGroup " $user + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements) + } + } + } + } + } + "GlobalApplicationEntitlement" { + if ("ENABLED" -ne $info.localPodStatus.status) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + $eqFilter = Get-HVQueryFilter 'base.displayName' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType GlobalApplicationEntitlementInfo -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No globalApplicationEntitlementInfo found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'globalData.globalApplicationEntitlements' -Contains ([VMware.Hv.GlobalApplicationEntitlementId[]]$ResourceObjs.Id) + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer + if ($results) { + foreach ($result in $Results) { + $userEntitlements = $result.globalData.globalUserApplicationEntitlements + Write-Host $userEntitlements.Length " GlobalApplicationEntitlement(s) will be removed for UserOrGroup " $user + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements) + } + } + } + } + "GlobalEntitlement" { + if ("ENABLED" -ne $info.localPodStatus.status) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + $eqFilter = Get-HVQueryFilter 'base.displayName' -Eq $ResourceName + $ResourceObjs = Get-HVQueryResult -EntityType GlobalEntitlementSummaryView -Filter $eqFilter -HvServer $HvServer + if (! $ResourceObjs) { + Write-Host "No globalEntitlementSummary found with given resourceName: " $ResourceName + return + } + $AndFilter += Get-HVQueryFilter 'globalData.globalEntitlements' -Contains ([VMware.Hv.GlobalEntitlementId[]]$ResourceObjs.Id) + $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter + $results = Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer + if ($results) { + foreach ($result in $Results) { + $userEntitlements = $result.globalData.globalUserEntitlements + Write-Host $userEntitlements.Length " GlobalEntitlement(s) will be removed for UserOrGroup " $user + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) { + $services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements) + } + } + + } + } + } + } + if (! $results) { + Write-Host "Remove-HVEntitlement: No entitlements found with given search parameters" + return + } + } + end { + [System.gc]::collect() + } +} + +function Set-HVMachine { +<# +.Synopsis + Sets existing virtual Machine(s). + +.DESCRIPTION + This cmdlet allows user to edit Machine configuration by passing key/value pair. + Allows the machine in to Maintenance mode and vice versa + +.PARAMETER MachineName + The name of the Machine to edit. + +.PARAMETER Machine + Object(s) of the virtual Machine(s) to edit. + +.PARAMETER Maintenance + The virtual machine is in maintenance mode. Users cannot log in or use the virtual machine + +PARAMETER Key + Property names path separated by . (dot) from the root of machine info spec. + +.PARAMETER Value + Property value corresponds to above key name. + +.PARAMETER HvServer + Reference to Horizon View Server to query the virtual machines from. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Set-HVMachine -MachineName 'Agent_Praveen' -Maintenance ENTER_MAINTENANCE_MODE + Moving the machine in to Maintenance mode using machine name + +.EXAMPLE + Get-HVMachine -MachineName 'Agent_Praveen' | Set-HVMachine -Maintenance ENTER_MAINTENANCE_MODE + Moving the machine in to Maintenance mode using machine object(s) + +.EXAMPLE + $machine = Get-HVMachine -MachineName 'Agent_Praveen'; Set-HVMachine -Machine $machine -Maintenance EXIT_MAINTENANCE_MODE + Moving the machine in to Maintenance mode using machine object(s) + +.OUTPUTS + None + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + + param( + + [Parameter(Mandatory = $true ,ParameterSetName = 'option')] + [string] + $MachineName, + + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'pipeline')] + $Machine, + + [Parameter(Mandatory = $false)] + [ValidateSet('ENTER_MAINTENANCE_MODE', 'EXIT_MAINTENANCE_MODE')] + [string] + $Maintenance, + + [Parameter(Mandatory = $false)] + [string]$Key, + + [Parameter(Mandatory = $false)] + $Value, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + + process { + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + $machineList = @{} + if ($machineName) { + try { + $machines = Get-HVMachineSummary -MachineName $machineName -suppressInfo $true -hvServer $hvServer + } catch { + Write-Error "Make sure Get-HVMachineSummary advanced function is loaded, $_" + break + } + if ($machines) { + foreach ($macineObj in $machines) { + $machineList.add($macineObj.id, $macineObj.base.Name) + } + } + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Machine) { + foreach ($item in $machine) { + if (($item.GetType().name -eq 'MachineNamesView') -or ($item.GetType().name -eq 'MachineInfo')) { + $machineList.add($item.id, $item.Base.Name) + } else { + Write-Error "In pipeline did not get object of expected type MachineNamesView/MachineInfo" + [System.gc]::collect() + return + } + } + } + $updates = @() + if ($key -and $value) { + $updates += Get-MapEntry -key $key -value $value + } elseif ($key -or $value) { + Write-Error "Both key:[$key] and value:[$value] needs to be specified" + } + + if ($Maintenance) { + if ($Maintenance -eq 'ENTER_MAINTENANCE_MODE') { + $updates += Get-MapEntry -key 'managedMachineData.inMaintenanceMode' -value $true + } else { + $updates += Get-MapEntry -key 'managedMachineData.inMaintenanceMode' -value $false + } + } + $machine_helper = New-Object VMware.Hv.MachineService + foreach ($item in $machineList.Keys) { + Write-Host "Updating the Machine: " $machineList.$item + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($machineList.$item)) { + $machine_helper.Machine_Update($services,$item,$updates) + } + } + } + + end { + [System.gc]::collect() + } + +} + +function New-HVGlobalEntitlement { + + <# +.Synopsis + Creates a Global Entitlement. + +.DESCRIPTION + Global entitlements are used to route users to their resources across multiple pods. + These are persisted in a global ldap instance that is replicated across all pods in a linked mode view set. + +.PARAMETER DisplayName + Display Name of Global Entitlement. + +.PARAMETER Type + Specify whether to create desktop/app global entitlement + +.PARAMETER Description + Description of Global Entitlement. + +.PARAMETER Scope + Scope for this global entitlement. Visibility and Placement policies are defined by this value. + +.PARAMETER Dedicated + Specifies whether dedicated/floating resources associated with this global entitlement. + +.PARAMETER FromHome + This value defines the starting location for resource placement and search. + When true, a pod in the user's home site is used to start the search. When false, the current site is used. + +.PARAMETER RequireHomeSite + This value determines whether we fail if a home site isn't defined for this global entitlement. + +.PARAMETER MultipleSessionAutoClean + This value is used to determine if automatic session clean up is enabled. + This cannot be enabled when this Global Entitlement is associated with a Desktop that has dedicated user assignment. + +.PARAMETER Enabled + If this Global Entitlement is enabled. + +.PARAMETER SupportedDisplayProtocols + The set of supported display protocols for the global entitlement. + +.PARAMETER DefaultDisplayProtocol + The default display protocol for the global entitlement. + +.PARAMETER AllowUsersToChooseProtocol + Whether the users can choose the protocol used. + +.PARAMETER AllowUsersToResetMachines + Whether users are allowed to reset/restart their machines. + +.PARAMETER EnableHTMLAccess + If set to true, the desktops that are associated with this GlobalEntitlement must also have HTML Access enabled. + +.PARAMETER HvServer + Reference to Horizon View Server. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + New-HVGlobalEntitlement -DisplayName 'GE_APP' -Type APPLICATION_ENTITLEMENT + Creates new global application entitlement + +.EXAMPLE + New-HVGlobalEntitlement -DisplayName 'GE_DESKTOP' -Type DESKTOP_ENTITLEMENT + Creates new global desktop entitlement + + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + +[CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [String] + $DisplayName, + + [Parameter(Mandatory = $true)] + [ValidateSet('DESKTOP_ENTITLEMENT','APPLICATION_ENTITLEMENT')] + [String] + $Type, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [String] + $Description, + + [Parameter(Mandatory = $false)] + [ValidateSet('LOCAL','SITE','ANY')] + [String] + $Scope = "ANY", + + [Parameter(Mandatory = $false)] + [Boolean] + $Dedicated, + + [Parameter(Mandatory = $false)] + [Boolean] + $FromHome, + + [Parameter(Mandatory = $false)] + [Boolean] + $RequireHomeSite, + + [Parameter(Mandatory = $false)] + [Boolean] + $MultipleSessionAutoClean, + + [Parameter(Mandatory = $false)] + [Boolean] + $Enabled, + + [Parameter(Mandatory = $false)] + [ValidateSet('RDP', 'PCOIP', 'BLAST')] + [String[]] + $SupportedDisplayProtocols = @("PCOIP","BLAST"), + + [Parameter(Mandatory = $false)] + [ValidateSet("PCOIP",'RDP',"BLAST")] + [String] + $DefaultDisplayProtocol = 'PCOIP', + + [Parameter(Mandatory = $false)] + [Boolean] + $AllowUsersToChooseProtocol = $true, + + [Parameter(Mandatory = $false)] + [Boolean] + $AllowUsersToResetMachines = $false, + + [Parameter(Mandatory = $false)] + [Boolean] + $EnableHTMLAccess = $false, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $info = $services.PodFederation.PodFederation_get() + if ("ENABLED" -ne $info.localPodStatus.status) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + if ($Type -eq 'DESKTOP_ENTITLEMENT') { + $GeService = New-Object VMware.HV.GlobalEntitlementService + $geBaseHelper = $GeService.getGlobalEntitlementBaseHelper() + $geBase = $geBaseHelper.getDataObject() + $geBase.Dedicated = $dedicated + $geBase.AllowUsersToResetMachines = $AllowUsersToResetMachines + } else { + $GeService = New-Object VMware.Hv.GlobalApplicationEntitlementService + $geBaseHelper = $GeService.getGlobalApplicationEntitlementBaseHelper() + $geBase = $geBaseHelper.getDataObject() + } + $geBase.DisplayName = $displayName + if ($description) { + $geBaseHelper.setDescription($Description) + } + $geBase.Scope = $Scope + $geBase.FromHome = $fromHome + $geBase.RequireHomeSite = $requireHomeSite + $geBase.MultipleSessionAutoClean = $multipleSessionAutoClean + $geBase.Enabled = $enabled + $geBase.DefaultDisplayProtocol = $defaultDisplayProtocol + $geBase.AllowUsersToChooseProtocol = $AllowUsersToChooseProtocol + $geBase.EnableHTMLAccess = $enableHTMLAccess + $geBase.SupportedDisplayProtocols = $supportedDisplayProtocols + Write-Host "Creating new global entitlement with DisplayName: " $DisplayName + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($displayName)) { + if ($type -eq 'DESKTOP_ENTITLEMENT') { + $GeService.GlobalEntitlement_Create($services, $geBase) + } else { + $GeService.GlobalApplicationEntitlement_Create($services, $geBase) + } + } + } + end { + [System.gc]::collect() + } + +} + + +function Find-HVGlobalEntitlement { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + $Param, + [Parameter(Mandatory = $true)] + [String] + $Type + ) + + # This translates the function arguments into the View API properties that must be queried + $GeSelectors = @{ + 'displayName' = 'base.displayName'; + 'description' = 'base.description'; + } + + $params = $Param + + $query_service_helper = New-Object VMware.Hv.QueryServiceService + $query = New-Object VMware.Hv.QueryDefinition + + $wildCard = $false + #Only supports wild card '*' + if ($params['displayName'] -and $params['displayName'].contains('*')) { + $wildcard = $true + } + + # build the query values + $query.queryEntityType = $Type + if (! $wildcard) { + [VMware.Hv.queryfilter[]]$filterSet = @() + foreach ($setting in $GeSelectors.Keys) { + if ($null -ne $params[$setting]) { + $equalsFilter = New-Object VMware.Hv.QueryFilterEquals + $equalsFilter.memberName = $GeSelectors[$setting] + $equalsFilter.value = $params[$setting] + $filterSet += $equalsFilter + } + } + if ($filterSet.Count -gt 0) { + $andFilter = New-Object VMware.Hv.QueryFilterAnd + $andFilter.Filters = $filterset + $query.Filter = $andFilter + } + $queryResults = $query_service_helper.QueryService_Query($services,$query) + $GeList = $queryResults.results + } + if ($wildcard -or [string]::IsNullOrEmpty($GeList)) { + $query.Filter = $null + $queryResults = $query_service_helper.QueryService_Query($services,$query) + $strFilterSet = @() + foreach ($setting in $GeSelectors.Keys) { + if ($null -ne $params[$setting]) { + if ($wildcard -and ($setting -eq 'displayName') ) { + $strFilterSet += '($_.' + $GeSelectors[$setting] + ' -like "' + $params[$setting] + '")' + } else { + $strFilterSet += '($_.' + $GeSelectors[$setting] + ' -eq "' + $params[$setting] + '")' + } + } + } + $whereClause = [string]::Join(' -and ', $strFilterSet) + $scriptBlock = [Scriptblock]::Create($whereClause) + $GeList = $queryResults.results | where $scriptBlock + } + Return $GeList +} + +function Get-HVGlobalEntitlement { + + <# +.Synopsis + Gets Global Entitlement(s) with given search parameters. + +.DESCRIPTION + Queries and returns global entitlement(s) and global application entitlement(s). + Global entitlements are used to route users to their resources across multiple pods. + +.PARAMETER DisplayName + Display Name of Global Entitlement. + +.PARAMETER Description + Description of Global Entitlement. + +.PARAMETER SuppressInfo + Suppress text info, when no global entitlement(s) found with given search parameters + +.PARAMETER HvServer + Reference to Horizon View Server. If the value is not passed or null then + first element from global:DefaultHVServers would be considered in-place of hvServer + +.EXAMPLE + Get-HVGlobalEntitlement -DisplayName 'GEAPP' + Retrieves global application/desktop entitlement(s) with displayName 'GEAPP' + + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + +[CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [String] + $DisplayName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [String] + $Description, + + [Parameter(Mandatory = $false)] + [boolean] + $SuppressInfo = $false, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $info = $services.PodFederation.PodFederation_get() + if ("ENABLED" -ne $info.localPodStatus.status) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + $result = @() + $result += Find-HVGlobalEntitlement -Param $psboundparameters -Type 'GlobalEntitlementSummaryView' + $result += Find-HVGlobalEntitlement -Param $psboundparameters -Type 'GlobalApplicationEntitlementInfo' + if (!$result -and !$SuppressInfo) { + Write-Host "Get-HVGlobalEntitlement: No global entitlement Found with given search parameters" + } + return $result + } + end { + [System.gc]::collect() + } +} + + +function Remove-HVGlobalEntitlement { + + <# +.Synopsis + Deletes a Global Entitlement. + +.DESCRIPTION + Deletes global entitlement(s) and global application entitlement(s). + Optionally, user can pipe the global entitlement(s) as input to this function. + +.PARAMETER DisplayName + Display Name of Global Entitlement. + +.PARAMETER HvServer + Reference to Horizon View Server. If the value is not passed or null then + first element from global:DefaultHVServers would be considered inplace of hvServer + +.EXAMPLE + Remove-HVGlobalEntitlement -DisplayName 'GE_APP' + Deletes global application/desktop entitlement with displayName 'GE_APP' + +.EXAMPLE + Get-HVGlobalEntitlement -DisplayName 'GE_*' | Remove-HVGlobalEntitlement + Deletes global application/desktop entitlement(s), if displayName matches with 'GE_*' + + +.NOTES + Author : Praveen Mathamsetty. + Author email : pmathamsetty@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2, 7.1.0 + PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + +[CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true, ParameterSetName = 'Default')] + [ValidateNotNullOrEmpty()] + [String] + $DisplayName, + + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'pipeline')] + $GlobalEntitlement, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + process { + $info = $services.PodFederation.PodFederation_get() + if ("ENABLED" -ne $info.localPodStatus.status) { + Write-Host "Multi-DataCenter-View/CPA is not enabled" + return + } + $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys + $GeList = @() + if ($DisplayName) { + try { + $GeList = Get-HVGlobalEntitlement -DisplayName $DisplayName -suppressInfo $true -hvServer $hvServer + } catch { + Write-Error "Make sure Get-HVGlobalEntitlement advanced function is loaded, $_" + break + } + } elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $GlobalEntitlement) { + foreach ($item in $GlobalEntitlement) { + if (($item.GetType().name -ne 'GlobalEntitlementSummaryView') -and ($item.GetType().name -ne 'GlobalApplicationEntitlementInfo')) { + Write-Error "In pipeline did not get object of expected type GlobalApplicationEntitlementInfo/GlobalEntitlementSummaryView" + [System.gc]::collect() + return + } + $GeList += ,$item + } + } + foreach ($item in $GeList) { + Write-Host "Deleting global entitlement with DisplayName: " $item.base.displayName + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($item.base.displayName)) { + if ($item.GetType().Name -eq 'GlobalEntitlementSummaryView') { + $services.GlobalEntitlement.GlobalEntitlement_Delete($item.id) + } else { + $services.GlobalApplicationEntitlement.GlobalApplicationEntitlement_Delete($item.id) + } + } + } + } + end { + [System.gc]::collect() + } + +} + +function Get-HVPodSession { +<# +.Synopsis + Gets the total amount of sessions for all Pods in a Federation +.DESCRIPTION + Gets the total amout of current sessions (connected and disconnected) for all Pods in a Federation (CPA) + based on the global query service. + The default object response is used which contains both success and fault information as well as the + session count per pod and the ID of each pod. +.PARAMETER HvServer + Reference to Horizon View Server to query the virtual machines from. If the value is not passed or null then + first element from global:DefaultHVServers would be considered inplace of hvServer + +.EXAMPLE + Get-HVPodSession + +.OUTPUTS + Returns list of objects of type GlobalSessionPodSessionCounter + +.NOTES + Author : Rasmus Sjoerslev + Author email : rasmus.sjorslev@vmware.com + Version : 1.0 + ===Tested Against Environment==== + Horizon View Server Version : 7.0.2 + PowerCLI Version : PowerCLI 6.5 + PowerShell Version : 5.0 +#> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + + param( + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + $services = Get-ViewAPIService -hvServer $hvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + + $query_service_helper = New-Object VMware.Hv.GlobalSessionQueryServiceService + $count_spec = New-Object VMware.Hv.GlobalSessionQueryServiceCountSpec + $queryResults = @() + + foreach ($pod in $services.Pod.Pod_List()) { + $count_spec.Pod = $pod.Id + $info = $query_service_helper.GlobalSessionQueryService_GetCountWithSpec($services,$count_spec) + + foreach ($res in $info) { + if ($pod.Id.Id -eq $res.Id.Id) { + $queryResults += $res + } + } + } + return $queryResults +} + +function Set-HVApplicationIcon { +<# +.SYNOPSIS + Used to create/update an icon association for a given application. + +.DESCRIPTION + This function is used to create an application icon and associate it with the given application. If the specified icon already exists in the LDAP, it will just updates the icon association to the application. Any of the existing customized icon association to the given application will be overwritten. + +.PARAMETER ApplicationName + Name of the application to which the association to be made. + +.PARAMETER IconPath + Path of the icon. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.EXAMPLE + Creating the icon I1 and associating with application A1. Same command is used for update icon also. + Set-HVApplicationIcon -ApplicationName A1 -IconPath C:\I1.ico -HvServer $hvServer + +.OUTPUTS + None + +.NOTES + Author : Paramesh Oddepally. + Author email : poddepally@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.1 + PowerCLI Version : PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + + param( + [Parameter(Mandatory = $true)] + [string] $ApplicationName, + + [Parameter(Mandatory = $true)] + $IconPath, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object." + break + } + Add-Type -AssemblyName System.Drawing + } + + process { + try { + $appInfo = Get-HVQueryResult -EntityType ApplicationInfo -Filter (Get-HVQueryFilter data.name -Eq $ApplicationName) -HvServer $HvServer + } catch { + # EntityNotFound, InsufficientPermission, InvalidArgument, InvalidType, UnexpectedFault + Write-Error "Error in querying the ApplicationInfo for Application:[$ApplicationName] $_" + break + } + + if ($null -eq $appInfo) { + Write-Error "No application found with specified name:[$ApplicationName]." + break + } + + if (!(Test-Path $IconPath)) { + Write-Error "File:[$IconPath] does not exists" + break + } + + $spec = New-Object VMware.Hv.ApplicationIconSpec + $base = New-Object VMware.Hv.ApplicationIconBase + + try { + $fileHash = Get-FileHash -Path $IconPath -Algorithm MD5 + $base.IconHash = $fileHash.Hash + $base.Data = (Get-Content $iconPath -Encoding byte) + $bitMap = [System.Drawing.Bitmap]::FromFile($iconPath) + $base.Width = $bitMap.Width + $base.Height = $bitMap.Height + $base.IconSource = "broker" + $base.Applications = @($appInfo.Id) + $spec.ExecutionData = $base + } catch { + Write-Error "Error in reading the icon parameters: $_" + break + } + + if ($base.Height -gt 256 -or $base.Width -gt 256) { + Write-Error "Invalid image resolution. Maximum resolution for an icon should be 256*256." + break + } + + $ApplicationIconHelper = New-Object VMware.Hv.ApplicationIconService + try { + $ApplicationIconId = $ApplicationIconHelper.ApplicationIcon_CreateAndAssociate($services, $spec) + } catch { + if ($_.Exception.InnerException.MethodFault.GetType().name.Equals('EntityAlreadyExists')) { + # This icon is already part of LDAP and associated with some other application(s). + # In this case, call updateAssociations + $applicationIconId = $_.Exception.InnerException.MethodFault.Id + Write-Host "Some application(s) already have an association for the specified icon." + $ApplicationIconHelper.ApplicationIcon_UpdateAssociations($services, $applicationIconId, @($appInfo.Id)) + Write-Host "Successfully updated customized icon association for Application:[$ApplicationName]." + break + } + Write-Host "Error in associating customized icon for Application:[$ApplicationName] $_" + break + } + Write-Host "Successfully associated customized icon for Application:[$ApplicationName]." + } + + end { + [System.gc]::collect() + } +} + +Function Remove-HVApplicationIcon { +<# +.SYNOPSIS + Used to remove a customized icon association for a given application. + +.DESCRIPTION + This function is used to remove an application association to the given application. It will never remove the RDS system icons. If application doesnot have any customized icon, an error will be thrown. + +.PARAMETER ApplicationName + Name of the application to which customized icon needs to be removed. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.EXAMPLE + Removing the icon for an application A1. + Remove-HVApplicationIcon -ApplicationName A1 -HvServer $hvServer + +.OUTPUTS + None + +.NOTES + Author : Paramesh Oddepally. + Author email : poddepally@vmware.com + Version : 1.1 + + ===Tested Against Environment==== + Horizon View Server Version : 7.1 + PowerCLI Version : PowerCLI 6.5.1 + PowerShell Version : 5.0 +#> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] + param( + [Parameter(Mandatory = $true)] + [string] $ApplicationName, + + [Parameter(Mandatory = $false)] + $HvServer = $null + ) + + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object." + break + } + } + + process { + try { + $appInfo = Get-HVQueryResult -EntityType ApplicationInfo -Filter (Get-HVQueryFilter data.name -Eq $ApplicationName) -HvServer $HvServer + } catch { + # EntityNotFound, InsufficientPermission, InvalidArgument, InvalidType, UnexpectedFault + Write-Error "Error in querying the ApplicationInfo for Application:[$ApplicationName] $_" + break + } + + if ($null -eq $appInfo) { + Write-Error "No application found with specified name:[$ApplicationName]" + break + } + + [VMware.Hv.ApplicationIconId[]] $icons = $appInfo.Icons + [VMware.Hv.ApplicationIconId] $brokerIcon = $null + $ApplicationIconHelper = New-Object VMware.Hv.ApplicationIconService + Foreach ($icon in $icons) { + $applicationIconInfo = $ApplicationIconHelper.ApplicationIcon_Get($services, $icon) + if ($applicationIconInfo.Base.IconSource -eq "broker") { + $brokerIcon = $icon + } + } + + if ($null -eq $brokerIcon) { + Write-Error "There is no customized icon for the Application:[$ApplicationName]." + break + } + + try { + $ApplicationIconHelper.ApplicationIcon_RemoveAssociations($services, $brokerIcon, @($appInfo.Id)) + } catch { + Write-Error "Error in removing the customized icon association for Application:[$ApplicationName] $_ " + break + } + Write-Host "Successfully removed customized icon association for Application:[$ApplicationName]." + } + + end { + [System.gc]::collect() + } +} + +Export-ModuleMember Add-HVDesktop,Add-HVRDSServer,Connect-HVEvent,Disconnect-HVEvent,Get-HVPoolSpec,Get-HVInternalName, Get-HVEvent,Get-HVFarm,Get-HVFarmSummary,Get-HVPool,Get-HVPoolSummary,Get-HVMachine,Get-HVMachineSummary,Get-HVQueryResult,Get-HVQueryFilter,New-HVFarm,New-HVPool,Remove-HVFarm,Remove-HVPool,Set-HVFarm,Set-HVPool,Start-HVFarm,Start-HVPool,New-HVEntitlement,Get-HVEntitlement,Remove-HVEntitlement, Set-HVMachine, New-HVGlobalEntitlement, Remove-HVGlobalEntitlement, Get-HVGlobalEntitlement, Get-HVPodSession, Set-HVApplicationIcon, Remove-HVApplicationIcon 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..c350955 --- /dev/null +++ b/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 @@ -0,0 +1,2107 @@ +# 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 vMotionEncryption -ObjectType VirtualMachine -Value { + Param ($VM) + $VM.ExtensionData.Config.MigrateEncryption +} -BasedOnExtensionProperty 'Config.MigrateEncryption' -Force | Out-Null + +New-VIProperty -Name KMSserver -ObjectType VirtualMachine -Value { + Param ($VM) + if ($VM.Encrypted) { + $VM.EncryptionKeyId.ProviderId.Id + } +} -BasedOnExtensionProperty '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 Set-vMotionEncryptionConfig { + <# + .SYNOPSIS + This cmdlet sets the vMotionEncryption property of a VM. + + .DESCRIPTION + Use this function to set the vMotionEncryption settings for a VM. + The 'Encryption' parameter is set up with Tab-Complete for the available + options. + + .PARAMETER VM + Specifies the VM you want to set the vMotionEncryption property. + + .PARAMETER Encryption + Specifies the value you want to set to the vMotionEncryption property. + The Encryption options are: disabled, opportunistic, and required. + + .EXAMPLE + PS C:\> Get-VM | Set-vMotionEncryptionConfig -Encryption opportunistic + + Sets the vMotionEncryption of all the VMs + + .NOTES + Author : Brian Graf, Carrie Yang. + Author email : grafb@vmware.com, 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)] + [ValidateSet("disabled", "opportunistic", "required")] + [String]$Encryption + ) + + process{ + if ($VM.vMotionEncryption -eq $Encryption) { + Write-Warning "The encrypted vMotion state is already $Encrypted, no need to change it." + return + } + + if ($VM.Encrypted) { + Write-Error "Cannot change encrypted vMotion state for an encrypted VM." + return + } + + $VMView = $VM | get-view + $Config = New-Object VMware.Vim.VirtualMachineConfigSpec + $Config.MigrateEncryption = New-Object VMware.Vim.VirtualMachineConfigSpecEncryptedVMotionModes + $Config.MigrateEncryption = $Encryption + + $VMView.ReconfigVM($config) + + $VM.ExtensionData.UpdateViewData() + $VM.vMotionEncryption + } +} + +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/apply-hardening.psm1 similarity index 100% rename from Modules/apply-hardening.psm1 rename to Modules/apply-hardening/apply-hardening.psm1 diff --git a/Modules/vSphere_Hardening_Assess_VM_v1a.psm1 b/Modules/vSphere_Hardening_Assess_VM_v1a/vSphere_Hardening_Assess_VM_v1a.psm1 similarity index 100% rename from Modules/vSphere_Hardening_Assess_VM_v1a.psm1 rename to Modules/vSphere_Hardening_Assess_VM_v1a/vSphere_Hardening_Assess_VM_v1a.psm1 diff --git a/Pester/00 Test Connect-CISServer Connection to VC.Tests.ps1 b/Pester/00 Test Connect-CISServer Connection to VC.Tests.ps1 new file mode 100644 index 0000000..e9fb3c9 --- /dev/null +++ b/Pester/00 Test Connect-CISServer Connection to VC.Tests.ps1 @@ -0,0 +1,37 @@ +<# +Script name: Test Connect-CISServer to VC.Tests.ps1 +Created on: 04/20/2017 +Author: Alan Renouf, @alanrenouf +Description: The purpose of this pester test is to ensure the PowerCLI modules are imported and a connection can be made to a vCenter for the CIS Service +Dependencies: Pester Module +Example run: + +Invoke-Pester -Script @{ Path = '.\Test Connect-CISServer to VC.Tests.ps1'; Parameters = @{ VCNAME="VC01.local"; VCUSER="Administrator@vsphere.local"; VCPASS="Admin!23"} } + +#> + +$VCUSER = $Parameters.Get_Item("VCUSER") +$VCPASS = $Parameters.Get_Item("VCPASS") +$VCNAME = $Parameters.Get_Item("VCNAME") + +Describe "Checking PowerCLI Cmdlets available" { + $cmdletname = "Connect-CISServer" + It "Checking $cmdletname is available" { + $command = Get-Command $cmdletname + $command | Select Name, Version + $command.Name| Should Be $cmdletname + } +} + +Describe "Connect-CISServer Tests" { + + $connection = Connect-CISServer $VCName -User $VCUser -password $VCPass + It "Connection is active" { + $Global:DefaultCISServers[0].isconnected | Should Be $true + } + + It "Checking connected server name is $VCName" { + $Global:DefaultCISServers[0] | Select * + $Global:DefaultCISServers[0].name | Should Be $VCName + } +} \ No newline at end of file diff --git a/Pester/00 Test Connect-VIServer Connection to VC.Tests.ps1 b/Pester/00 Test Connect-VIServer Connection to VC.Tests.ps1 new file mode 100644 index 0000000..2428458 --- /dev/null +++ b/Pester/00 Test Connect-VIServer Connection to VC.Tests.ps1 @@ -0,0 +1,36 @@ +<# +Script name: Test Connection to VC.ps1 +Created on: 07/15/2016 +Author: Alan Renouf, @alanrenouf +Description: The purpose of this pester test is to ensure the PowerCLI modules are imported and a connection can be made to a vCenter +Dependencies: Pester Module +Example run: + +Invoke-Pester -Script @{ Path = '.\Test Connection to VC.Tests.ps1'; Parameters = @{ VCNAME="VC01.local"; VCUSER="Administrator@vsphere.local"; VCPASS="Admin!23"} } + +#> + +$VCUSER = $Parameters.Get_Item("VCUSER") +$VCPASS = $Parameters.Get_Item("VCPASS") +$VCNAME = $Parameters.Get_Item("VCNAME") + +Describe "Checking PowerCLI Cmdlets available" { + $cmdletname = "Connect-VIServer" + It "Checking $cmdletname is available" { + $command = Get-Command $cmdletname + $command | Select Name, Version + $command.Name| Should Be $cmdletname + } +} + +Describe "Connect-VIServer Tests" { + + $connection = Connect-VIServer $VCName -User $VCUser -password $VCPass + It "Connection is active" { + $Global:DefaultVIServer[0].isconnected | Should Be $true + } + + It "Checking connected server name is $VCName" { + $Global:DefaultVIServer[0].name | Should Be $VCName + } +} \ No newline at end of file diff --git a/Pester/Test Connection to VC.ps1 b/Pester/Test Connection to VC.ps1 deleted file mode 100644 index 006825a..0000000 --- a/Pester/Test Connection to VC.ps1 +++ /dev/null @@ -1,44 +0,0 @@ -<# -Script name: Test Connection to VC.ps1 -Created on: 07/15/2016 -Author: Alan Renouf, @alanrenouf -Description: The purpose of this pester test is to ensure the PowerCLI modules are imported and a connection and disconnection can be made to a vCenter -Dependencies: Pester Module -Example run: - -Invoke-Pester -Script @{ Path = '.\Test Connection to VC.ps1'; Parameters = @{ VCNAME="VC01.local"; VCUSER="Administrator@vsphere.local"; VCPASS="Admin!23"} } - -#> - -$VCUSER = $Parameters.Get_Item("VCUSER") -$VCPASS = $Parameters.Get_Item("VCPASS") -$VCNAME = $Parameters.Get_Item("VCNAME") - -Describe "PowerCLI Tests" { - It "Importing PowerCLI Modules" { - Get-Module VMware* | Foreach { - Write-Host "Importing Module $($_.name) Version $($_.Version)" - $_ | Import-Module - Get-Module $_ | Should Be $true - } - } -} - -Describe "Connect-VIServer Tests" { - - $connection = Connect-VIServer $VCName -User $VCUser -password $VCPass - It "Connection is active" { - $Global:DefaultVIServer[0].isconnected | Should Be $true - } - - It "Checking connected server name is $VCName" { - $Global:DefaultVIServer[0].name | Should Be $VCName - } -} - -Describe "Disconnect-VIServer Tests" { - It "Disconnect from $VCName" { - Disconnect-VIServer $VCName -confirm:$false - $Global:DefaultVIServer | Should Be $null - } -} \ No newline at end of file diff --git a/Pester/Test Get-CISService.Tests.ps1 b/Pester/Test Get-CISService.Tests.ps1 new file mode 100644 index 0000000..17d18b5 --- /dev/null +++ b/Pester/Test Get-CISService.Tests.ps1 @@ -0,0 +1,49 @@ +<# +Script name: Test Connect-CISService.Tests.ps1 +Created on: 04/20/2017 +Author: Alan Renouf, @alanrenouf +Description: The purpose of this pester test is to ensure the CIS Service cmdlet works correctly +Dependencies: Pester Module +Example run: + +Invoke-Pester -Script @{ Path = '.\Test Get-CISService.ps1' } + +#> + +Describe "Checking PowerCLI Cmdlets available" { + $cmdletname = "Get-CISService" + It "Checking $cmdletname is available" { + $command = Get-Command $cmdletname + $command | Select Name, Version + $command.Name| Should Be $cmdletname + } +} + +Describe "Get-CISService Tests for services" { + + It "Checking CIS connection is active" { + $Global:DefaultCISServers[0].isconnected | Should Be $true + } + + It "Checking Get-CISService returns services" { + Get-CISService | Should Be $true + } + + # Checking some known services which have a Get Method + $servicestocheck = "com.vmware.appliance.system.version", "com.vmware.appliance.health.system" + Foreach ($service in $servicestocheck) { + It "Checking $service get method returns data" { + Get-CisService -Name $service | Should Be $true + (Get-CisService -Name $service).get() | Should Be $true + } + } + + # Checking some known services which have a List Method + $servicestocheck = "com.vmware.vcenter.folder", "com.vmware.vcenter.vm" + Foreach ($service in $servicestocheck) { + It "Checking $service list method returns data" { + Get-CisService -Name $service | Should Be $true + (Get-CisService -Name $service).list() | Should Be $true + } + } +} \ No newline at end of file diff --git a/Pester/ZZ Test Disconnect-CISServer to VC.Tests.ps1 b/Pester/ZZ Test Disconnect-CISServer to VC.Tests.ps1 new file mode 100644 index 0000000..63f12e4 --- /dev/null +++ b/Pester/ZZ Test Disconnect-CISServer to VC.Tests.ps1 @@ -0,0 +1,20 @@ +<# +Script name: Test Disconnect-CISServer to VC.Tests.ps1 +Created on: 04/20/2017 +Author: Alan Renouf, @alanrenouf +Description: The purpose of this pester test is to ensure the Disconnect-CISServer cmdlet disconnects +Dependencies: Pester Module +Example run: + +Invoke-Pester -Script @{ Path = '.\Test Disconnect-CISServer to VC.Tests.ps1'; Parameters = @{ VCNAME="VC01.local" } } + +#> + +$VCNAME = $Parameters.Get_Item("VCNAME") + +Describe "Disconnect-CISServer Tests" { + It "Disconnect from $VCName" { + Disconnect-CISServer $VCName -confirm:$false + $Global:DefaultCISServers | Should Be $null + } +} \ No newline at end of file diff --git a/Pester/ZZ Test Disconnect-VIServer to VC.Tests.ps1 b/Pester/ZZ Test Disconnect-VIServer to VC.Tests.ps1 new file mode 100644 index 0000000..8a51fb9 --- /dev/null +++ b/Pester/ZZ Test Disconnect-VIServer to VC.Tests.ps1 @@ -0,0 +1,20 @@ +<# +Script name: Test Disconnect-VIServer to VC.ps1 +Created on: 04/20/2017 +Author: Alan Renouf, @alanrenouf +Description: The purpose of this pester test is to ensure the Disconnect-VIServer cmdlet disconnects +Dependencies: Pester Module +Example run: + +Invoke-Pester -Script @{ Path = '.\Test Disconnect-VISServer to VC.ps1'; Parameters = @{ VCNAME="VC01.local" } } + +#> + +$VCNAME = $Parameters.Get_Item("VCNAME") + +Describe "Disconnect-VIServer Tests" { + It "Disconnect from $VCName" { + Disconnect-VIServer $VCName -confirm:$false + $Global:DefaultVIServer | Should Be $null + } +} \ 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/Get-VsanHclDatabase.ps1 b/Scripts/Get-VsanHclDatabase.ps1 new file mode 100644 index 0000000..66ac72f --- /dev/null +++ b/Scripts/Get-VsanHclDatabase.ps1 @@ -0,0 +1,29 @@ +Function Get-VsanHclDatabase { +<# + .NOTES + =========================================================================== + Created by: Alan Renouf + Organization: VMware + Blog: http://virtu-al.net + Twitter: @alanrenouf + =========================================================================== + .SYNOPSIS + This function will allow you to view and download the VSAN Hardware Compatability List (HCL) Database + + .DESCRIPTION + Use this function to view or download the VSAN HCL + .EXAMPLE + View the latest online HCL Database from online source + PS C:\> Get-VsanHclDatabase | Format-Table + .EXAMPLE + Download the latest HCL Database from online source and store locally + PS C:\> Get-VsanHclDatabase -filepath ~/hcl.json +#> +param ($filepath) + $uri = "https://partnerweb.vmware.com/service/vsan/all.json" + If ($filepath) { + Invoke-WebRequest -Uri $uri -OutFile $filepath + } Else { + Invoke-WebRequest -Uri $uri | ConvertFrom-Json | Select-Object -ExpandProperty Data | Select-object -ExpandProperty Controller + } +} \ No newline at end of file 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/Horizon-GetUsageStats.ps1 b/Scripts/Horizon-GetUsageStats.ps1 new file mode 100644 index 0000000..7c389bb --- /dev/null +++ b/Scripts/Horizon-GetUsageStats.ps1 @@ -0,0 +1,38 @@ +<# +.NOTES +Script name: Horizon-UsageStats.ps1 +Author: Ray Heffer, @rayheffer +Last Edited on: 04/18/2017 +Dependencies: PowerCLI 6.5 R1 or later, Horizon 7.0.2 or later +.DESCRIPTION +This is a sample script that retrieves the Horizon usage statistics. This produces the same metrics as listed under View Configuration > Product Licensing and Usage. Service providers can use this script or incorporate it with their existing scripts to automate the reporting of Horizon usage. + +Example Output: +NumConnections : 180 +NumConnectionsHigh : 250 +NumViewComposerConnections : 0 +NumViewComposerConnectionsHigh : 0 +NumTunneledSessions : 0 +NumPSGSessions : 180 +#> + +# User Configuration +$hzUser = "Administrator" +$hzPass = "VMware1!" +$hzDomain = "vmw.lab" +$hzConn = "connect01.vmw.lab" + +# Import the Horizon module +Import-Module VMware.VimAutomation.HorizonView + +# Establish connection to Connection Server +$hvServer = Connect-HVServer -server $hzConn -User $hzUser -Password $hzPass -Domain $hzDomain + +# Assign a variable to obtain the API Extension Data +$hvServices = $Global:DefaultHVServers.ExtensionData + +# Retrieve Connection Server Health metrics +$hvHealth =$hvServices.ConnectionServerHealth.ConnectionServerHealth_List() + +# Display ConnectionData (Usage stats) +$hvHealth.ConnectionData diff --git a/Scripts/NVME Info.ps1 b/Scripts/NVME Info.ps1 new file mode 100644 index 0000000..415b298 --- /dev/null +++ b/Scripts/NVME Info.ps1 @@ -0,0 +1,27 @@ +<# + .NOTES + =========================================================================== + Created by: Alan Renouf + Organization: VMware + Blog: http://virtu-al.net + Twitter: @alanrenouf + =========================================================================== +#> + +Foreach ($vmhost in Get-VMHost) { + $esxcli = get-esxcli -V2 -vmhost $vmhost + Write-Host "Host: $($vmhost.name)" -ForegroundColor Green + $devices = $esxcli.nvme.device.list.Invoke() + Foreach ($device in $devices) { + $nvmedevice = $esxcli.nvme.device.get.CreateArgs() + $nvmedevice.adapter = $device.HBAName + $esxcli.nvme.device.get.invoke($nvmedevice) | Select-Object ModelNumber, FirmwareRevision + $features = $esxcli.nvme.device.feature.ChildElements | Select-object -ExpandProperty name + ForEach ($feature in $features){ + Write-Host "Feature: $feature" -ForegroundColor Yellow + $currentfeature = $esxcli.nvme.device.feature.$feature.get.CreateArgs() + $currentfeature.adapter = $device.HBAName + $esxcli.nvme.device.feature.$feature.get.Invoke($currentfeature) + } + } +} \ No newline at end of file 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/SetLunReservation.ps1 b/Scripts/SetLunReservation.ps1 new file mode 100644 index 0000000..ae610a0 --- /dev/null +++ b/Scripts/SetLunReservation.ps1 @@ -0,0 +1,103 @@ +<# + .SYNOPSIS + Set a given LUN ID to Perennially Reserved. + + .DESCRIPTION + A description of the file. + + .PARAMETER vCenter + Set vCenter server to connect to + + .PARAMETER Username + Set username to use + + .PARAMETER Password + Set password to be used + + .PARAMETER VirtualMachine + Name of the virtual machine which has the RDM + + .NOTES + =========================================================================== + Created on: 20/03/2017 15:05 + Created by: Alessio Rocchi + Organization: VMware + Filename: SetLunReservation.ps1 + =========================================================================== +#> +param +( + [Parameter(Mandatory = $true, + ValueFromPipeline = $true, + Position = 0)] + [ValidateNotNullOrEmpty()] + [String]$vCenter, + [Parameter(Mandatory = $false, + ValueFromPipeline = $true, + HelpMessage = 'Set vCenter Username')] + [AllowNull()] + [String]$Username, + [Parameter(Mandatory = $false, + ValueFromPipeline = $true, + HelpMessage = 'Set vCenterPassword')] + [AllowNull()] + [String]$Password, + [Parameter(Mandatory = $true, + ValueFromPipeline = $true)] + [ValidateNotNullOrEmpty()] + [String]$VirtualMachine +) + +Import-Module -Name VMware.VimAutomation.Core -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null + +try +{ + if ([String]::IsNullOrEmpty($Username) -or [String]::IsNullOrEmpty($Password)) + { + $vcCredential = Get-Credential + Connect-VIServer -Server $vCenter -Credential $vcCredential -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null + } + else + { + Connect-VIServer -Server $vCenter -User $Username -Password $Password -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null + } +} +catch +{ + Write-Error("Error connecting to vCenter: {0}" -f $vCenter) + exit +} + + +$rDms = Get-HardDisk -DiskType rawPhysical -Vm (Get-VM -Name $VirtualMachine) +$clusterHosts = Get-Cluster -VM $VirtualMachine | Get-VMHost + +$menu = @{ } + +for ($i = 1; $i -le $rDms.count; $i++) +{ + Write-Host("{0}) {1}[{2}]: {3}" -f ($i, $rDms[$i - 1].Name, $rDms[$i - 1].CapacityGB, $rDms[$i - 1].ScsiCanonicalName)) + $menu.Add($i, ($rDms[$i - 1].ScsiCanonicalName)) +} + +[int]$ans = Read-Host 'Which Disk you want to configure?' +$selection = $menu.Item($ans) +write-host("Choosed Disk: {0}" -f $selection) + +$current = 0 +foreach ($vmHost in $clusterHosts) +{ + Write-Progress -Activity "Processing Cluster." -CurrentOperation $vmHost.Name -PercentComplete (($counter / $clusterHosts.count) * 100) + $esxcli = Get-EsxCli -V2 -VMHost $vmHost + $deviceListArgs = $esxcli.storage.core.device.list.CreateArgs() + $deviceListArgs.device = $selection + $esxcli.storage.core.device.list.Invoke($deviceListArgs) | Select-Object Device, IsPerenniallyReserved + $deviceSetArgs = $esxcli.storage.core.device.setconfig.CreateArgs() + $deviceSetArgs.device = $selection + $deviceSetArgs.perenniallyreserved = $true + $esxcli.storage.core.device.setconfig.Invoke($deviceSetArgs) + $counter++ +} + +Disconnect-VIServer -WarningAction SilentlyContinue -Server $vCenter -Force -Confirm:$false + diff --git a/Scripts/VSANSmartsData.ps1 b/Scripts/VSANSmartsData.ps1 new file mode 100644 index 0000000..61ef427 --- /dev/null +++ b/Scripts/VSANSmartsData.ps1 @@ -0,0 +1,59 @@ +Function Get-VSANSmartsData { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + This function retreives SMART drive data using new vSAN + Management 6.6 API. This can also be used outside of vSAN + to query existing SSD devices not being used for vSAN. + .PARAMETER Cluster + The name of a vSAN Cluster + .EXAMPLE + Get-VSANSmartsData -Cluster VSAN-Cluster +#> + param( + [Parameter(Mandatory=$false)][String]$Cluster + ) + + if($global:DefaultVIServer.ExtensionData.Content.About.ApiType -eq "VirtualCenter") { + if(!$cluster) { + Write-Host "Cluster property is required when connecting to vCenter Server" + break + } + + $vchs = Get-VSANView -Id "VsanVcClusterHealthSystem-vsan-cluster-health-system" + $cluster_view = (Get-Cluster -Name $Cluster).ExtensionData.MoRef + $result = $vchs.VsanQueryVcClusterSmartStatsSummary($cluster_view) + } else { + $vhs = Get-VSANView -Id "HostVsanHealthSystem-ha-vsan-health-system" + $result = $vhs.VsanHostQuerySmartStats($null,$true) + } + + $vmhost = $result.Hostname + $smartsData = $result.SmartStats + + Write-Host "`nESXi Host: $vmhost`n" + foreach ($data in $smartsData) { + if($data.stats) { + $stats = $data.stats + Write-Host $data.disk + + $smartsResults = @() + foreach ($stat in $stats) { + $statResult = [pscustomobject] @{ + Parameter = $stat.Parameter; + Value =$stat.Value; + Threshold = $stat.Threshold; + Worst = $stat.Worst + } + $smartsResults+=$statResult + } + $smartsResults | Format-Table + } + } +} \ No newline at end of file diff --git a/Scripts/VSANVersion.ps1 b/Scripts/VSANVersion.ps1 new file mode 100644 index 0000000..45fa7a7 --- /dev/null +++ b/Scripts/VSANVersion.ps1 @@ -0,0 +1,26 @@ +Function Get-VSANVersion { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + This function retreives the vSAN software version for both VC/ESXi + .PARAMETER Cluster + The name of a vSAN Cluster + .EXAMPLE + Get-VSANVersion -Cluster VSAN-Cluster +#> + param( + [Parameter(Mandatory=$true)][String]$Cluster + ) + $vchs = Get-VSANView -Id "VsanVcClusterHealthSystem-vsan-cluster-health-system" + $cluster_view = (Get-Cluster -Name $Cluster).ExtensionData.MoRef + $results = $vchs.VsanVcClusterQueryVerifyHealthSystemVersions($cluster_view) + + Write-Host "`nVC Version:"$results.VcVersion + $results.HostResults | Select Hostname, Version +} diff --git a/Scripts/esxi-image-comparator.ps1 b/Scripts/esxi-image-comparator.ps1 new file mode 100644 index 0000000..a9be557 --- /dev/null +++ b/Scripts/esxi-image-comparator.ps1 @@ -0,0 +1,97 @@ +<# +Script name: esxi-image-comparator.ps1 +Last update: 24 May 2017 +Author: Eric Gray, @eric_gray +Description: Compare contents (VIBs) of multiple VMware ESXi image profiles. +Dependencies: PowerCLI Image Builder (VMware.ImageBuilder,VMware.VimAutomation.Core) +#> + +param( + [switch]$ShowAllVIBs=$false, + [switch]$HideDates=$false, + [switch]$Interactive=$false, + [switch]$Grid=$false, + [string]$ProfileInclude, + [string]$ProfileExclude +) + +$profileList = Get-EsxImageProfile | sort -Property Name + +if ($ProfileInclude) { + $profileList = $profileList | ? Name -Match $ProfileInclude +} + +if ($ProfileExclude) { + $profileList = $profileList | ? Name -NotMatch $ProfileExclude +} + +if ($profileList.Count -eq 0) { + Write-Host "No ESXi image profiles available in current session." + Write-Host "Use Add-EsxSoftwareDepot for each depot zip bundle you would like to compare." + exit 1 +} + +if ($Interactive) { + $keep = @() + Write-Host "Found the following profiles:" -ForegroundColor Yellow + $profileList | % { write-host $_.Name } + + if ($profileList.Count -gt 7) { + Write-Host "Found $($profileList.Count) profiles!" -ForegroundColor Yellow + Write-Host "Note: List filtering is possible through -ProfileInclude / -ProfileExclude" -ForegroundColor DarkGreen + } + + write-host "`nType 'y' next to each profile to compare..." -ForegroundColor Yellow + + foreach ($profile in $profileList) { + $want = Read-Host -Prompt $profile.Name + if ($want.StartsWith("y") ) { + $keep += $profile + } + + } + $profileList = $keep + +} + +# go thru each profile and build a hash of the vib name and hash of profile name + version +$diffResults = @{} +foreach ($profile in $profileList ) { + foreach ($vib in $profile.VibList) { + $vibValue = $vib.Version + if (! $HideDates) { + $vibValue += " "+ $vib.CreationDate.ToShortDateString() + } + $diffResults.($vib.name) += @{$profile.name = $vibValue} + + } + +} + +# create an object that will neatly output as CSV or table +$outputTable=@() +foreach ($row in $diffResults.keys | sort) { + $vibRow = new-object PSObject + $vibRow | add-member -membertype NoteProperty -name "VIB" -Value $row + $valueCounter = @{} + + foreach ($profileName in $profileList.name) { + #populate this hash to decide if all profiles have same version of VIB + $valueCounter.($diffResults.$row.$profileName) = 1 + $vibRow | add-member -membertype NoteProperty -name $profileName -Value $diffResults.$row.$profileName + } + + if ($valueCounter.Count -gt 1 -or $ShowAllVIBs) { + $outputTable += $vibRow + } +} + +# useful for debugging +#$diffResults | ConvertTo-Json +#$outputTable|Export-Csv -Path .\image-diff-results.csv -NoTypeInformation + +if ($Grid) { + $outputTable | Out-GridView -Title "VMware ESXi Image Profile Comparator" +} else { + $outputTable +} \ No newline at end of file diff --git a/Scripts/esxi-image-creator.ps1 b/Scripts/esxi-image-creator.ps1 new file mode 100644 index 0000000..322c6e6 --- /dev/null +++ b/Scripts/esxi-image-creator.ps1 @@ -0,0 +1,108 @@ +<# +Script name: esxi-image-creator.ps1 +Last update: 24 May 2017 +Author: Eric Gray, @eric_gray +Description: Create a VMware ESXi image profile based on + one or more depots and offline driver bundles. +Dependencies: PowerCLI Image Builder (VMware.ImageBuilder,VMware.VimAutomation.Core) +#> + +param( + [switch]$NewestDate = $false, + [switch]$WriteZip = $false, + [switch]$WriteISO = $false, + [switch]$LeaveCurrentDepotsMounted = $false, + [string]$NewProfileName = "Custom Image $(Get-Date -Format "yyyyMMddhhmm")", + [ValidateNotNullOrEmpty()] + [ValidateSet('VMwareCertified','VMwareAccepted','PartnerSupported','CommunitySupported')] + [string]$Acceptance = "VMwareCertified", + [string[]]$Files = "*.zip" +) + +#### Specify optional image fine-tuning here #### +# comma-separated list (array) of VIBs to exclude +$removeVibs = @("tools-light") + +# force specific VIB version to be included, when more than one version is present +# e.g. "net-enic"="2.1.2.71-1OEM.550.0.0.1331820" +$overrideVibs = @{ + # "net-enic"="2.1.2.71-1OEM.550.0.0.1331820", +} + +#### end of optional fine-tuning #### + +# may be desirable to manually mount an online depot in advance, such as for HPE +# e.g. Add-EsxSoftwareDepot http://vibsdepot.hpe.com/index-ecli-650.xml +if (! $LeaveCurrentDepotsMounted) { + Get-EsxSoftwareDepot | Remove-EsxSoftwareDepot +} + +foreach ($depot in Get-ChildItem $Files) { + if ($depot.Name.EndsWith(".zip") ) { + Add-EsxSoftwareDepot $depot.FullName + } else { + Write-Host "Not a zip depot:" $depot.Name + } +} + +if ((Get-EsxImageProfile).count -eq 0) { + write-host "No image profiles found in the selected files" + exit 1 +} + +# either use the native -Newest switch, or try to find latest VIBs by date (NewestDate) +if ($NewestDate) { + $pkgsAll = Get-EsxSoftwarePackage | sort -Property Name,CreationDate -Descending + $pkgsNewestDate=@() + + foreach ($pkg in $pkgsAll) { + if ($pkgsNewestDate.GetEnumerator().name -notcontains $pkg.Name ) { + $pkgsNewestDate += $pkg + } + } + $pkgs = $pkgsNewestDate + +} else { + $pkgs = Get-ESXSoftwarePackage -Newest +} + +# rebuild the package array according to manual fine-tuning +if ($removeVibs) { + Write-Host "`nThe following VIBs will not be included in ${NewProfileName}:" -ForegroundColor Yellow + $removeVibs + $pkgs = $pkgs | ? name -NotIn $removeVibs +} + +foreach ($override in $overrideVibs.keys) { + # check that the override exists, then remove existing and add override + $tmpOver = Get-EsxSoftwarePackage -Name $override -Version $overrideVibs.$override + if ($tmpOver) { + $pkgs = $pkgs | ? name -NotIn $tmpOver.name + $pkgs += $tmpOver + } else { + Write-host "Did not find:" $override $overrideVibs.$override -ForegroundColor Yellow + } +} + +try { + New-EsxImageProfile -NewProfile $NewProfileName -SoftwarePackage $pkgs ` + -Vendor Custom -AcceptanceLevel $Acceptance -Description "Made with esxi-image-creator.ps1" ` + -ErrorAction Stop -ErrorVariable CreationError | Out-Null +} +catch { + Write-Host "Custom image profile $NewProfileName not created." -ForegroundColor Yellow + $CreationError + exit 1 +} + +Write-Host "`nFinished creating $NewProfileName" -ForegroundColor Yellow + +if ($WriteZip) { + Write-Host "Creating zip bundle..." -ForegroundColor Green + Export-EsxImageProfile -ImageProfile $NewProfileName -ExportToBundle -FilePath .\${NewProfileName}.zip -Force +} + +if ($WriteISO) { + Write-Host "Creating ISO image..." -ForegroundColor Green + Export-EsxImageProfile -ImageProfile $NewProfileName -ExportToIso -FilePath .\${NewProfileName}.iso -Force +} diff --git a/Scripts/modules.sh b/Scripts/modules.sh new file mode 100644 index 0000000..ea84779 --- /dev/null +++ b/Scripts/modules.sh @@ -0,0 +1,6 @@ +#!/bin/bash +for file in $( ls /powershell/PowerCLI-Example-Scripts/Modules/ ) +do + mkdir "/root/.local/share/powershell/Modules/${file%.*}/" + mv "/powershell/PowerCLI-Example-Scripts/Modules/$file" "/root/.local/share/powershell/Modules/${file%.*}/$file" +done diff --git a/SetDatastoreTag.ps1 b/SetDatastoreTag.ps1 new file mode 100755 index 0000000..23708e5 --- /dev/null +++ b/SetDatastoreTag.ps1 @@ -0,0 +1,198 @@ +<# + .SYNOPSIS + A brief description of the file. + + .DESCRIPTION + Given a list of Datastore Names, this script will assign a Tag to them + + .PARAMETER csvFile + String representing the full path of the file + The file must be structured like this: + ----------------------------- + Tag1,Tag2,Tag3,Tag4 + IPv4-iSCSI-SiteA,Tag1,Tag3 + IPv4-NFS-SiteA,Tag2,Tag4 + ... + ----------------------------- + + .NOTES + =========================================================================== + Created on: 31/03/2017 11:16 + Created by: Alessio Rocchi + Organization: VMware + Filename: SetDatastoreTag.ps1 + =========================================================================== +#> +[CmdletBinding()] +param +( + [Parameter(Mandatory = $true, + ValueFromPipeline = $true)] + [ValidateNotNullOrEmpty()] + [System.String]$csvFile, + [Parameter(Mandatory = $true, + ValueFromPipeline = $true)] + [ValidateNotNullOrEmpty()] + [String]$vCenter, + [Parameter(ValueFromPipeline = $true, + Position = 2)] + [AllowNull()] + [String]$Username, + [Parameter(Position = 3)] + [AllowNull()] + [String]$Password +) + +Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null + +class vcConnector : System.IDisposable +{ + [String]$Username + [String]$Password + [String]$vCenter + [PSObject]$server + + static [vcConnector]$instance + + vcConnector($Username, $Password, $vCenter) + { + Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null + + $this.Username = $Username + $this.Password = $Password + $this.vCenter = $vCenter + $this.connect() + } + + vcConnector($vcCredential, $vCenter) + { + Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue | Out-Null + + $this.vcCredential = $vcCredential + $this.vCenter = $vCenter + $this.connect() + } + + [void] hidden connect() + { + try + { + if ([String]::IsNullOrEmpty($this.Username) -or [String]::IsNullOrEmpty($this.Password)) + { + $vcCredential = Get-Credential + Connect-VIServer -Server $this.vCenter -Credential $this.vcCredential -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null + } + else + { + Connect-VIServer -Server $this.vCenter -User $this.Username -Password $this.Password -WarningAction SilentlyContinue -ErrorAction Stop + } + Write-Debug("Connected to vCenter: {0}" -f $this.vCenter) + } + catch + { + Write-Error($Error[0].Exception.Message) + exit + } + } + + + [void] Dispose() + { + Write-Debug("Called Dispose Method of Instance: {0}" -f ($this)) + Disconnect-VIServer -WarningAction SilentlyContinue -Server $this.vCenter -Force -Confirm:$false | Out-Null + } + + static [vcConnector] GetInstance() + { + if ([vcConnector]::instance -eq $null) + { + [vcConnector]::instance = [vcConnector]::new() + } + + return [vcConnector]::instance + } +} + +class Content{ + [System.Collections.Generic.List[System.String]]$availableTags + [System.Collections.Generic.List[System.String]]$elements + + Content() + { + } + + Content([String]$filePath) + { + if ((Test-Path -Path $filePath) -eq $false) + { + throw ("Cannot find file: {0}" -f ($filePath)) + } + try + { + # Cast the Get-Content return type to Generic List of Strings in order to avoid fixed-size array + $this.elements = [System.Collections.Generic.List[System.String]](Get-Content -Path $filePath -ea SilentlyContinue -wa SilentlyContinue) + $this.availableTags = $this.elements[0].split(',') + # Delete the first element aka availableTags + $this.elements.RemoveAt(0) + } + catch + { + throw ("Error reading the file: {0}" -f ($filePath)) + } + } +} + +try +{ + $vc = [vcConnector]::new($Username, $Password, $vCenter) + $csvContent = [Content]::new($csvFile) + + Write-Host("Available Tags: {0}" -f ($csvContent.availableTags)) + + foreach ($element in $csvContent.elements) + { + [System.Collections.Generic.List[System.String]]$splittedList = $element.split(',') + # Get the Datastore Name + [System.String]$datastoreName = $splittedList[0] + # Removing Datastore Name + $splittedList.RemoveAt(0) + # Create a List of Tags which will be assigned to the Datastore + [System.Collections.Generic.List[PSObject]]$tagsToAssign = $splittedList | ForEach-Object { Get-Tag -Name $_ } + Write-Host("Tags to assign to Datastore: {0} are: {1}" -f ($datastoreName, $tagsToAssign)) + # Get Datastore object by the given Datastore Name, first field of the the line + $datastore = Get-Datastore -Name $datastoreName -ea Stop + # Iterate the assigned Datastore Tags + foreach ($tag in ($datastore | Get-TagAssignment)) + { + # Check if the current tag is one of the available ones. + if ($tag.Tag.Name -in $csvContent.availableTags) + { + # Remove the current assigned Tag + Write-Host("Removing Tag: {0}" -f ($tag)) + Remove-TagAssignment -TagAssignment $tag -Confirm:$false + } + } + # Finally add the new set of tags to the Datastore + foreach ($tag in $tagsToAssign) + { + Write-Host("Trying to assign Tag: {0} to Datastore: {1}" -f ($tag.Name, $datastoreName)) + # Assign the Tag + New-TagAssignment -Entity $datastore -Tag $tag + } + } +} +catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.VimException] +{ + Write-Error("VIException: {0}" -f ($Error[0].Exception.Message)) + exit +} +catch +{ + Write-Error $Error[0].Exception.Message + exit +} +finally +{ + # Let be assured that the vc connection will be disposed. + $vc.Dispose() +}