From 3d29306cb651f54f5c5a904c2941bd090641a382 Mon Sep 17 00:00:00 2001 From: mycloudrevolution Date: Fri, 24 Aug 2018 14:20:51 +0200 Subject: [PATCH 001/175] add Module with Validate-ESXiPackages Function --- .../Validate-ESXiPackages.psm1 | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Modules/Validate-ESXiPackages/Validate-ESXiPackages.psm1 diff --git a/Modules/Validate-ESXiPackages/Validate-ESXiPackages.psm1 b/Modules/Validate-ESXiPackages/Validate-ESXiPackages.psm1 new file mode 100644 index 0000000..ccf5d85 --- /dev/null +++ b/Modules/Validate-ESXiPackages/Validate-ESXiPackages.psm1 @@ -0,0 +1,82 @@ +function Validate-ESXiPackages { + <# + .DESCRIPTION + Compares all ESXi Host VIBs within a vSphere with a reference Hosts. + + .NOTES + File Name : Validate-ESXiPackages.ps1 + Author : Markus Kraus + Version : 1.0 + State : Ready + + Tested Against Environment: + + vSphere Version: 6.0 U2, 6.5 U1 + PowerCLI Version: PowerCLI 10.0.0 build 7895300 + PowerShell Version: 4.0 + OS Version: Windows Server 2012 R2 + + .LINK + https://mycloudrevolution.com/ + + .EXAMPLE + Validate-ESXiPackages -Cluster (Get-Cluster) -RefernceHost (Get-VMHost | Select-Object -First 1) + + .PARAMETER Cluster + vSphere Cluster to verify + + .PARAMETER RefernceHost + The VIB Reference ESXi Host + #> + + [CmdletBinding()] + param( + [Parameter(Mandatory=$True, ValueFromPipeline=$True, HelpMessage="vSphere Cluster to verify")] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.ComputeResourceImpl] $Cluster, + [Parameter(Mandatory=$True, ValueFromPipeline=$false, HelpMessage="The VIB Reference ESXi Host")] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl] $RefernceHost + ) + + Process { + + #region: Get reference VIBs + $EsxCli2 = Get-ESXCLI -VMHost $RefernceHost -V2 + $RefernceVibList = $esxcli2.software.vib.list.invoke() + #endregion + + #region: Compare reference VIBs + $MyView = @() + foreach ($VmHost in ($Cluster | Get-VMHost)) { + + $EsxCli2 = Get-ESXCLI -VMHost $VmHost -V2 + $VibList = $esxcli2.software.vib.list.invoke() + [Array]$VibDiff = Compare-Object -ReferenceObject $RefernceVibList.ID -DifferenceObject $VibList.ID + + if($VibDiff.Count -gt 0) { + $VibDiffSideIndicator = @() + foreach ($Item in $VibDiff) { + $VibDiffSideIndicator += $($Item.SideIndicator + " " + $Item.InputObject) + } + } + else { + $VibDiffSideIndicator = $null + } + + $Report = [PSCustomObject] @{ + Host = $VmHost.Name + Version = $VmHost.Version + Build = $VmHost.Build + VibDiffCount = $VibDiff.Count + VibDiff = $VibDiff.InputObject + VibDiffSideIndicator = $VibDiffSideIndicator + } + $MyView += $Report + + } + #region: Compare reference VIBs + + $MyView + } +} \ No newline at end of file From cff2f29b9735408dd6a4ffa6e0ba0ffa5ed57948 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 24 Aug 2018 16:32:35 -0400 Subject: [PATCH 002/175] Added Get-TraceFlows Added Get-TraceFlows. Will add to export list if it looks good. --- Modules/NSXT/NSXT.psm1 | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index a6afe2d..8616e88 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -293,4 +293,37 @@ Function Get-NSXTTransportNodes { } $results +} + +Function Get-NSXTTraceFlows { + Param ( + [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id + ) + + $NSXTraceFlowsService = Get-NsxtService -Name "com.vmware.nsx.traceflows" + + if($Id) { + $NSXTraceFlows = $NSXTraceFlowsService.get($Id) + } else { + $NSXTraceFlows = $NSXTraceFlowsService.list().results + } + + $results = @() + foreach ($NSXTraceFlow in $NSXTraceFlows) { + + $tmp = [pscustomobject] @{ + Id = $NSXTraceFlow.Id; + Operation_State = $NSXTraceFlow.operation_state; + Delivered = $NSXTraceFlow.Counters.delivered_count; + Dropped = $NSXTraceFlow.Counters.dropped_count; + Analysis = $NSXTraceFlow.maintenance_mode; + } + $results+=$tmp + } + + $results + + if ($Id) { + write-output $Id + } } \ No newline at end of file From 3c5e8363ed71db1a850fb6d31ce06a36ca082910 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 24 Aug 2018 16:34:11 -0400 Subject: [PATCH 003/175] Added Get-TraceFlowsObservations Added Get-TraceFlowsObservations. Will add to export if it looks ok. --- Modules/NSXT/NSXT.psm1 | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 8616e88..bfb320f 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -326,4 +326,20 @@ Function Get-NSXTTraceFlows { if ($Id) { write-output $Id } +} + +Function Get-NSXTTraceFlowObservations { + Param ( + [parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Id + ) + + $NSXTraceFlowsObservService = Get-NsxtService -Name "com.vmware.nsx.traceflows.observations" + + if($Id) { + $NSXTraceFlowsObserv = $NSXTraceFlowsObservService.list($Id) + } else { + throw "TraceFlow ID required" + } + + $NSXTraceFlowsObserv.results | select transport_node_name,component_name,@{N='PacketEvent';E={($_.resource_type).TrimStart("TraceflowObservation")}} } \ No newline at end of file From 1f6ec2c2c2188001bad863a36c0083458b42bdb6 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 24 Aug 2018 16:36:48 -0400 Subject: [PATCH 004/175] First try at a set- function - does not work! First try at a set- function. Does not work! Not clear how to resolve, the .create method ignores required parameters; looking for ideas. --- Modules/NSXT/NSXT.psm1 | 128 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index bfb320f..b2f9c3c 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -342,4 +342,132 @@ Function Get-NSXTTraceFlowObservations { } $NSXTraceFlowsObserv.results | select transport_node_name,component_name,@{N='PacketEvent';E={($_.resource_type).TrimStart("TraceflowObservation")}} +} + +Function Set-NSXTTraceFlow { + [CmdletBinding()] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateSet("UNICAST")] + [string] + $TrafficType = "UNICAST", + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + #[ValidateScript({Get-NSXTLogicalPort -Id $_}] + [string] + $LPORTID, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$_ -match [IPAddress]$_})] + [string] + $SIPAddr, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$pattern = '^(([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))|(([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2}))$' + if ($_ -match ($pattern -join '|')) {$true} else { + throw "The argument '$_' does not match a valid MAC address format." + } + })] + [string] + $SMAC, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$_ -match [IPAddress]$_ })] + [string] + $DIPAddr, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$pattern = '^(([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))|(([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2}))$' + if ($_ -match ($pattern -join '|')) {$true} else { + throw "The argument '$_' does not match a valid MAC address format." + } + })] + [string] + $DMAC) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTraceFlowsService = Get-NsxtService -Name "com.vmware.nsx.traceflows" + + # This is where I need help - the method does not ingest the complete $traceflow_request object! + + # Create the example object + $traceflow_request = $NSXTraceFlowService.help.create.traceflow_request.Create() + $traceflow_request.lport_id = $LPORTID + $traceflow_request.timeout = '15000' + $traceflow_request.packet.routed = 'true' + $traceflow_request.packet.transport_type = $TrafficType.ToUpper() + $traceflow_request.packet.resource_type = 'FieldsPacketData' + $traceflow_request.packet.frame_size = '64' + + # The example object is missing packet data, so we create it. + $eth_header = @{src_mac = $SMAC;eth_type = '2048';dst_mac = $DMAC} + $ip_header = @{src_ip = $SIPAddr;protocol = '1';ttl = '64';dst_ip = $DIPAddr} + $traceflow_request.packet | Add-Member -NotePropertyMembers $eth_header -TypeName eth_header + $traceflow_request.packet | Add-Member -NotePropertyMembers $ip_header -TypeName ip_header + + # Alternative method of creating $traceflow_request (not working either) + <# + $TraceFlow_Request = [PSCustomObject]@{ + packet = @{routed = 'true'; + transport_type = $TrafficType.ToUpper(); + ip_header = @{src_ip = $SIPAddr;dst_ip = $DIPAddr}; + eth_header = @{dst_mac = $DMAC;src_mac = $SMAC}; + payload = 'test_payload'; + resource_type = 'FieldsPacketData'}; + timeout = '10000'; + lport_id = $LPORTID + } + #> + } + + Process + { + try + { + # This does not work, ignores eth_header,ip_header etc.. Not clear why!? + $NSXTraceFlow = $NSXTraceFlowService.create($traceflow_request) + } + + catch + { + $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. Filter by MONITORING. + } + } + + End + { + if ($NSXTraceFlow) + { + Get-NSXttraceflow + } + } } \ No newline at end of file From cca008ed276773cc93e64c6b997064e5f26937e8 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Fri, 24 Aug 2018 19:49:32 -0400 Subject: [PATCH 005/175] VMWonAWS Firewall Rule Accelorator Script Addition of the script version of the VMware Cloud on AWS Firewall Rule Accelorator functionality --- .../VMWonAWS_FirewallRuleAccelerator.ps1 | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 Scripts/VMware_Cloud_on_AWS/VMWonAWS_FirewallRuleAccelerator.ps1 diff --git a/Scripts/VMware_Cloud_on_AWS/VMWonAWS_FirewallRuleAccelerator.ps1 b/Scripts/VMware_Cloud_on_AWS/VMWonAWS_FirewallRuleAccelerator.ps1 new file mode 100644 index 0000000..de5b870 --- /dev/null +++ b/Scripts/VMware_Cloud_on_AWS/VMWonAWS_FirewallRuleAccelerator.ps1 @@ -0,0 +1,209 @@ +# Author: Kyle Ruddy +# Product: VMware Cloud on AWS +# Description: VMware Cloud on AWS Firewall Rule Accelerator for PowerCLI +# Requirements: +# - PowerShell 3.x or newer +# - PowerCLI 6.5.4 or newer +# - Use Default IP Addresses +# - Use NSX-V on VMware Cloud on AWS + +#---------- USER VARIABLES ---------------------------------------- + +$oauthToken = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" +$orgId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx' +$sddcId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx' + +# ---------- DO NOT MODIFY BELOW THIS ------------------------------ + + +Connect-Vmc -RefreshToken $oauthToken | Out-Null + +$orgSvc = Get-VmcService -Name com.vmware.vmc.orgs + +if ($orgId) { + $org = $orgSvc.List() | where {$_.id -eq $orgId} +} +else {$org = $orgSvc.List()} + +if ($org -eq $null) {Write-Output "No Org Found. Exiting."; break} + +$sddcSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs + +if ($sddcId) { + $sddc = $sddcSvc.Get($org.id, $sddcId) +} +else {$sddc = $sddcSvc.List($org.id)} + +if ($sddc -eq $null) {Write-Output "No SDDC Found. Exiting."; break} +elseif ($sddc -is [array]) {Write-Output "Multiple SDDCs Found. Please Specify an SDDC ID. Exiting."; break} + +$edgeSvc = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges +$mgwEdge = ($edgeSvc.Get($org.id,$sddcId,'gatewayServices') | Select-Object -ExpandProperty edge_page).data | where {$_.id -eq 'edge-1'} + +$ipsecSvc = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.ipsec.config +$ipsecVPN = $ipsecSvc.Get($org.id, $sddcId, $mgwEdge.id) + +$localSubnet = $ipsecVPN.sites.sites.local_subnets.subnets +$vpnSubnet = $ipsecVPN.sites.sites.peer_subnets.subnets +$vcMgmtIP = $sddc.resource_config.vc_management_ip +$vcPublicIP = $sddc.resource_config.vc_public_ip +$esxSubnet = $sddc.resource_config.esx_host_subnet +$ipsecVPNname = $ipsecVPN.sites.sites.name + +function Add-VMCFirewallRule { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 08/22/2018 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + .SYNOPSIS + Creates a Firewall Rule for a given SDDC + .DESCRIPTION + Creates a Firewall Rule for a given SDDC + .EXAMPLE + Add-VMCFirewallRule -OrgId -sddcId -FwRuleName -SourceIpAddress -DestIpAddress -Service + + #> + param( + [Parameter(Mandatory=$true)] + [String]$OrgId, + [Parameter(Mandatory=$true)] + [String]$SddcId, + [Parameter(Mandatory=$false)] + [ValidateSet('Management Gateway','Compute Gateway')] + [String]$Edge = 'Management Gateway', + [Parameter(Mandatory=$true)] + [String]$FwRuleName, + [Parameter(Mandatory=$false)] + $SourceIpAddress, + [Parameter(Mandatory=$false)] + $DestIpAddress, + [Parameter(Mandatory=$true)] + [ValidateSet('HTTPS','ICMP','SSO','Provisioning','Any','Remote Console')] + [String]$Service, + [Parameter(Mandatory=$false)] + [ValidateSet('accept')] + $FwAction = 'accept' + + ) + + if ($edge -eq 'Management Gateway') {$EdgeId = 'edge-1'} + elseif ($edge -eq 'Compute Gateway') {$EdgeId = 'edge-2'} + else {Write-Output "No Valid Edge Input Found."} + + $fwRuleSvc = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + + $ruleElementSpec = $fwRuleSvc.Help.add.firewall_rules.firewall_rules.Element.Create() + $fwRules = $fwRuleSvc.Help.add.firewall_rules.Create() + $ruleSpec = $fwRuleSvc.Help.add.firewall_rules.firewall_rules.Create() + + # AppSpec + $appSpec = $fwRuleSvc.Help.add.firewall_rules.firewall_rules.Element.application.Create() + # ServiceSpec + $serviceSpec = $fwRuleSvc.Help.add.firewall_rules.firewall_rules.Element.application.service.Element.Create() + + if ($Service -eq 'HTTPS') { + $protocol = 'TCP' + $port = @("443") + } + elseif ($Service -eq 'ICMP') { + $protocol = 'ICMP' + $icmpType = 'any' + + } + elseif ($Service -eq 'SSO') { + $protocol = 'TCP' + $port = @("7444") + } + elseif ($Service -eq 'Provisioning') { + $protocol = 'TCP' + $port = @("902") + } + elseif ($Service -eq 'Any') { + $protocol = 'Any' + $port = $null + } + elseif ($Service -eq 'Remote Console') { + $protocol = 'TCP' + $port = @("903") + } + else {Write-Output "No Protocol Found."; break} + + $serviceSpec.protocol = $protocol + + # Process ICMP Type from JSON + $icmpType = $null + if($protocol -eq 'ICMP') { + $icmpType = 'any' + } + + if ($icmpType) { + $serviceSpec.icmp_type = $icmpType} + if ($port) { + $serviceSpec.port = $port + $serviceSpec.source_port = @("any") + } + + $addSpec = $ruleElementSpec.application.service.Add($serviceSpec) + + + # Create Source Spec + if($SourceIpAddress) { + $srcSpec = $fwRuleSvc.Help.add.firewall_rules.firewall_rules.Element.source.Create() + $srcSpec.exclude = $false + $srcSpec.ip_address = @($SourceIpAddress) + $ruleElementSpec.source = $srcSpec + } + + + # Create Destination Spec + if($DestIpAddress) { + $destSpec = $fwRuleSvc.Help.add.firewall_rules.firewall_rules.Element.destination.Create() + $destSpec.exclude = $false + $destSpec.ip_address = @($DestIpAddress) + $ruleElementSpec.destination = $destSpec + + } + + + $ruleElementSpec.rule_type = "user" + $ruleElementSpec.enabled = $true + $ruleElementSpec.logging_enabled = $false + + $ruleElementSpec.action = $FwAction + $ruleElementSpec.name = $FwRuleName + + # Add the individual FW rule spec into our overall firewall rules array + Write-Output "Creating VMC Firewall Rule: $FwRuleName" + $ruleSpecAdd = $ruleSpec.Add($ruleElementSpec) + + $fwRules.firewall_rules = $ruleSpec + $fwRuleAdd = $fwRuleSvc.add($orgId,$sddcId,$EdgeId,$fwRules) + +} + + +# vCenter (ANY) to VPN +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "vCenter (ANY) to $ipsecVPNname" -SourceIpAddress $vcMgmtIP -DestIpAddress $vpnSubnet -Service 'Any' + +# ESXi (ANY) to VPN +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "ESXi (ANY) to $ipsecVPNname" -SourceIpAddress $esxSubnet,'10.2.16.0/20' -DestIpAddress $vpnSubnet -Service 'Any' + +# VPN to vCenter (HTTPS) +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "$ipsecVPNname to vCenter (HTTPS)" -SourceIpAddress $vpnSubnet -DestIpAddress $vcMgmtIP -Service 'HTTPS' + +# VPN to vCenter (ICMP) +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "$ipsecVPNname to vCenter (ICMP)" -SourceIpAddress $vpnSubnet -DestIpAddress $vcMgmtIP -Service 'ICMP' + +# VPN to ESXi (Provisioning) +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "$ipsecVPNname to ESXi (Provisioning)" -SourceIpAddress $vpnSubnet -DestIpAddress $esxSubnet,'10.2.16.0/20' -Service 'Provisioning' + +# VPN to ESXi (Remove Console) +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "$ipsecVPNname to ESXi (Remote Console)" -SourceIpAddress $vpnSubnet -DestIpAddress $esxSubnet,'10.2.16.0/20' -Service 'Remote Console' + +# VPN to ESXi (ICMP) +Add-VMCFirewallRule -OrgId $org.Id -sddcId $sddc.id -FwRuleName "$ipsecVPNname to ESXi (ICMP)" -SourceIpAddress $vpnSubnet -DestIpAddress $esxSubnet,'10.2.16.0/20' -Service 'ICMP' \ No newline at end of file From 7086f2c823000d9aaf3672b1bb4d29159198c2dc Mon Sep 17 00:00:00 2001 From: "Michael D. Harlan" <40269730+r3mdh@users.noreply.github.com> Date: Tue, 28 Aug 2018 00:01:03 -0400 Subject: [PATCH 006/175] Update VMware.HV.Helper.psm1 --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 74bf078..57e5b2c 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -3568,30 +3568,35 @@ function New-HVPool { [string[]] $ConnectionServerRestrictions, - #desktopSpec.desktopSettings.logoffSettings.powerPloicy + #desktopSpec.desktopSettings.logoffSettings.powerPolicy [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 + #desktopSpec.desktopSettings.logoffSettings.powerPolicy + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [ValidateSet('IMMEDIATELY', 'NEVER', 'AFTER')] [string]$AutomaticLogoffPolicy = 'NEVER', #desktopSpec.desktopSettings.logoffSettings.automaticLogoffMinutes + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [ValidateRange(1,[int]::MaxValue)] [int]$AutomaticLogoffMinutes = 120, #desktopSpec.desktopSettings.logoffSettings.allowUsersToResetMachines + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [boolean]$allowUsersToResetMachines = $false, #desktopSpec.desktopSettings.logoffSettings.allowMultipleSessionsPerUser + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [boolean]$allowMultipleSessionsPerUser = $false, #desktopSpec.desktopSettings.logoffSettings.deleteOrRefreshMachineAfterLogoff + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [ValidateSet('NEVER', 'DELETE', 'REFRESH')] [string]$deleteOrRefreshMachineAfterLogoff = 'NEVER', @@ -3612,25 +3617,30 @@ function New-HVPool { #DesktopDisplayProtocolSettings #desktopSpec.desktopSettings.logoffSettings.supportedDisplayProtocols + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [ValidateSet('RDP', 'PCOIP', 'BLAST')] [string[]]$supportedDisplayProtocols = @('RDP', 'PCOIP', 'BLAST'), #desktopSpec.desktopSettings.logoffSettings.defaultDisplayProtocol + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [ValidateSet('RDP', 'PCOIP', 'BLAST')] [string]$defaultDisplayProtocol = 'PCOIP', #desktopSpec.desktopSettings.logoffSettings.allowUsersToChooseProtocol + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [int]$allowUsersToChooseProtocol = $true, #desktopSpec.desktopSettings.logoffSettings.enableHTMLAccess + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [boolean]$enableHTMLAccess = $false, # DesktopPCoIPDisplaySettings #desktopSpec.desktopSettings.logoffSettings.pcoipDisplaySettings.renderer3D + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [ValidateSet('MANAGE_BY_VSPHERE_CLIENT', 'AUTOMATIC', 'SOFTWARE', 'HARDWARE', 'DISABLED')] [string]$renderer3D = 'DISABLED', @@ -3725,7 +3735,7 @@ function New-HVPool { [string] $ResourcePool, - #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.datacenter if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + #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')] @@ -3739,7 +3749,7 @@ function New-HVPool { [string[]] $Datastores, - #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastores.storageOvercommit if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + #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')] @@ -3980,7 +3990,8 @@ function New-HVPool { [string] $CustType, - #desktopSpec.automatedDesktopSpec.customizationSettings.reusePreExistingAccounts if LINKED_CLONE + #desktopSpec.automatedDesktopSpec.customizationSettings.reusePreExistingAccounts if LINKED_CLONE, INSTANT_CLONE + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] [Boolean] $ReusePreExistingAccounts = $false, @@ -5211,6 +5222,7 @@ function Get-HVPoolCustomizationSetting { throw "No Instant Clone Engine Domain Administrator found with netBiosName: [$netBiosName]" } $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings = Get-CustomizationObject + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.ReusePreExistingAccounts = $reusePreExistingAccounts $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.InstantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.powerOffScriptName = $powerOffScriptName $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings.powerOffScriptParameters = $powerOffScriptParameters From 127252196f417553ba09e05b7bb980f4f42563f0 Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 5 Sep 2018 11:46:41 -0700 Subject: [PATCH 007/175] SDDC Summary data using GET /sddc --- Modules/VMware.VMC/VMware.VMC.psm1 | 47 +++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 7b64047..982c0cc 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -855,4 +855,49 @@ Function New-VMCLogicalNetwork { Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName } -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork' \ No newline at end of file +Function Get-VMCSDDCSummary { + <# + .NOTES + =========================================================================== + Created by: VMware + Date: 09/04/18 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns a number of useful informational data about a given SDDC within VMC Org + .DESCRIPTION + Returns Version, Create/Expiration Date, Deployment Type, Region, AZ, Instance Type, VPC CIDR & NSX-T + .EXAMPLE + Get-VMCSDDCSummary -Name -Org + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $Org).Id + $sddcId = (Get-VMCSDDC -Name $Name -Org $Org).Id + + $sddcService = Get-VmcService "com.vmware.vmc.orgs.sddcs" + $sddc = $sddcService.get($orgId,$sddcId) + + $results = [pscustomobject] @{ + Version = $sddc.resource_config.sddc_manifest.vmc_version; + CreateDate = $sddc.created; + ExpirationDate = $sddc.expiration_date; + DeploymentType = $sddc.resource_config.deployment_type; + Region = $sddc.resource_config.region; + AvailabilityZone = $sddc.resource_config.availability_zones; + InstanceType = $sddc.resource_config.sddc_manifest.esx_ami.instance_type; + VpcCIDR = $sddc.resource_config.vpc_info.vpc_cidr; + NSXT = $sddc.resource_config.nsxt; + } + $results + } +} + +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary' \ No newline at end of file From 760c534cf74e1418d1fa61e232d6e1ecfd4c6f13 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Fri, 7 Sep 2018 11:02:42 -0500 Subject: [PATCH 008/175] Update VMware.HV.Helper.psm1 Added -DeleteFromDisk parameter to Remove-HVMachine Performed some minor cleanup (remove trailing whitespaces, capitalization) --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 98 +++++++++++-------- 1 file changed, 55 insertions(+), 43 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 74bf078..58026bb 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -9988,63 +9988,75 @@ function Reset-HVMachine { $services.machine.Machine_ResetMachines($machine.id) } } -function Remove-HVMachine(){ +function Remove-HVMachine { <# .Synopsis - Remove a Horizon View desktop or desktops. - + Remove a Horizon View desktop or desktops. + .DESCRIPTION - Deletes a VM or an array of VM's from Horizon. Utilizes an Or query filter to match machine names. + Deletes a VM or an array of VM's from Horizon. Utilizes an Or query filter to match machine names. .PARAMETER HVServer - The Horizon server where the machine to be deleted resides.Parameter is not mandatory, - but if you do not specify the server, than make sure you are connected to a Horizon server + The Horizon server where the machine to be deleted resides. Parameter is not mandatory, + but if you do not specify the server, than make sure you are connected to a Horizon server first with connect-hvserver. .PARAMETER MachineNames - The name or names of the machine(s) to be deleted. Accepts a single VM or an array of VM names.This is a mandatory parameter. + The name or names of the machine(s) to be deleted. Accepts a single VM or an array of VM names.This is a mandatory parameter. + + .PARAMETER DeleteFromDisk + Determines whether the Machine VM should be deleted from vCenter Server. This is only applicable for managed machines. + This must always be true for machines in linked and instant clone desktops. + This defaults to true for linked and instant clone machines and false for all other types. .EXAMPLE - remove-HVMachine -HVServer 'horizonserver123' -MachineNames 'LAX-WIN10-002' - Deletes VM 'LAX-WIN10-002' from HV Server 'horizonserver123' + Remove-HVMachine -HVServer 'horizonserver123' -MachineNames 'LAX-WIN10-002' + Deletes VM 'LAX-WIN10-002' from HV Server 'horizonserver123' .EXAMPLE - remove-HVMachine -HVServer 'horizonserver123' -MachineNames $machines - Deletes VM's contained within an array of machine names from HV Server 'horizonserver123' - + Remove-HVMachine -HVServer 'horizonserver123' -MachineNames $machines + Deletes VM's contained within an array of machine names from HV Server 'horizonserver123' + + .EXAMPLE + Remove-HVMachine -HVServer 'horizonserver123' -MachineNames 'ManualVM01' -DeleteFromDisk:$false + Deletes VM 'ManualVM01' from Horizon inventory, but not from vSphere. Note this only works for Full Clone VMs. + .NOTES Author : Jose Rodriguez Author email : jrodsguitar@gmail.com Version : 1.0 - + ===Tested Against Environment==== Horizon View Server Version : 7.1.1 PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> - - [CmdletBinding( + + [CmdletBinding( SupportsShouldProcess = $true, ConfirmImpact = 'High' )] - - param( - + + param( + [Parameter(Mandatory = $true)] [array] - $MachineNames, - + $MachineNames, + + [Parameter(Mandatory = $false)] + [switch]$DeleteFromDisk = $true, + [Parameter(Mandatory = $false)] $HVServer = $null - ) + ) #Connect to HV Server $services = Get-ViewAPIService -HVServer $HVServer - - if ($null -eq $services) { - Write-Error "Could not retrieve ViewApi services from connection object" + +if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" break - } + } #Connect to Query Service $queryService = New-Object 'Vmware.Hv.QueryServiceService' @@ -10096,9 +10108,9 @@ $trys = 0 foreach($session in $deleteMachine.base.session){ $sessions = $null - [VMware.Hv.SessionId[]]$sessions += $session - - } + [VMware.Hv.SessionId[]]$sessions += $session + + } try{ @@ -10110,8 +10122,8 @@ $trys = 0 #Wait more for Sessions to end - Start-Sleep -Seconds 5 - + Start-Sleep -Seconds 5 + } catch{ @@ -10121,39 +10133,39 @@ $trys = 0 write-host ($deleteMachine.base.Name -join "`n") start-sleep -seconds 5 - + } - - if(($trys -le 10)){ - + + if(($trys -le 10)){ + write-host "`n" write-host "Retrying Logoffs: $trys times" #Recheck existing sessions $deleteMachine = $machineService.Machine_GetInfos($services,$deleteThisMachine.Id) - + } - - $trys++ + + $trys++ } until((!$deleteMachine.base.session.id) -or ($trys -gt 10)) - + } #Create delete spec for the DeleteMachines method $deleteSpec = [VMware.Hv.MachineDeleteSpec]::new() -$deleteSpec.DeleteFromDisk = $true +$deleteSpec.DeleteFromDisk = $DeleteFromDisk $deleteSpec.ArchivePersistentDisk = $false - + #Delete the machines -write-host "Attempting to Delete:" +write-host "Attempting to Delete:" Write-Output ($deleteMachine.base.Name -join "`n") $bye = $machineService.Machine_DeleteMachines($services,$deleteMachine.id,$deleteSpec) [System.gc]::collect() - -} + +} function get-hvhealth { <# From a753d8251bb756aa3c523302859a95874e87d290 Mon Sep 17 00:00:00 2001 From: AndyG Date: Wed, 12 Sep 2018 13:31:03 -0400 Subject: [PATCH 009/175] Major refactoring Major refactoring - replaced hashtables with classes. Can now accept pipeline input. --- Modules/NSXT/NSXT.psm1 | 342 +++++++++++++++++++++++++++++++---------- 1 file changed, 260 insertions(+), 82 deletions(-) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index b2f9c3c..d80a565 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -259,89 +259,114 @@ Function Get-NSXTManager { $results } -Function Get-NSXTTransportNodes { +Function Get-NSXTTransportNode { Param ( - [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id","Tranportnode_id")] + [string]$transport_node_id ) - $transport_nodesService = Get-NsxtService -Name "com.vmware.nsx.transport_nodes" - $transport_nodesstateService = Get-NsxtService -Name "com.vmware.nsx.transport_nodes.state" - - if($Id) { - $transport_nodes = $transport_nodesService.get($Id) - } else { - $transport_nodes = $transport_nodesService.list().results - } + begin + { + $NSXTransportNodesService = Get-NsxtService -Name "com.vmware.nsx.transport_nodes" - $results = @() - foreach ($transport_node in $transport_nodes) { - - $transport_nodesstate = $transport_nodesstateService.get("$($transport_node.Id)") - - $tmp = [pscustomobject] @{ - Id = $transport_node.Id; - Name = $transport_node.display_name; - Tags = $transport_node.tags; - MaintenanceMode = $transport_node.maintenance_mode; - HostSwitchesName = $transport_node.host_switches.host_switch_name; - Default_gateway = $transport_nodesstate.host_switch_states.endpointsdefault_gateway; - Device_name = $transport_nodesstate.host_switch_states.endpoints.device_name; - Ip = $transport_nodesstate.host_switch_states.endpoints.ip; - Subnet_mask =$transport_nodesstate.host_switch_states.endpoints.subnet_mask + class NSXTransportNode { + [string]$Name + [string]$Tranport_node_id + [string]$maintenance_mode + hidden $tags = [System.Collections.Generic.List[string]]::new() + hidden $host_switches = [System.Collections.Generic.List[string]]::new() + hidden [string]$host_switch_spec + hidden $transport_zone_endpoints = [System.Collections.Generic.List[string]]::new() } - $results+=$tmp } - $results + Process + { + if($transport_node_id) { + $NSXTransportNodes = $NSXTransportNodesService.get($transport_node_id) + } else { + $NSXTransportNodes = $NSXTransportNodesService.list().results + } + + foreach ($NSXTransportNode in $NSXTransportNodes) { + + $results = [NSXTransportNode]::new() + $results.Name = $NSXTransportNode.display_name; + $results.Tranport_node_id = $NSXTransportNode.Id; + $results.maintenance_mode = $NSXTransportNode.maintenance_mode; + $results.Tags = $NSXTransportNode.tags; + $results.host_switches = $NSXTransportNode.host_switches; + $results.host_switch_spec = $NSXTransportNode.host_switch_spec; + $results.transport_zone_endpoints = $NSXTransportNode.transport_zone_endpoints; + $results.host_switches = $NSXTransportNode.host_switches + write-output $results + } + } } -Function Get-NSXTTraceFlows { +Function Get-NSXTTraceFlow { Param ( - [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id + [parameter(Mandatory=$false,ValueFromPipeline=$true)] + [Alias("Id")] + [string]$traceflow_id ) $NSXTraceFlowsService = Get-NsxtService -Name "com.vmware.nsx.traceflows" - if($Id) { - $NSXTraceFlows = $NSXTraceFlowsService.get($Id) + if($traceflow_id) { + $NSXTraceFlows = $NSXTraceFlowsService.get($traceflow_id) } else { $NSXTraceFlows = $NSXTraceFlowsService.list().results } - $results = @() - foreach ($NSXTraceFlow in $NSXTraceFlows) { - - $tmp = [pscustomobject] @{ - Id = $NSXTraceFlow.Id; - Operation_State = $NSXTraceFlow.operation_state; - Delivered = $NSXTraceFlow.Counters.delivered_count; - Dropped = $NSXTraceFlow.Counters.dropped_count; - Analysis = $NSXTraceFlow.maintenance_mode; - } - $results+=$tmp + class NSXTraceFlow { + [string]$traceflow_id + hidden [string]$lport_id + [string]$Operation_State + [int]$Forwarded + [int]$Delivered + [int]$Received + [int]$Dropped + [string]$Analysis } - $results - - if ($Id) { - write-output $Id - } + foreach ($NSXTraceFlow in $NSXTraceFlows) { + + $results = [NSXTraceFlow]::new() + $results.traceflow_id = $NSXTraceFlow.Id; + $results.Operation_State = $NSXTraceFlow.operation_state; + $results.forwarded = $NSXTraceFlow.Counters.forwarded_count; + $results.delivered = $NSXTraceFlow.Counters.delivered_count; + $results.received = $NSXTraceFlow.Counters.received_count; + $results.dropped = $NSXTraceFlow.Counters.dropped_count; + $results.analysis = $NSXTraceFlow.analysis + write-output $results + } } Function Get-NSXTTraceFlowObservations { Param ( - [parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Id + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$traceflow_id ) - $NSXTraceFlowsObservService = Get-NsxtService -Name "com.vmware.nsx.traceflows.observations" - - if($Id) { - $NSXTraceFlowsObserv = $NSXTraceFlowsObservService.list($Id) - } else { - throw "TraceFlow ID required" + begin + { + $NSXTraceFlowsObservService = Get-NsxtService -Name "com.vmware.nsx.traceflows.observations" } + + Process + { + if($traceflow_id) { + $NSXTraceFlowsObserv = $NSXTraceFlowsObservService.list($traceflow_id) + } else { + throw "TraceFlow ID required" + } - $NSXTraceFlowsObserv.results | select transport_node_name,component_name,@{N='PacketEvent';E={($_.resource_type).TrimStart("TraceflowObservation")}} + $NSXTraceFlowsObserv.results | select transport_node_name,component_name,@{N='PacketEvent';E={($_.resource_type).TrimStart("TraceflowObservation")}} + } } Function Set-NSXTTraceFlow { @@ -416,36 +441,55 @@ Function Set-NSXTTraceFlow { $NSXTraceFlowsService = Get-NsxtService -Name "com.vmware.nsx.traceflows" - # This is where I need help - the method does not ingest the complete $traceflow_request object! + class ip_header { + [string]$src_ip + [string]$dst_ip + } + + class eth_header { + [string]$src_mac + [string]$dst_mac + } + + class packet_data { + [boolean]$routed + [ValidateSet("UNICAST","BROADCAST","MULTICAST","UNKNOWN")] + [string]$transport_type + [ValidateSet("BINARYPACKETDATA","FIELDSPACKETDATA")] + [string]$resource_type + [long]$frame_size + [eth_header]$eth_header = [eth_header]::new() + [ip_header]$ip_header = [ip_header]::new() - # Create the example object - $traceflow_request = $NSXTraceFlowService.help.create.traceflow_request.Create() - $traceflow_request.lport_id = $LPORTID + packet_data(){ + $this.routed = 'true' + $this.transport_type = 'UNICAST' + $this.resource_type = 'FieldsPacketData' + } + } + + class traceflow_request { + [string]$lport_id + [long]$timeout + [packet_data]$packet = [packet_data]::new() + + traceflow_request(){ + $this.timeout = '15000' + } + } + + [traceflow_request]$traceflow_request = [traceflow_request]::new() + + $traceflow_request.lport_id = '8afcd58a-4bdc-483c-97a5-c5f08df7f772' $traceflow_request.timeout = '15000' $traceflow_request.packet.routed = 'true' - $traceflow_request.packet.transport_type = $TrafficType.ToUpper() + $traceflow_request.packet.transport_type = 'UNICAST' $traceflow_request.packet.resource_type = 'FieldsPacketData' - $traceflow_request.packet.frame_size = '64' - - # The example object is missing packet data, so we create it. - $eth_header = @{src_mac = $SMAC;eth_type = '2048';dst_mac = $DMAC} - $ip_header = @{src_ip = $SIPAddr;protocol = '1';ttl = '64';dst_ip = $DIPAddr} - $traceflow_request.packet | Add-Member -NotePropertyMembers $eth_header -TypeName eth_header - $traceflow_request.packet | Add-Member -NotePropertyMembers $ip_header -TypeName ip_header - - # Alternative method of creating $traceflow_request (not working either) - <# - $TraceFlow_Request = [PSCustomObject]@{ - packet = @{routed = 'true'; - transport_type = $TrafficType.ToUpper(); - ip_header = @{src_ip = $SIPAddr;dst_ip = $DIPAddr}; - eth_header = @{dst_mac = $DMAC;src_mac = $SMAC}; - payload = 'test_payload'; - resource_type = 'FieldsPacketData'}; - timeout = '10000'; - lport_id = $LPORTID - } - #> + $traceflow_request.packet.frame_size = '128' + $traceflow_request.packet.eth_header.src_mac = '00:50:56:b3:90:e3' + $traceflow_request.packet.eth_header.dst_mac = '00:50:56:b3:0e:91' + $traceflow_request.packet.ip_header.src_ip = '15.128.160.20' + $traceflow_request.packet.ip_header.dst_ip = '15.128.160.24' } Process @@ -470,4 +514,138 @@ Function Set-NSXTTraceFlow { Get-NSXttraceflow } } -} \ No newline at end of file +} + +Function Get-NSXTEdgeCluster { + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$edge_cluster_id + ) + + Begin + { + $NSXTEdgeClustersService = Get-NsxtService -Name "com.vmware.nsx.edge_clusters" + + class NSXEdgeCluster { + [string]$Name + hidden [string]$Protection + hidden [string]$Tags + [string]$edge_cluster_id + [string]$resource_type + [string]$deployment_type + [string]$member_node_type + $members = [System.Collections.Generic.List[string]]::new() + $cluster_profile_bindings = [System.Collections.Generic.List[string]]::new() + } + } + + Process + { + if ($edge_cluster_id) { + $NSXEdgeClusters = $NSXTEdgeClustersService.get($edge_cluster_id) + } + else { + $NSXEdgeClusters = $NSXTEdgeClustersService.list().results + } + + foreach ($NSXEdgeCluster in $NSXEdgeClusters) { + + $results = [NSXEdgeCluster]::new() + $results.Name = $NSXEdgeCluster.display_name; + $results.Protection = $NSXEdgeCluster.Protection; + $results.edge_cluster_id = $NSXEdgeCluster.Id; + $results.resource_type = $NSXEdgeCluster.resource_type; + $results.Tags = $NSXEdgeCluster.tags; + $results.deployment_type = $NSXEdgeCluster.deployment_type; + $results.member_node_type = $NSXEdgeCluster.member_node_type; + $results.members = $NSXEdgeCluster.members; + $results.cluster_profile_bindings = $NSXEdgeCluster.cluster_profile_bindings + write-output $results + } + } +} + +Function Get-NSXTLogicalRouter { + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$Logical_router_id + ) + + begin + { + $NSXTLogicalRoutersService = Get-NsxtService -Name "com.vmware.nsx.logical_routers" + + class NSXTLogicalRouter { + [string]$Name + [string]$Logical_router_id + hidden [string]$Tags + [string]$edge_cluster_id + [ValidateSet("TIER0","TIER1")] + [string]$router_type + [ValidateSet("ACTIVE_ACTIVE","ACTIVE_STANDBY","")] + [string]$high_availability_mode + [ValidateSet("PREEMPTIVE","NON_PREEMPTIVE","")] + [string]$failover_mode + [string]$external_transit + [string]$internal_transit + } + } + + Process + { + if($Logical_router_id) { + $NSXLogicalRouters = $NSXTLogicalRoutersService.get($Logical_router_id) + } else { + $NSXLogicalRouters = $NSXTLogicalRoutersService.list().results + } + + foreach ($NSXLogicalRouter in $NSXLogicalRouters) { + + $results = [NSXTLogicalRouter]::new() + $results.Name = $NSXLogicalRouter.display_name; + $results.Logical_router_id = $NSXLogicalRouter.Id; + $results.Tags = $NSXLogicalRouter.tags; + $results.edge_cluster_id = $NSXLogicalRouter.edge_cluster_id; + $results.router_type = $NSXLogicalRouter.router_type; + $results.high_availability_mode = $NSXLogicalRouter.high_availability_mode; + $results.failover_mode =$NSXLogicalRouter.failover_mode; + $results.external_transit = $NSXLogicalRouter.advanced_config.external_transit_networks; + $results.internal_transit = $NSXLogicalRouter.advanced_config.internal_transit_network + write-output $results + } + } +} + +Function Get-NSXTRoutingTable { + Param ( + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [string]$Logical_router_id, + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [string]$Tranport_node_id + ) + + Begin + { + $NSXTRoutingTableService = Get-NsxtService -Name "com.vmware.nsx.logical_routers.routing.route_table" + + class NSXTRoutingTable { + [string]$Name + hidden [string]$Id + hidden $tags = [System.Collections.Generic.List[string]]::new() + #more things need to be added when .list actually works + } + } + + Process + { + $NSXTRoutingTable = [NSXTRoutingTable]::new() + + $NSXTRoutingTable = $NSXTRoutingTableService.list($Logical_router_id, $transport_node_id) + + #$NSXTRoutingTable = $NSXTRoutingTableService.list("ca02cb69-0210-4f34-8164-42943a1cc974","309fda89-3439-40ff-996e-b7eb2ec69ace") + + write-output $NSXTRoutingTable + } +} From 75a2562d974f96625c0d4aff7a8be43849362fb6 Mon Sep 17 00:00:00 2001 From: AndyG Date: Wed, 12 Sep 2018 13:45:38 -0400 Subject: [PATCH 010/175] Updates to Set-NSXTraceFlow Updates to Set-NSXTraceFlow. Added more comment and aligned variable names with api --- Modules/NSXT/NSXT.psm1 | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index d80a565..c68b135 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -378,21 +378,21 @@ Function Set-NSXTTraceFlow { ParameterSetName='Parameter Set VM Type')] [ValidateSet("UNICAST")] [string] - $TrafficType = "UNICAST", + $transport_type = "UNICAST", [parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Parameter Set VM Type')] [ValidateNotNullOrEmpty()] #[ValidateScript({Get-NSXTLogicalPort -Id $_}] [string] - $LPORTID, + $lport_id, [parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Parameter Set VM Type')] [ValidateNotNullOrEmpty()] [ValidateScript({$_ -match [IPAddress]$_})] [string] - $SIPAddr, + $src_ip, [parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Parameter Set VM Type')] @@ -403,14 +403,14 @@ Function Set-NSXTTraceFlow { } })] [string] - $SMAC, + $src_mac, [parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Parameter Set VM Type')] [ValidateNotNullOrEmpty()] [ValidateScript({$_ -match [IPAddress]$_ })] [string] - $DIPAddr, + $dst_ip, [parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Parameter Set VM Type')] @@ -421,7 +421,7 @@ Function Set-NSXTTraceFlow { } })] [string] - $DMAC) + $dst_mac) Begin { @@ -477,26 +477,22 @@ Function Set-NSXTTraceFlow { $this.timeout = '15000' } } - - [traceflow_request]$traceflow_request = [traceflow_request]::new() - - $traceflow_request.lport_id = '8afcd58a-4bdc-483c-97a5-c5f08df7f772' - $traceflow_request.timeout = '15000' - $traceflow_request.packet.routed = 'true' - $traceflow_request.packet.transport_type = 'UNICAST' - $traceflow_request.packet.resource_type = 'FieldsPacketData' - $traceflow_request.packet.frame_size = '128' - $traceflow_request.packet.eth_header.src_mac = '00:50:56:b3:90:e3' - $traceflow_request.packet.eth_header.dst_mac = '00:50:56:b3:0e:91' - $traceflow_request.packet.ip_header.src_ip = '15.128.160.20' - $traceflow_request.packet.ip_header.dst_ip = '15.128.160.24' } Process { + [traceflow_request]$traceflow_request = [traceflow_request]::new() + + $traceflow_request.lport_id = $lport_id + $traceflow_request.packet.transport_type = $transport_type + $traceflow_request.packet.eth_header.src_mac = $src_mac + $traceflow_request.packet.eth_header.dst_mac = $dst_mac + $traceflow_request.packet.ip_header.src_ip = $src_ip + $traceflow_request.packet.ip_header.dst_ip = $dst_ip + try { - # This does not work, ignores eth_header,ip_header etc.. Not clear why!? + # This does not work, bug report submitted to PowerCLI team $NSXTraceFlow = $NSXTraceFlowService.create($traceflow_request) } @@ -509,6 +505,7 @@ Function Set-NSXTTraceFlow { End { + # Likely don't need this and will replace with write-output $NSXTraceFlow but I can't test right now due to bug if ($NSXTraceFlow) { Get-NSXttraceflow @@ -642,10 +639,9 @@ Function Get-NSXTRoutingTable { { $NSXTRoutingTable = [NSXTRoutingTable]::new() + # this does not work, bug report submitted to PowerCLI team $NSXTRoutingTable = $NSXTRoutingTableService.list($Logical_router_id, $transport_node_id) - #$NSXTRoutingTable = $NSXTRoutingTableService.list("ca02cb69-0210-4f34-8164-42943a1cc974","309fda89-3439-40ff-996e-b7eb2ec69ace") - write-output $NSXTRoutingTable } } From 33bb7f6b3a9d05d94dbd39ca5795eb1f5b4ace2c Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 12 Sep 2018 11:38:49 -0700 Subject: [PATCH 011/175] Added {Get,New,Remove}-VMCPublicIP function --- Modules/VMware.VMC/VMware.VMC.psm1 | 110 ++++++++++++++++++++++++++++- 1 file changed, 109 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 982c0cc..919bea2 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -900,4 +900,112 @@ Function Get-VMCSDDCSummary { } } -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary' \ No newline at end of file +Function Get-VMCPublicIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves all public IP Addresses for a given SDDC + .DESCRIPTION + This cmdlet retrieves all public IP Address for a given SDDC + .EXAMPLE + Get-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + $publicIPs = $publicIPService.list($orgId,$sddcId) + + $publicIPs | select public_ip, name, allocation_id + } + } + + Function New-VMCPublicIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Request a new public IP Address for a given SDDC + .DESCRIPTION + This cmdlet requests a new public IP Address for a given SDDC + .EXAMPLE + New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$False)]$Description + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + $publicIPSpec = $publicIPService.Help.create.spec.Create() + $publicIPSpec.count = 1 + $publicIPSpec.names = @($Description) + + Write-Host "Requesting a new public IP Address for your SDDC ..." + $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) + } + } + + Function Remove-VMCPublicIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes a specific public IP Addresses for a given SDDC + .DESCRIPTION + This cmdlet removes a specific public IP Address for a given SDDC + .EXAMPLE + Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$AllocationId + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + Write-Host "Deleting public IP Address with ID $AllocationId ..." + $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + } + } + +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'New-VMCPublicIP', '', 'Remove-VMCPublicIP' \ No newline at end of file From 5b74c582b796a74b8c4758eb770aa5799aac736c Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 12 Sep 2018 12:23:37 -0700 Subject: [PATCH 012/175] Fixing typo --- Modules/VMware.VMC/VMware.VMC.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 919bea2..6605a14 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -1008,4 +1008,4 @@ Function Get-VMCPublicIP { } } -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'New-VMCPublicIP', '', 'Remove-VMCPublicIP' \ No newline at end of file +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP' From c34b602bf327bb7afc98e3266b6966561f8565d9 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 14 Sep 2018 08:58:53 -0400 Subject: [PATCH 013/175] Get-NSXTRoutingTable & Get-NSXTForwardingTable now work Get-NSXTRoutingTable & Get-NSXTForwardingTable now work. Thanks for Nick from VMW for pointing out the .help was incorrect and submitting a PR to update the API guide. --- Modules/NSXT/NSXT.psd1 | 18 ++- Modules/NSXT/NSXT.psm1 | 318 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 322 insertions(+), 14 deletions(-) diff --git a/Modules/NSXT/NSXT.psd1 b/Modules/NSXT/NSXT.psd1 index d9e25bc..01b05f0 100644 --- a/Modules/NSXT/NSXT.psd1 +++ b/Modules/NSXT/NSXT.psd1 @@ -7,7 +7,23 @@ Copyright = '(c) 2017. All rights reserved.' Description = 'Powershell Module for NSX-T REST API Functions' PowerShellVersion = '5.0' - FunctionsToExport = 'Get-NSXTComputeManager','Get-NSXTFabricNode','Get-NSXTFirewallRule','Get-NSXTIPPool','Get-NSXTLogicalSwitch','Get-NSXTManager','Get-NSXTTransportZone','Get-NSXTController','Get-NSXTTransportNodes' + FunctionsToExport = 'Get-NSXTComputeManager', + 'Get-NSXTFabricNode', + 'Get-NSXTFirewallRule', + 'Get-NSXTIPPool', + 'Get-NSXTLogicalSwitch', + 'Get-NSXTManager', + 'Get-NSXTTransportZone', + 'Get-NSXTController', + 'Get-NSXTTransportNodes', + 'Get-NSXTTraceFlow', + 'Get-NSXTEdgeCluster', + 'Get-NSXTLogicalRouter', + 'Get-NSXTRoutingTable', + 'Get-NSXTFabricVM', + 'Get-NSXTBGPNeighbors', + 'Get-NSXTForwardingTable', + 'Get-NSXTNetworkRoutes' PrivateData = @{ PSData = @{ Tags = @('NSX-T','REST') diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index c68b135..bc95e6d 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -573,10 +573,18 @@ Function Get-NSXTLogicalRouter { begin { $NSXTLogicalRoutersService = Get-NsxtService -Name "com.vmware.nsx.logical_routers" - + $NSXTLogicalRoutersStatusService = Get-NsxtService -Name "com.vmware.nsx.logical_routers.status" + + class per_node_status { + $service_router_id = [System.Collections.ArrayList]::new() + [ValidateSet("ACTIVE","STANDBY","DOWN","SYNC","UNKNOWN")] + $high_availability_status = [System.Collections.ArrayList]::new() + } + class NSXTLogicalRouter { [string]$Name [string]$Logical_router_id + [string]$protection hidden [string]$Tags [string]$edge_cluster_id [ValidateSet("TIER0","TIER1")] @@ -587,6 +595,9 @@ Function Get-NSXTLogicalRouter { [string]$failover_mode [string]$external_transit [string]$internal_transit + hidden [string]$advanced_config = [System.Collections.Generic.List[string]]::new() + hidden [string]$firewall_sections = [System.Collections.Generic.List[string]]::new() + $per_node_status = [per_node_status]::new() } } @@ -600,16 +611,26 @@ Function Get-NSXTLogicalRouter { foreach ($NSXLogicalRouter in $NSXLogicalRouters) { + $NSXTLogicalRoutersStatus = $NSXTLogicalRoutersStatusService.get($NSXLogicalRouter.id) $results = [NSXTLogicalRouter]::new() + + foreach ($NSXTLogicalRouterStatus in $NSXTLogicalRoutersStatus.per_node_status) { + $results.per_node_status.service_router_id.add($NSXTLogicalRouterStatus.service_router_id) 1>$null + $results.per_node_status.high_availability_status.add($NSXTLogicalRouterStatus.high_availability_status) 1>$null + } + $results.Name = $NSXLogicalRouter.display_name; $results.Logical_router_id = $NSXLogicalRouter.Id; + $results.protection = $NSXLogicalRouter.protection; $results.Tags = $NSXLogicalRouter.tags; $results.edge_cluster_id = $NSXLogicalRouter.edge_cluster_id; $results.router_type = $NSXLogicalRouter.router_type; $results.high_availability_mode = $NSXLogicalRouter.high_availability_mode; $results.failover_mode =$NSXLogicalRouter.failover_mode; $results.external_transit = $NSXLogicalRouter.advanced_config.external_transit_networks; - $results.internal_transit = $NSXLogicalRouter.advanced_config.internal_transit_network + $results.internal_transit = $NSXLogicalRouter.advanced_config.internal_transit_network; + $results.advanced_config =$NSXLogicalRouter.advanced_config; + $results.firewall_sections =$NSXLogicalRouter.firewall_sections write-output $results } } @@ -620,28 +641,299 @@ Function Get-NSXTRoutingTable { [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [string]$Logical_router_id, [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] - [string]$Tranport_node_id + [string]$transport_node_id ) Begin { $NSXTRoutingTableService = Get-NsxtService -Name "com.vmware.nsx.logical_routers.routing.route_table" - class NSXTRoutingTable { - [string]$Name - hidden [string]$Id - hidden $tags = [System.Collections.Generic.List[string]]::new() - #more things need to be added when .list actually works + class NSXTRoutingTable { + hidden [string]$Logical_router_id + [string]$lr_component_id + [string]$lr_component_type + [string]$network + [string]$next_hop + [string]$route_type + hidden [string]$logical_router_port_id + [long]$admin_distance + } + } + + Process + { + $NSXTRoutingTable = $NSXTRoutingTableService.list($Logical_router_id,$transport_node_id,$null,$null,$null,$null,$null,'realtime') + + foreach ($NSXTRoute in $NSXTRoutingTable.results) { + + $results = [NSXTRoutingTable]::new() + $results.Logical_router_id = $Logical_router_id; + $results.lr_component_type = $NSXTRoute.lr_component_type; + $results.lr_component_id = $NSXTRoute.lr_component_id; + $results.next_hop = $NSXTRoute.next_hop; + $results.route_type = $NSXTRoute.route_type; + $results.logical_router_port_id = $NSXTRoute.logical_router_port_id; + $results.admin_distance = $NSXTRoute.admin_distance; + $results.network = $NSXTRoute.network + write-output $results + } + } +} + +Function Get-NSXTFabricVM { + + Begin + { + $NSXTVMService = Get-NsxtService -Name "com.vmware.nsx.fabric.virtual_machines" + + class NSXVM { + [string]$Name + $resource_type + hidden [string]$Tags + hidden $compute_ids + hidden [string]$external_id + [string]$host_id + [string]$power_state + [string]$type + hidden $source + } + } + + Process + { + + $NSXTVMs = $NSXTVMService.list().results + + foreach ($NSXTVM in $NSXTVMs) { + + $results = [NSXVM]::new() + $results.Name = $NSXTVM.display_name; + $results.resource_type = $NSXTVM.resource_type; + $results.compute_ids = $NSXTVM.compute_ids; + $results.resource_type = $NSXTVM.resource_type; + $results.Tags = $NSXTVM.tags; + $results.external_id = $NSXTVM.external_id; + $results.host_id = $NSXTVM.host_id; + $results.power_state = $NSXTVM.power_state; + $results.type = $NSXTVM.type; + $results.source = $NSXTVM.source + write-output $results + } + } +} + +Function Get-NSXTBGPNeighbors { + Param ( + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$logical_router_id + ) + + begin + { + $NSXTThingsService = Get-NsxtService -Name "com.vmware.nsx.logical_routers.routing.bgp.neighbors" + + class NSXTBGPNeighbors { + [string]$Name + [string]$logical_router_id + hidden $tags = [System.Collections.Generic.List[string]]::new() + [string]$protection + [string]$resource_type + [string]$address_families = [System.Collections.Generic.List[string]]::new() + hidden $bfd_config + [bool]$enable_bfd + [bool]$enabled + hidden $filter_in_ipprefixlist_id + hidden $filter_in_routemap_id + hidden $filter_out_ipprefixlist_id + hidden $filter_out_routemap_id + hidden [long]$hold_down_timer + hidden [long]$keep_alive_timer + hidden [long]$maximum_hop_limit + [string]$neighbor_address + hidden [string]$password + [long]$remote_as + [string]$remote_as_num + [string]$source_address + [string]$source_addresses = [System.Collections.Generic.List[string]]::new() + } + } + + Process + { + $NSXTThings = $NSXTThingsService.list($logical_router_id).results + + foreach ($NSXTThing in $NSXTThings) { + + $results = [NSXTBGPNeighbors]::new() + $results.Name = $NSXTThing.display_name; + $results.logical_router_id = $NSXTThing.logical_router_id; + $results.tags = $NSXTThing.tags; + $results.protection = $NSXTThing.protection; + $results.resource_type = $NSXTThing.resource_type; + $results.address_families = $NSXTThing.address_families; + $results.bfd_config = $NSXTThing.bfd_config; + $results.enable_bfd = $NSXTThing.enable_bfd; + $results.enabled = $NSXTThing.enabled; + $results.filter_in_ipprefixlist_id = $NSXTThing.filter_in_ipprefixlist_id; + $results.filter_in_routemap_id = $NSXTThing.filter_in_routemap_id; + $results.filter_out_ipprefixlist_id = $NSXTThing.filter_out_ipprefixlist_id; + $results.filter_out_routemap_id = $NSXTThing.filter_out_routemap_id; + $results.hold_down_timer = $NSXTThing.hold_down_timer; + $results.keep_alive_timer = $NSXTThing.keep_alive_timer; + $results.maximum_hop_limit = $NSXTThing.maximum_hop_limit; + $results.neighbor_address = $NSXTThing.neighbor_address; + $results.password = $NSXTThing.password; + $results.remote_as = $NSXTThing.remote_as; + $results.remote_as_num = $NSXTThing.remote_as_num; + $results.source_address = $NSXTThing.source_address; + $results.source_addresses = $NSXTThing.source_addresses + write-output $results + } + } +} + +Function Get-NSXTForwardingTable { + Param ( + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [string]$Logical_router_id, + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [string]$transport_node_id + ) + + Begin + { + $NSXTForwardingTableService = Get-NsxtService -Name "com.vmware.nsx.logical_routers.routing.forwarding_table" + + class NSXTForwardingTable { + hidden [string]$Logical_router_id + [string]$lr_component_id + [string]$lr_component_type + [string]$network + [string]$next_hop + [string]$route_type + hidden [string]$logical_router_port_id } } Process { - $NSXTRoutingTable = [NSXTRoutingTable]::new() + $NSXTForwardingTable = $NSXTForwardingTableService.list($Logical_router_id,$transport_node_id,$null,$null,$null,$null,$null,$null,'realtime') - # this does not work, bug report submitted to PowerCLI team - $NSXTRoutingTable = $NSXTRoutingTableService.list($Logical_router_id, $transport_node_id) - - write-output $NSXTRoutingTable + foreach ($NSXTForwarding in $NSXTForwardingTable.results) { + + $results = [NSXTForwardingTable]::new() + $results.Logical_router_id = $Logical_router_id; + $results.lr_component_type = $NSXTForwarding.lr_component_type; + $results.lr_component_id = $NSXTForwarding.lr_component_id; + $results.network = $NSXTForwarding.network; + $results.next_hop = $NSXTForwarding.next_hop; + $results.route_type = $NSXTForwarding.route_type; + $results.logical_router_port_id = $NSXTForwarding.logical_router_port_id + write-output $results + } } } + + Function Get-NSXTNetworkRoutes { + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [string]$route_id + ) + + Begin + { + $NSXTNetworkRoutesService = Get-NsxtService -Name "com.vmware.nsx.node.network.routes" + + class NSXTNetworkRoutes { + [string]$route_id + $route_type + $interface_id + $gateway + $from_address + $destination + $netmask + $metric + $proto + $scope + $src + } + } + + Process + { + if ($route_id) { + $NSXTNetworkRoutes = $NSXTNetworkRoutesService.get($route_id) + } + else { + $NSXTNetworkRoutes = $NSXTNetworkRoutesService.list().results + } + + foreach ($NSXTRoute in $NSXTNetworkRoutes) { + + $results = [NSXTNetworkRoutes]::new() + $results.route_id = $NSXTRoute.route_id; + $results.route_type = $NSXTRoute.route_type; + $results.interface_id = $NSXTRoute.interface_id; + $results.gateway = $NSXTRoute.gateway; + $results.from_address = $NSXTRoute.from_address; + $results.destination = $NSXTRoute.destination; + $results.netmask = $NSXTRoute.netmask; + $results.metric = $NSXTRoute.metric; + $results.proto = $NSXTRoute.proto; + $results.scope = $NSXTRoute.scope; + $results.src = $NSXTRoute.src + write-output $results + } + } +} + +# Get Template +Function Get-NSXTThingTemplate { + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$Thing_id + ) + + begin + { + $NSXTThingsService = Get-NsxtService -Name "com.vmware.nsx.API.Thing" + + class NSXTThing { + [string]$Name + [string]$Thing1 + hidden [string]$Tags = [System.Collections.Generic.List[string]]::new() + [string]$Thing2 + #[ValidateSet("TIER0","TIER1")] + [string]$Thing3 + #[ValidateSet("ACTIVE_ACTIVE","ACTIVE_STANDBY","")] + [string]$Thing4 + #[ValidateSet("PREEMPTIVE","NON_PREEMPTIVE","")] + [string]$Thing5 + [string]$Thing6 + [string]$Thing7 + } + } + + Process + { + if($Thing_id) { + $NSXTThings = $NSXTThingsService.get($Thing_id) + } else { + $NSXTThings = $NSXTThingsService.list().results + } + + foreach ($NSXTThing in $NSXTThings) { + + $results = [NSXTThing]::new() + $results.Name = $NSXTThing.display_name; + $results.Logical_router_id = $NSXTThing.Id; + $results.Tags = $NSXTThing.tags; + $results.thing1 = $NSXTThing.thing1; + $results.thing2 = $NSXTThing.thing2 + + write-output $results + } + } +} \ No newline at end of file From 2103438f8a74bd2059ed3a5729df87ca237e2b94 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 14 Sep 2018 12:27:31 -0400 Subject: [PATCH 014/175] Added Help & Get-NSXTLogicalRouterPorts Added Help & Get-NSXTLogicalRouterPorts --- Modules/NSXT/NSXT.psd1 | 3 +- Modules/NSXT/NSXT.psm1 | 303 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 275 insertions(+), 31 deletions(-) diff --git a/Modules/NSXT/NSXT.psd1 b/Modules/NSXT/NSXT.psd1 index 01b05f0..46ddd8d 100644 --- a/Modules/NSXT/NSXT.psd1 +++ b/Modules/NSXT/NSXT.psd1 @@ -23,7 +23,8 @@ 'Get-NSXTFabricVM', 'Get-NSXTBGPNeighbors', 'Get-NSXTForwardingTable', - 'Get-NSXTNetworkRoutes' + 'Get-NSXTNetworkRoutes', + 'Get-NSXTLogicalRouterPorts' PrivateData = @{ PSData = @{ Tags = @('NSX-T','REST') diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index bc95e6d..145ba10 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -260,6 +260,17 @@ Function Get-NSXTManager { } Function Get-NSXTTransportNode { + <# + .Synopsis + Retrieves the transport_node information + .DESCRIPTION + Retrieves transport_node information for a single or multiple IDs. Execute with no parameters to get all ports, specify a transport_node if known. + .EXAMPLE + Get-NSXTTransportNode + .EXAMPLE + Get-NSXTThingTemplate -Tranport_node_id "TN ID" +#> + Param ( [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] [Alias("Id","Tranportnode_id")] @@ -272,7 +283,7 @@ Function Get-NSXTTransportNode { class NSXTransportNode { [string]$Name - [string]$Tranport_node_id + [string]$Transport_node_id [string]$maintenance_mode hidden $tags = [System.Collections.Generic.List[string]]::new() hidden $host_switches = [System.Collections.Generic.List[string]]::new() @@ -293,19 +304,30 @@ Function Get-NSXTTransportNode { $results = [NSXTransportNode]::new() $results.Name = $NSXTransportNode.display_name; - $results.Tranport_node_id = $NSXTransportNode.Id; + $results.Transport_node_id = $NSXTransportNode.Id; $results.maintenance_mode = $NSXTransportNode.maintenance_mode; $results.Tags = $NSXTransportNode.tags; $results.host_switches = $NSXTransportNode.host_switches; $results.host_switch_spec = $NSXTransportNode.host_switch_spec; $results.transport_zone_endpoints = $NSXTransportNode.transport_zone_endpoints; $results.host_switches = $NSXTransportNode.host_switches - write-output $results + $results } } } Function Get-NSXTTraceFlow { + <# + .Synopsis + Retrieves traceflow information + .DESCRIPTION + Retrieves traceflow information for a single or multiple traceflows. Execute with no parameters to get all traceflows, specify a traceflow_id if known. + .EXAMPLE + Get-NSXTTraceFlow + .EXAMPLE + Get-NSXTTraceFlow -traceflow_id "TF ID +#> + Param ( [parameter(Mandatory=$false,ValueFromPipeline=$true)] [Alias("Id")] @@ -341,11 +363,22 @@ Function Get-NSXTTraceFlow { $results.received = $NSXTraceFlow.Counters.received_count; $results.dropped = $NSXTraceFlow.Counters.dropped_count; $results.analysis = $NSXTraceFlow.analysis - write-output $results + $results } } Function Get-NSXTTraceFlowObservations { + <# + .Synopsis + Retrieves traceflow observations information + .DESCRIPTION + Retrieves traceflow observations information for a single traceflow. Must specify a current traceflow_id + .EXAMPLE + Get-NSXTTraceFlowObservations -traceflow_id "TF ID" + .EXAMPLE + Get-NSXTTraceFlow | Get-NSXTTraceFlowObservations +#> + Param ( [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Id")] @@ -370,6 +403,19 @@ Function Get-NSXTTraceFlowObservations { } Function Set-NSXTTraceFlow { + <# + .Synopsis + Creates a TraceFlow + .DESCRIPTION + Create a TraceFlow for later observation. + .EXAMPLE + Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" + .EXAMPLE + Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow + .EXAMPLE + Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow | Get-NSXTTraceFlowObservations +#> + [CmdletBinding()] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types @@ -498,22 +544,28 @@ Function Set-NSXTTraceFlow { catch { - $Error[0].Exception.ServerError.data + throw $Error[0].Exception.ServerError.data # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. Filter by MONITORING. } - } - End - { - # Likely don't need this and will replace with write-output $NSXTraceFlow but I can't test right now due to bug - if ($NSXTraceFlow) - { - Get-NSXttraceflow - } + $NSXTraceFlow } } Function Get-NSXTEdgeCluster { + <# + .Synopsis + Retrieves the Edge cluster information + .DESCRIPTION + Retrieves Edge cluster information for a single or multiple clusterss. Execute with no parameters to get all ports, specify a edge_cluster_id if known. + .EXAMPLE + Get-NSXTEdgeCluster + .EXAMPLE + Get-NSXTEdgeCluster -edge_cluster_id "Edge Cluster ID" + .EXAMPLE + Get-NSXTThingTemplate | where name -eq "My Edge Cluster Name" +#> + Param ( [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] [Alias("Id")] @@ -558,12 +610,27 @@ Function Get-NSXTEdgeCluster { $results.member_node_type = $NSXEdgeCluster.member_node_type; $results.members = $NSXEdgeCluster.members; $results.cluster_profile_bindings = $NSXEdgeCluster.cluster_profile_bindings - write-output $results + $results } } } Function Get-NSXTLogicalRouter { + <# + .Synopsis + Retrieves the Logical Router information + .DESCRIPTION + Retrieves Logical Router information for a single or multiple LR's. This includes corresponding SR's and transport_node_id. Execute with no parameters to get all ports, specify a Logical_router_id if known. + .EXAMPLE + Get-NSXTLogicalRouter + .EXAMPLE + Get-NSXTLogicalRouter -Logical_router_id "LR ID" + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq "LR Name" + .EXAMPLE + (Get-NSXTLogicalRouter -Logical_router_id "LR ID").per_node_status +#> + Param ( [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] [Alias("Id")] @@ -576,9 +643,22 @@ Function Get-NSXTLogicalRouter { $NSXTLogicalRoutersStatusService = Get-NsxtService -Name "com.vmware.nsx.logical_routers.status" class per_node_status { - $service_router_id = [System.Collections.ArrayList]::new() + $service_router_id [ValidateSet("ACTIVE","STANDBY","DOWN","SYNC","UNKNOWN")] - $high_availability_status = [System.Collections.ArrayList]::new() + $high_availability_status + $transport_node_id + + per_node_status(){} + + per_node_status( + $service_router_id, + $high_availability_status, + $transport_node_id + ) { + $this.service_router_id = $service_router_id + $this.high_availability_status = $high_availability_status + $this.transport_node_id = $transport_node_id + } } class NSXTLogicalRouter { @@ -597,7 +677,7 @@ Function Get-NSXTLogicalRouter { [string]$internal_transit hidden [string]$advanced_config = [System.Collections.Generic.List[string]]::new() hidden [string]$firewall_sections = [System.Collections.Generic.List[string]]::new() - $per_node_status = [per_node_status]::new() + $per_node_status = [System.Collections.Generic.List[string]]::new() } } @@ -613,10 +693,9 @@ Function Get-NSXTLogicalRouter { $NSXTLogicalRoutersStatus = $NSXTLogicalRoutersStatusService.get($NSXLogicalRouter.id) $results = [NSXTLogicalRouter]::new() - + foreach ($NSXTLogicalRouterStatus in $NSXTLogicalRoutersStatus.per_node_status) { - $results.per_node_status.service_router_id.add($NSXTLogicalRouterStatus.service_router_id) 1>$null - $results.per_node_status.high_availability_status.add($NSXTLogicalRouterStatus.high_availability_status) 1>$null + $results.per_node_status += [per_node_status]::new($NSXTLogicalRouterStatus.service_router_id,$NSXTLogicalRouterStatus.high_availability_status,$NSXTLogicalRouterStatus.transport_node_id) } $results.Name = $NSXLogicalRouter.display_name; @@ -631,12 +710,27 @@ Function Get-NSXTLogicalRouter { $results.internal_transit = $NSXLogicalRouter.advanced_config.internal_transit_network; $results.advanced_config =$NSXLogicalRouter.advanced_config; $results.firewall_sections =$NSXLogicalRouter.firewall_sections - write-output $results + $results } } } Function Get-NSXTRoutingTable { + <# + .Synopsis + Retrieves the routing table information + .DESCRIPTION + Retrieves routing table for a single LR including LR type (SR/DR) and next_hop. Must specify Logical_router_id & transport_node_id. Pipeline input supported. + .EXAMPLE + Get-NSXTRoutingTable -Logical_router_id "LR ID" -transport_node_id "TN ID" | format-table -autosize + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq "LR Name" | Get-NSXTRoutingTable -transport_node_id "TN ID" + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq INT-T1 | Get-NSXTRoutingTable -transport_node_id ((Get-NSXTTransportNode | where name -match "INT")[0].transport_node_id) + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq INT-T1 | Get-NSXTRoutingTable -transport_node_id (((Get-NSXTLogicalRouter | where name -eq INT-T1).per_node_status | where high_availability_status -eq ACTIVE).transport_node_id) +#> + Param ( [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [string]$Logical_router_id, @@ -675,13 +769,20 @@ Function Get-NSXTRoutingTable { $results.logical_router_port_id = $NSXTRoute.logical_router_port_id; $results.admin_distance = $NSXTRoute.admin_distance; $results.network = $NSXTRoute.network - write-output $results + $results } } } Function Get-NSXTFabricVM { - + <# + .Synopsis + Retrieves the VM's attached to the fabric. + .DESCRIPTION + Retrieves all VM's attached to the fabric. + .EXAMPLE + Get-NSXTFabricVM +#> Begin { $NSXTVMService = Get-NsxtService -Name "com.vmware.nsx.fabric.virtual_machines" @@ -717,12 +818,23 @@ Function Get-NSXTFabricVM { $results.power_state = $NSXTVM.power_state; $results.type = $NSXTVM.type; $results.source = $NSXTVM.source - write-output $results + $results } } } Function Get-NSXTBGPNeighbors { + <# + .Synopsis + Retrieves the BGP neighbor information + .DESCRIPTION + Retrieves BGP neighbor information for a single logical router. Must specify logical_router_id parameter. Pipeline input supported + .EXAMPLE + Get-NSXTBGPNeighbors -logical_router_id "LR ID" + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq "LR Name" | Get-NSXTBGPNeighbors +#> + Param ( [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Id")] @@ -788,12 +900,27 @@ Function Get-NSXTBGPNeighbors { $results.remote_as_num = $NSXTThing.remote_as_num; $results.source_address = $NSXTThing.source_address; $results.source_addresses = $NSXTThing.source_addresses - write-output $results + $results } } } Function Get-NSXTForwardingTable { + <# + .Synopsis + Retrieves the forwarding table information + .DESCRIPTION + Retrieves forwarding table for a single LR including LR type (SR/DR) and next_hop. Must specify Logical_router_id & transport_node_id. Pipeline input supported. + .EXAMPLE + Get-Get-NSXTForwardingTable -Logical_router_id "LR ID" -transport_node_id "TN ID" | format-table -autosize + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq "LR Name" | Get-NSXTForwardingTable -transport_node_id "TN ID" + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq "LR Name" | Get-NSXTForwardingTable -transport_node_id ((Get-NSXTTransportNode | where name -match "Edge Name")[0].transport_node_id) + .EXAMPLE + Get-NSXTLogicalRouter | where name -eq "LR Name" | Get-NSXTForwardingTable -transport_node_id (((Get-NSXTLogicalRouter | where name -eq "Edge Name").per_node_status | where high_availability_status -eq ACTIVE).transport_node_id) +#> + Param ( [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [string]$Logical_router_id, @@ -830,12 +957,23 @@ Function Get-NSXTForwardingTable { $results.next_hop = $NSXTForwarding.next_hop; $results.route_type = $NSXTForwarding.route_type; $results.logical_router_port_id = $NSXTForwarding.logical_router_port_id - write-output $results + $results } } } - Function Get-NSXTNetworkRoutes { +Function Get-NSXTNetworkRoutes { +<# + .Synopsis + Retrieves the network routes information + .DESCRIPTION + Retrieves the network routes information for a single or multiple routes. + .EXAMPLE + Get-NSXTNetworkRoutes + .EXAMPLE + Get-NSXTNetworkRoutes -route_id "Route ID" +#> + Param ( [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] [string]$route_id @@ -883,13 +1021,118 @@ Function Get-NSXTForwardingTable { $results.proto = $NSXTRoute.proto; $results.scope = $NSXTRoute.scope; $results.src = $NSXTRoute.src - write-output $results + $results } } } +Function Get-NSXTLogicalRouterPorts { +<# + .Synopsis + Retrieves the logical router port information + .DESCRIPTION + Retrieves logical router port information for a single or multiple ports. Execute with no parameters to get all ports, specify a single port if known, or feed a logical switch for filtered output. + .EXAMPLE + Get-NSXTLogicalRouterPorts + .EXAMPLE + Get-NSXTLogicalRouterPorts -logical_router_port_id "LR Port Name" + .EXAMPLE + Get-NSXTLogicalRouterPorts -logical_router_id "LR Name" + .EXAMPLE + Get-NSXTLogicalRouterPorts -logical_router_id (Get-NSXTLogicalRouter | where name -eq "LR Name") +#> + + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$logical_router_port_id, + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [string]$logical_router_id + ) + + begin + { + $NSXTLogicalRouterPortsService = Get-NsxtService -Name "com.vmware.nsx.logical_router_ports" + + class subnets { + $ip_addresses + $prefix_length + + subnets(){} + + subnets( + $ip_addresses, + $prefix_length + ) { + $this.ip_addresses = $ip_addresses + $this.prefix_length = $prefix_length + } + } + + class NSXTLogicalRouterPorts { + [string]$Name + $Id + [string]$logical_router_id + $resource_type + [string]$protection + $mac_address + $subnets = [System.Collections.Generic.List[string]]::new() + hidden [string]$Tags + hidden $linked_logical_switch_port_id + } + } + + Process + { + if($logical_router_port_id) { + $NSXTLogicalRouterPorts = $NSXTLogicalRouterPortsService.get($logical_router_port_id) + } else { + if ($logical_router_id) { + $NSXTLogicalRouterPorts = $NSXTLogicalRouterPortsService.list().results | where {$_.logical_router_id -eq $Logical_router_id} + } + else { + $NSXTLogicalRouterPorts = $NSXTLogicalRouterPortsService.list().results + } + } + + foreach ($NSXTLogicalRouterPort in $NSXTLogicalRouterPorts) { + + $results = [NSXTLogicalRouterPorts]::new() + + foreach ($subnet in $NSXTLogicalRouterPort.subnets) { + $results.subnets += [subnets]::new($subnet.ip_addresses,$subnet.prefix_length) + } + + $results.Name = $NSXTLogicalRouterPort.display_name + $results.Id = $NSXTLogicalRouterPort.Id + $results.Logical_router_id = $NSXTLogicalRouterPort.Logical_router_id + $results.resource_type = $NSXTLogicalRouterPort.resource_type + $results.protection = $NSXTLogicalRouterPort.protection + $results.Tags = $NSXTLogicalRouterPort.tags + $results.mac_address = $NSXTLogicalRouterPort.mac_address + $results.linked_logical_switch_port_id = $NSXTLogicalRouterPort.linked_logical_switch_port_id + $results + } + } +} + # Get Template Function Get-NSXTThingTemplate { + <# + .Synopsis + Retrieves the THING information + .DESCRIPTION + Retrieves THING information for a single or multiple ports. Execute with no parameters to get all ports, specify a PARAM if known. + .EXAMPLE + Get-NSXTThingTemplate + .EXAMPLE + Get-NSXTThingTemplate -param1 "LR Port Name" + .EXAMPLE + Get-NSXTThingTemplate -param2 "LR Name" + .EXAMPLE + Get-NSXTThingTemplate -param2 (Get-NSXTLogicalRouter | where name -eq "LR Name") +#> + Param ( [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] [Alias("Id")] @@ -933,7 +1176,7 @@ Function Get-NSXTThingTemplate { $results.thing1 = $NSXTThing.thing1; $results.thing2 = $NSXTThing.thing2 - write-output $results + $results } } -} \ No newline at end of file +} From 9a4acf5c57445e90cde776f3b17cf3887915e888 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 14 Sep 2018 15:51:11 -0400 Subject: [PATCH 015/175] Adding Set Commands Adding Set Commands --- Modules/NSXT/NSXT.psd1 | 32 +- Modules/NSXT/NSXT.psm1 | 994 +++++++++++++++++++++++++++++++---------- 2 files changed, 773 insertions(+), 253 deletions(-) diff --git a/Modules/NSXT/NSXT.psd1 b/Modules/NSXT/NSXT.psd1 index 46ddd8d..1ebab1e 100644 --- a/Modules/NSXT/NSXT.psd1 +++ b/Modules/NSXT/NSXT.psd1 @@ -7,24 +7,32 @@ Copyright = '(c) 2017. All rights reserved.' Description = 'Powershell Module for NSX-T REST API Functions' PowerShellVersion = '5.0' - FunctionsToExport = 'Get-NSXTComputeManager', + FunctionsToExport = 'Get-NSXTBGPNeighbors', + 'Get-NSXTComputeManager', + 'Get-NSXTController', + 'Get-NSXTEdgeCluster', 'Get-NSXTFabricNode', + 'Get-NSXTFabricVM', 'Get-NSXTFirewallRule', + 'Get-NSXTForwardingTable', 'Get-NSXTIPPool', + 'Get-NSXTLogicalRouter', + 'Get-NSXTLogicalRouterPorts', 'Get-NSXTLogicalSwitch', 'Get-NSXTManager', - 'Get-NSXTTransportZone', - 'Get-NSXTController', - 'Get-NSXTTransportNodes', - 'Get-NSXTTraceFlow', - 'Get-NSXTEdgeCluster', - 'Get-NSXTLogicalRouter', - 'Get-NSXTRoutingTable', - 'Get-NSXTFabricVM', - 'Get-NSXTBGPNeighbors', - 'Get-NSXTForwardingTable', 'Get-NSXTNetworkRoutes', - 'Get-NSXTLogicalRouterPorts' + 'Get-NSXTRoutingTable', + 'Get-NSXTThingTemplate', + 'Get-NSXTTraceFlow', + 'Get-NSXTTraceFlowObservations', + 'Get-NSXTTransportNode', + 'Get-NSXTTransportZone', + 'Set-NSXTIPPool', + 'Set-NSXTLogicalRouter', + 'Set-NSXTLogicalSwitch', + 'Set-NSXTThingTemplate', + 'Set-NSXTTraceFlow' + PrivateData = @{ PSData = @{ Tags = @('NSX-T','REST') diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 145ba10..aa30c32 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -71,63 +71,6 @@ Function Get-NSXTFabricNode { $results } -Function Get-NSXTIPPool { - Param ( - [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id - ) - - $ipPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" - - if($Id) { - $ipPools = $ipPoolService.get($Id) - } else { - $ipPools = $ipPoolService.list().results - } - - $results = @() - foreach ($ipPool in $ipPools) { - $tmp = [pscustomobject] @{ - Id = $ipPool.Id; - Name = $ipPool.Display_Name; - Total = $ipPool.pool_usage.total_ids; - Free = $ipPool.pool_usage.free_ids; - Network = $ipPool.subnets.cidr; - Gateway = $ipPool.subnets.gateway_ip; - DNS = $ipPool.subnets.dns_nameservers; - RangeStart = $ipPool.subnets.allocation_ranges.start; - RangeEnd = $ipPool.subnets.allocation_ranges.end - } - $results+=$tmp - } - $results -} - -Function Get-NSXTTransportZone { - Param ( - [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id - ) - - $transportZoneService = Get-NsxtService -Name "com.vmware.nsx.transport_zones" - - if($Id) { - $transportZones = $transportZoneService.get($Id) - } else { - $transportZones = $transportZoneService.list().results - } - - $results = @() - foreach ($transportZone in $transportZones) { - $tmp = [pscustomobject] @{ - Id = $transportZone.Id; - Name = $transportZone.display_name; - Type = $transportZone.transport_type; - HostSwitchName = $transportZone.host_switch_name; - } - $results+=$tmp - } - $results -} - Function Get-NSXTComputeManager { Param ( [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id @@ -160,38 +103,6 @@ Function Get-NSXTComputeManager { $results } -Function Get-NSXTLogicalSwitch { - Param ( - [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id - ) - - $logicalSwitchService = Get-NsxtService -Name "com.vmware.nsx.logical_switches" - $logicalSwitchSummaryService = Get-NsxtService -Name "com.vmware.nsx.logical_switches.summary" - - if($Id) { - $logicalSwitches = $logicalSwitchService.get($Id) - } else { - $logicalSwitches = $logicalSwitchService.list().results - } - - $results = @() - foreach ($logicalSwitch in $logicalSwitches) { - $transportZone = (Get-NSXTTransportZone -Id $logicalSwitch.transport_zone_id | Select Name | ft -HideTableHeaders | Out-String).trim() - $ports = $logicalSwitchSummaryService.get($logicalSwitch.id).num_logical_ports - - $tmp = [pscustomobject] @{ - Id = $logicalSwitch.Id; - Name = $logicalSwitch.display_name; - VLAN = $logicalSwitch.vlan; - AdminStatus = $logicalSwitch.admin_state; - Ports = $ports; - TransportZone = $transportZone; - } - $results+=$tmp - } - $results -} - Function Get-NSXTFirewallRule { Param ( [parameter(Mandatory=$false,ValueFromPipeline=$true)][string]$Id @@ -259,6 +170,8 @@ Function Get-NSXTManager { $results } +# Updated Function style below + Function Get-NSXTTransportNode { <# .Synopsis @@ -402,156 +315,6 @@ Function Get-NSXTTraceFlowObservations { } } -Function Set-NSXTTraceFlow { - <# - .Synopsis - Creates a TraceFlow - .DESCRIPTION - Create a TraceFlow for later observation. - .EXAMPLE - Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" - .EXAMPLE - Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow - .EXAMPLE - Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow | Get-NSXTTraceFlowObservations -#> - - [CmdletBinding()] - - # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types - Param ( - [parameter(Mandatory=$true, - ParameterSetName='Parameter Set VM Type')] - [ValidateSet("UNICAST")] - [string] - $transport_type = "UNICAST", - [parameter(Mandatory=$true, - ValueFromPipeline=$true, - ParameterSetName='Parameter Set VM Type')] - [ValidateNotNullOrEmpty()] - #[ValidateScript({Get-NSXTLogicalPort -Id $_}] - [string] - $lport_id, - [parameter(Mandatory=$true, - ValueFromPipeline=$true, - ParameterSetName='Parameter Set VM Type')] - [ValidateNotNullOrEmpty()] - [ValidateScript({$_ -match [IPAddress]$_})] - [string] - $src_ip, - [parameter(Mandatory=$true, - ValueFromPipeline=$true, - ParameterSetName='Parameter Set VM Type')] - [ValidateNotNullOrEmpty()] - [ValidateScript({$pattern = '^(([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))|(([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2}))$' - if ($_ -match ($pattern -join '|')) {$true} else { - throw "The argument '$_' does not match a valid MAC address format." - } - })] - [string] - $src_mac, - [parameter(Mandatory=$true, - ValueFromPipeline=$true, - ParameterSetName='Parameter Set VM Type')] - [ValidateNotNullOrEmpty()] - [ValidateScript({$_ -match [IPAddress]$_ })] - [string] - $dst_ip, - [parameter(Mandatory=$true, - ValueFromPipeline=$true, - ParameterSetName='Parameter Set VM Type')] - [ValidateNotNullOrEmpty()] - [ValidateScript({$pattern = '^(([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))|(([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2}))$' - if ($_ -match ($pattern -join '|')) {$true} else { - throw "The argument '$_' does not match a valid MAC address format." - } - })] - [string] - $dst_mac) - - Begin - { - if (-not $global:DefaultNsxtServers.isconnected) - { - - try - { - Connect-NsxtServer -Menu -ErrorAction Stop - } - - catch - { - throw "Could not connect to an NSX-T Manager, please try again" - } - } - - $NSXTraceFlowsService = Get-NsxtService -Name "com.vmware.nsx.traceflows" - - class ip_header { - [string]$src_ip - [string]$dst_ip - } - - class eth_header { - [string]$src_mac - [string]$dst_mac - } - - class packet_data { - [boolean]$routed - [ValidateSet("UNICAST","BROADCAST","MULTICAST","UNKNOWN")] - [string]$transport_type - [ValidateSet("BINARYPACKETDATA","FIELDSPACKETDATA")] - [string]$resource_type - [long]$frame_size - [eth_header]$eth_header = [eth_header]::new() - [ip_header]$ip_header = [ip_header]::new() - - packet_data(){ - $this.routed = 'true' - $this.transport_type = 'UNICAST' - $this.resource_type = 'FieldsPacketData' - } - } - - class traceflow_request { - [string]$lport_id - [long]$timeout - [packet_data]$packet = [packet_data]::new() - - traceflow_request(){ - $this.timeout = '15000' - } - } - } - - Process - { - [traceflow_request]$traceflow_request = [traceflow_request]::new() - - $traceflow_request.lport_id = $lport_id - $traceflow_request.packet.transport_type = $transport_type - $traceflow_request.packet.eth_header.src_mac = $src_mac - $traceflow_request.packet.eth_header.dst_mac = $dst_mac - $traceflow_request.packet.ip_header.src_ip = $src_ip - $traceflow_request.packet.ip_header.dst_ip = $dst_ip - - try - { - # This does not work, bug report submitted to PowerCLI team - $NSXTraceFlow = $NSXTraceFlowService.create($traceflow_request) - } - - catch - { - throw $Error[0].Exception.ServerError.data - # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. Filter by MONITORING. - } - - $NSXTraceFlow - } -} - Function Get-NSXTEdgeCluster { <# .Synopsis @@ -1116,6 +879,660 @@ Function Get-NSXTLogicalRouterPorts { } } +Function Get-NSXTTransportZone { + <# + .Synopsis + Retrieves the Transport Zone information + .DESCRIPTION + Retrieves THING information for a single or multiple ports. Execute with no parameters to get all ports, specify a PARAM if known. + .EXAMPLE + Get-NSXTTransportZone + .EXAMPLE + Get-NSXTTransportZone -zone_id "Zone ID" + .EXAMPLE + Get-NSXTTransportZone -name "Zone1" +#> + + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$zone_id, + [parameter(Mandatory=$false)] + [string]$name + ) + + begin + { + $NSXTTransportZoneService = Get-NsxtService -Name "com.vmware.nsx.transport_zones" + + class NSXTTransportZone { + [string]$Name + [string]$ID + hidden [string]$description + hidden $tags + $resource_type + $host_switch_name + $transport_type + hidden $transport_zone_profile_ids + $host_switch_mode + $protection + hidden $uplink_teaming_policy_names + } + } + + Process + { + if($zone_id) { + $NSXTTransportZones = $NSXTTransportZoneService.get($zone_id) + } else { + if ($name) { + $NSXTTransportZones = $NSXTTransportZoneService.list().results | where {$_.display_name -eq $name} + } + else { + $NSXTTransportZones = $NSXTTransportZoneService.list().results + } + } + + foreach ($NSXTTransportZone in $NSXTTransportZones) { + + $results = [NSXTTransportZone]::new() + $results.Name = $NSXTTransportZone.display_name; + $results.ID = $NSXTTransportZone.Id; + $results.description = $NSXTTransportZone.description; + $results.tags = $NSXTTransportZone.tags; + $results.resource_type = $NSXTTransportZone.resource_type; + $results.host_switch_name = $NSXTTransportZone.host_switch_name; + $results.transport_type = $NSXTTransportZone.transport_type; + $results.transport_zone_profile_ids = $NSXTTransportZone.transport_zone_profile_ids; + $results.host_switch_mode = $NSXTTransportZone.host_switch_mode; + $results.protection = $NSXTTransportZone.protection; + $results.uplink_teaming_policy_names = $NSXTTransportZone.uplink_teaming_policy_names + $results + } + } +} + +Function Get-NSXTLogicalSwitch { + <# + .Synopsis + Retrieves the Logical Switch information + .DESCRIPTION + Retrieves Logical Switch information for a single or multiple switches. Execute with no parameters to get all ports, specify a name or lswitch_id if known. + .EXAMPLE + Get-NSXTLogicalSwitch + .EXAMPLE + Get-NSXTLogicalSwitch -lswitch_id "switch id" + .EXAMPLE + Get-NSXTLogicalSwitch -name "switch name" +#> + + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$lswitch_id, + [parameter(Mandatory=$false)] + [string]$name + ) + + begin + { + $NSXTLogicalSwitchService = Get-NsxtService -Name "com.vmware.nsx.logical_switches" + + class NSXTLogicalSwitch { + [string]$Name + [string]$ID + $tags + $resource_type + hidden $description + $vni + $transport_zone_id + $admin_state + $replication_mode + hidden $address_bindings + $protection + hidden $extra_configs + $ip_pool_id + hidden $mac_pool_id + hidden $uplink_teaming_policy_name + hidden $vlan + hidden $vlan_trunk_spec + } + } + + Process + { + if($lswitch_id) { + $NSXTLogicalSwitches = $NSXTLogicalSwitchService.get($lswitch_id) + } else { + if ($name) { + $NSXTLogicalSwitches = $NSXTLogicalSwitchService.list().results | where {$_.display_name -eq $name} + } + else { + $NSXTLogicalSwitches = $NSXTLogicalSwitchService.list().results + } + } + + foreach ($NSXTLogicalSwitch in $NSXTLogicalSwitches) { + + $results = [NSXTLogicalSwitch]::new() + $results.Name = $NSXTLogicalSwitch.display_name; + $results.Id = $NSXTLogicalSwitch.Id; + $results.Tags = $NSXTLogicalSwitch.tags; + $results.resource_type = $NSXTLogicalSwitch.resource_type; + $results.description = $NSXTLogicalSwitch.description; + $results.vni = $NSXTLogicalSwitch.vni; + $results.transport_zone_id = $NSXTLogicalSwitch.transport_zone_id; + $results.admin_state = $NSXTLogicalSwitch.admin_state; + $results.replication_mode = $NSXTLogicalSwitch.replication_mode; + $results.address_bindings = $NSXTLogicalSwitch.address_bindings; + $results.protection = $NSXTLogicalSwitch.protection; + $results.extra_configs = $NSXTLogicalSwitch.extra_configs; + $results.ip_pool_id = $NSXTLogicalSwitch.ip_pool_id; + $results.mac_pool_id = $NSXTLogicalSwitch.mac_pool_id; + $results.uplink_teaming_policy_name = $NSXTLogicalSwitch.uplink_teaming_policy_name; + $results.vlan = $NSXTLogicalSwitch.vlan; + $results.vlan_trunk_spec = $NSXTLogicalSwitch.vlan_trunk_spec + $results + } + } +} + +Function Get-NSXTIPPool { + <# + .Synopsis + Retrieves the THING information + .DESCRIPTION + Retrieves THING information for a single or multiple ports. Execute with no parameters to get all ports, specify a PARAM if known. + .EXAMPLE + Get-NSXTIPPool + .EXAMPLE + Get-NSXTThingTemplate -pool_id "Pool ID" +#> + + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$pool_id, + [parameter(Mandatory=$false)] + [string]$name + ) + + begin + { + $NSXTIPPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" + + class NSXTIPPool { + [string]$Name + [string]$id + $total_ids + $free_ids + $allocated_ids + $Network + $Gateway + $DNS + $RangeStart + $RangeEnd + } + } + + Process + { + if($pool_id) { + $NSXTIPPools = $NSXTIPPoolService.get($pool_id) + } else { + if ($name) { + $NSXTIPPools = $NSXTIPPoolService.list().results | where {$_.display_name -eq $name} + } + else { + $NSXTIPPools = $NSXTIPPoolService.list().results + } + } + + foreach ($NSXTIPPool in $NSXTIPPools) { + + $results = [NSXTIPPool]::new() + $results.Name = $NSXTIPPool.display_name; + $results.ID = $NSXTIPPool.id; + $results.total_ids = $NSXTIPPool.pool_usage.total_ids; + $results.free_ids = $NSXTIPPool.pool_usage.free_ids; + $results.allocated_ids = $NSXTIPPool.pool_usage.allocated_ids; + $results.Network = $NSXTIPPool.subnets.cidr; + $results.Gateway = $NSXTIPPool.subnets.gateway_ip; + $results.DNS = $NSXTIPPool.subnets.dns_nameservers; + $results.RangeStart = $NSXTIPPool.subnets.allocation_ranges.start; + $results.RangeEnd = $NSXTIPPool.subnets.allocation_ranges.end + $results + } + } +} + +# Working Set Functions +Function Set-NSXTLogicalRouter { + <# + .Synopsis + Creates a Logical Router + .DESCRIPTION + Create a TIER0 or TIER1 logical router + .EXAMPLE + Set-NSXTLogicalRouter -display_name "Name" -high_availability_mode "ACTIVE_STANDBY" -router_type "TIER1" + .EXAMPLE + Set-NSXTLogicalRouter -display_name "Name" -high_availability_mode "ACTIVE_ACTIVE" -router_type "TIER0" -edge_cluster_id "Edge Cluster ID" + .EXAMPLE + Set-NSXTLogicalRouter -display_name "Name" -high_availability_mode "ACTIVE_STANDBY" -router_type "TIER1" -description "this is my new tier1 lr" +#> + + [CmdletBinding()] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$false, + ParameterSetName='TIER0')] + [parameter(Mandatory=$false, + ParameterSetName='TIER1')] + [string]$description, + + [parameter(Mandatory=$true, + ParameterSetName='TIER0')] + [parameter(Mandatory=$true, + ParameterSetName='TIER1')] + [string]$display_name, + + [parameter(Mandatory=$true, + ParameterSetName='TIER0')] + [parameter(Mandatory=$true, + ParameterSetName='TIER1')] + [ValidateSet("ACTIVE_ACTIVE","ACTIVE_STANDBY")] + [string]$high_availability_mode, + + [parameter(Mandatory=$true, + ParameterSetName='TIER0')] + [parameter(Mandatory=$true, + ParameterSetName='TIER1')] + [ValidateSet("TIER0","TIER1")] + [string]$router_type, + + [parameter(Mandatory=$true, + ParameterSetName='TIER0')] + [string]$edge_cluster_id + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTLogicalRouterService = Get-NsxtService -Name "com.vmware.nsx.logical_routers" + } + + Process + { + $logical_router_request = $NSXTLogicalRouterService.help.create.logical_router.Create() + + $logical_router_request.display_name = $display_name + $logical_router_request.description = $description + $logical_router_request.router_type = $router_type + $logical_router_request.high_availability_mode = $high_availability_mode + $logical_router_request.resource_type = "LogicalRouter" + $logical_router_request.failover_mode = "NON_PREEMPTIVE" + + if ($edge_cluster_id) { + $logical_router_request.edge_cluster_id = $edge_cluster_id + } + + try + { + # + $NSXTLogicalRouter = $NSXTLogicalRouterService.create($logical_router_request) + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + } + + $NSXTLogicalRouter + } +} + +Function Set-NSXTLogicalSwitch { + <# + .Synopsis + Creates a Logical Switch + .DESCRIPTION + Creates a Logical Switch with a number of required parameters. IP Pool is necessary even for an overlay logical switch + .EXAMPLE + Set-NSXTLogicalSwitch -display_name "Name" -transport_zone_id "TP Zone ID" + .EXAMPLE + Set-NSXTLogicalSwitch -display_name "Name" -transport_zone_id "TP Zone ID" -admin_state "UP" -replication_mode "MTEP" -ip_pool_id "IP Pool Name" +#> + + [CmdletBinding()] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$false)] + [string]$description, + + [parameter(Mandatory=$true)] + [string]$display_name, + + [parameter(Mandatory=$true)] + [string]$transport_zone_id, + + [parameter(Mandatory=$true)] + [ValidateSet("UP","DOWN")] + [string]$admin_state, + + [parameter(Mandatory=$false)] + [ValidateSet("MTEP","SOURCE")] + [string]$replication_mode, + + [parameter(Mandatory=$true)] + [string]$ip_pool_id + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTLogicalSwitchService = Get-NsxtService -Name "com.vmware.nsx.logical_switches" + } + + Process + { + $logical_switch_request = $NSXTLogicalSwitchService.help.create.logical_switch.Create() + + $logical_switch_request.display_name = $display_name + $logical_switch_request.description = $description + $logical_switch_request.admin_state = $admin_state + $logical_switch_request.transport_zone_id = $transport_zone_id + $logical_switch_request.resource_type = "LogicalSwitch" + $logical_switch_request.replication_mode = $replication_mode + $logical_switch_request.ip_pool_id = $ip_pool_id + + try + { + # + $NSXTLogicalSwitch = $NSXTLogicalSwitchService.create($logical_switch_request) + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + } + + $NSXTLogicalSwitch + } +} + +# Non-working Set Functions +Function Set-NSXTTraceFlow { + <# + .Synopsis + Creates a TraceFlow + .DESCRIPTION + Create a TraceFlow for later observation. + .EXAMPLE + Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" + .EXAMPLE + Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow + .EXAMPLE + Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow | Get-NSXTTraceFlowObservations +#> + + [CmdletBinding()] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateSet("UNICAST")] + [string] + $transport_type = "UNICAST", + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + #[ValidateScript({Get-NSXTLogicalPort -Id $_}] + [string] + $lport_id, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$_ -match [IPAddress]$_})] + [string] + $src_ip, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$pattern = '^(([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))|(([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2}))$' + if ($_ -match ($pattern -join '|')) {$true} else { + throw "The argument '$_' does not match a valid MAC address format." + } + })] + [string] + $src_mac, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$_ -match [IPAddress]$_ })] + [string] + $dst_ip, + [parameter(Mandatory=$true, + ValueFromPipeline=$true, + ParameterSetName='Parameter Set VM Type')] + [ValidateNotNullOrEmpty()] + [ValidateScript({$pattern = '^(([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))|(([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2}))$' + if ($_ -match ($pattern -join '|')) {$true} else { + throw "The argument '$_' does not match a valid MAC address format." + } + })] + [string] + $dst_mac) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTraceFlowsService = Get-NsxtService -Name "com.vmware.nsx.traceflows" + + # Comment out custom classes + <# + class ip_header { + [string]$src_ip + [string]$dst_ip + } + + class eth_header { + [string]$src_mac + [string]$dst_mac + } + + class packet_data { + [boolean]$routed + [ValidateSet("UNICAST","BROADCAST","MULTICAST","UNKNOWN")] + [string]$transport_type + [ValidateSet("BINARYPACKETDATA","FIELDSPACKETDATA")] + [string]$resource_type + [long]$frame_size + [eth_header]$eth_header = [eth_header]::new() + [ip_header]$ip_header = [ip_header]::new() + + packet_data(){ + $this.routed = 'true' + $this.transport_type = 'UNICAST' + $this.resource_type = 'FieldsPacketData' + } + } + + class traceflow_request { + [string]$lport_id + [long]$timeout + [packet_data]$packet = [packet_data]::new() + + traceflow_request(){ + $this.timeout = '15000' + } + } +#> + } + + Process + { + $traceflow_request = $NSXTraceFlowsService.Help.create.traceflow_request.Create() + + $traceflow_request.lport_id = $lport_id + $traceflow_request.packet.transport_type = $transport_type + + $eth_header = [ordered]@{'src_mac' = $src_mac;'eth_type' = '2048';'dst_mac' = $dst_mac} + $ip_header = [ordered]@{src_ip = $src_ip;protocol = '1';ttl = '64';dst_ip = $dst_ip} + $traceflow_request.packet | Add-Member -NotePropertyMembers $eth_header -TypeName eth_header + $traceflow_request.packet | Add-Member -NotePropertyMembers $ip_header -TypeName ip_header + + try + { + # This does not work, bug report submitted to PowerCLI team + $NSXTraceFlow = $NSXTraceFlowService.create($traceflow_request) + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. Filter by MONITORING. + } + + $NSXTraceFlow + } +} + +Function Set-NSXTIPPool { + <# + .Synopsis + Creates an IP Pool + .DESCRIPTION + Creates a IP Pool with a number of required parameters. Supported IP formats include 192.168.1.1, 192.168.1.1-192.168.1.100, 192.168.0.0/24 + .EXAMPLE + Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" + .EXAMPLE + Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" +#> + + [CmdletBinding()] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$true)] + [string]$display_name, + + [parameter(Mandatory=$false)] + [string]$description, + + [parameter(Mandatory=$false)] + [string]$dns_nameservers, + + [parameter(Mandatory=$true)] + [string]$allocation_start, + + [parameter(Mandatory=$true)] + [string]$allocation_end, + + [parameter(Mandatory=$true)] + [string]$cidr, + + [parameter(Mandatory=$false)] + [string]$gateway_ip + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTIPPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" + } + + Process + { + $ip_pool_request = $NSXTIPPoolService.help.create.ip_pool.Create() + $ip_pool_request.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Create() + $ip_pool_request.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create() + $ip_pool_request.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create() + $ip_pool_request.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create() + + $ip_pool_request.display_name = $display_name + $ip_pool_request.description = $description + $ip_pool_request.resource_type = "IpPool" + $ip_pool_request.subnets.dns_nameservers = $dns_nameservers + $ip_pool_request.subnets.allocation_ranges.start = $allocation_start + $ip_pool_request.subnets.allocation_ranges.end = $allocation_end + $ip_pool_request.subnets.cidr = $cidr + $ip_pool_request.subnets.gateway_ip = $gateway_ip + + try + { + # + $NSXTIPPool = $NSXTIPPoolService.create($ip_pool_request) + } + + catch + { + $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + throw + } + + $NSXTIPPool + } +} + # Get Template Function Get-NSXTThingTemplate { <# @@ -1136,7 +1553,9 @@ Function Get-NSXTThingTemplate { Param ( [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] [Alias("Id")] - [string]$Thing_id + [string]$Thing_id, + [parameter(Mandatory=$false)] + [string]$name ) begin @@ -1164,7 +1583,12 @@ Function Get-NSXTThingTemplate { if($Thing_id) { $NSXTThings = $NSXTThingsService.get($Thing_id) } else { - $NSXTThings = $NSXTThingsService.list().results + if ($name) { + $NSXTThings = $NSXTThingsService.list().results | where {$_.display_name -eq $name} + } + else { + $NSXTThings = $NSXTThingsService.list().results + } } foreach ($NSXTThing in $NSXTThings) { @@ -1180,3 +1604,91 @@ Function Get-NSXTThingTemplate { } } } + +# Set Template +Function Set-NSXTThingTemplate { + <# + .Synopsis + Creates a THING + .DESCRIPTION + Creates a THING with a number of required parameters. + .EXAMPLE + Set-NSXTThingTemplateh -param1 "Name" -param2 "TP Zone ID" + .EXAMPLE + Set-NSXTThingTemplateh -param1 "Name" -param2 "TP Zone ID" +#> + + [CmdletBinding()] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$false)] + [string]$description, + + [parameter(Mandatory=$true)] + [string]$display_name, + + [parameter(Mandatory=$true)] + [string]$transport_zone_id, + + [parameter(Mandatory=$true)] + [ValidateSet("UP","DOWN")] + [string]$admin_state, + + [parameter(Mandatory=$false)] + [ValidateSet("MTEP","SOURCE")] + [string]$replication_mode, + + [parameter(Mandatory=$true)] + [string]$ip_pool_id + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTTHINGService = Get-NsxtService -Name "com.vmware.nsx.THING" + } + + Process + { + $logical_THING_request = $NSXTTHINGService.help.create.logical_switch.Create() + + $logical_THING_request.display_name = $display_name + $logical_THING_request.description = $description + $logical_THING_request.admin_state = $admin_state + $logical_THING_request.transport_zone_id = $transport_zone_id + $logical_THING_request.resource_type = "LogicalSwitch" + $logical_THING_request.replication_mode = $replication_mode + $logical_THING_request.ip_pool_id = $ip_pool_id + + try + { + # + $NSXTTHING = $NSXTTHINGService.create($logical_THING_request) + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + } + + $NSXTTHING + } +} + + + + From 10f1f26ec16a571473bb8880e7ae7a538cf25835 Mon Sep 17 00:00:00 2001 From: AndyG Date: Fri, 14 Sep 2018 16:16:27 -0400 Subject: [PATCH 016/175] Don't want to export templates Don't want to export templates --- Modules/NSXT/NSXT.psd1 | 2 -- Modules/NSXT/NSXT.psm1 | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Modules/NSXT/NSXT.psd1 b/Modules/NSXT/NSXT.psd1 index 1ebab1e..537bf49 100644 --- a/Modules/NSXT/NSXT.psd1 +++ b/Modules/NSXT/NSXT.psd1 @@ -22,7 +22,6 @@ 'Get-NSXTManager', 'Get-NSXTNetworkRoutes', 'Get-NSXTRoutingTable', - 'Get-NSXTThingTemplate', 'Get-NSXTTraceFlow', 'Get-NSXTTraceFlowObservations', 'Get-NSXTTransportNode', @@ -30,7 +29,6 @@ 'Set-NSXTIPPool', 'Set-NSXTLogicalRouter', 'Set-NSXTLogicalSwitch', - 'Set-NSXTThingTemplate', 'Set-NSXTTraceFlow' PrivateData = @{ diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index aa30c32..07befe2 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -1452,7 +1452,7 @@ Function Set-NSXTIPPool { .EXAMPLE Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" .EXAMPLE - Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" + Set-NSXTIPPool -display_name "Test Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" #> [CmdletBinding()] From 14ecf2107de3bfc728046a86420b6d613a708f87 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 15 Sep 2018 05:32:19 -0700 Subject: [PATCH 017/175] Initial Commit --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 88 +++++++++++++ Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 127 +++++++++++++++++++ 2 files changed, 215 insertions(+) create mode 100644 Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 create mode 100644 Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 new file mode 100644 index 0000000..0e68563 --- /dev/null +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -0,0 +1,88 @@ +# +# Module manifest for module 'VMware.VMC.NSXT' +# +# Generated by: wlam@vmware.com +# +# Generated on: 09/11/18 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'VMware.VMC.NSXT.psm1' + +# Version number of this module. +ModuleVersion = '1.0.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = 'c094608a-7480-4751-a14c-c9dd68870607' + +# Author of this module +Author = 'William Lam' + +# Company or vendor of this module +CompanyName = 'VMware' + +# Copyright statement for this module +Copyright = '(c) 2018 VMware. All rights reserved.' + +# Description of the functionality provided by this module +Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' + +# Minimum version of the Windows PowerShell engine required by this module +PowerShellVersion = '6.0' + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment' +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() + +# Variables to export from this module +VariablesToExport = '*' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} \ No newline at end of file diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 new file mode 100644 index 0000000..72f5ebc --- /dev/null +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -0,0 +1,127 @@ +Function Connect-NSXTProxy { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves NSX-T Proxy URL + acquire CSP Access Token to then be used with NSXT-T Policy API + .DESCRIPTION + This cmdlet creates $global:nsxtProxyConnection object containing the NSX-T Proxy URL along with CSP Token + .EXAMPLE + Connect-NSXTProxy -RefreshToken $RefreshToken -OrgName $OrgName -SDDCName $SDDCName + .NOTES + You must be logged into VMC using Connect-VmcServer cmdlet +#> + Param ( + [Parameter(Mandatory=$true)][String]$RefreshToken, + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; exit } Else { + $sddcService = Get-VmcService "com.vmware.vmc.orgs.sddcs" + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $sddc = $sddcService.get($orgId,$sddcId) + if($sddc.resource_config.nsxt) { + $nsxtProxyURL = $sddc.resource_config.nsx_api_public_endpoint_url + } else { + Write-Host -ForegroundColor Red "This is not an NSX-T based SDDC" + break + } + } + + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + if($results.StatusCode -ne 200) { + Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" + break + } + $accessToken = ($results | ConvertFrom-Json).access_token + + $headers = @{ + "csp-auth-token"="$accessToken" + "Content-Type"="application/json" + "Accept"="application/json" + } + $global:nsxtProxyConnection = new-object PSObject -Property @{ + 'Server' = $nsxtProxyURL + 'headers' = $headers + } + $global:nsxtProxyConnection +} + +Function Get-NSXTSegment { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Segments (Logical Networks) + .DESCRIPTION + This cmdlet retrieves all NSX-T Segments (Logical Networks) + .EXAMPLE + Get-NSXTSegment + .EXAMPLE + Get-NSXTSegment -Name "sddc-cgw-network-1" +#> + Param ( + [Parameter(Mandatory=$False)]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $segmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$segmentsURL`n" + } + + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + + if($requests.StatusCode -eq 200) { + $segments = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $segments = $segments | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($segment in $segments) { + + $subnets = $segment.subnets + $network = $subnets.network + $gateway = $subnets.gateway_addresses + $dhcpRange = $subnets.dhcp_ranges + + $tmp = [pscustomobject] @{ + Name = $segment.display_name; + ID = $segment.Id; + Network = $network; + Gateway = $gateway; + DHCPRange = $dhcpRange; + } + $results+=$tmp + } + $results + } else { + Write-Error "Failed to retrieve NSX-T Segments" + } + } +} \ No newline at end of file From 5ee5c5d09a8f57185f0642fe4d47c58cd302dccc Mon Sep 17 00:00:00 2001 From: Wouter Kursten Date: Mon, 17 Sep 2018 09:39:07 +0200 Subject: [PATCH 018/175] added functions --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 116 +++++++++++++++++- 1 file changed, 115 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 57e5b2c..4779b9b 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11352,4 +11352,118 @@ function Clear-HVEventDatabase { } } -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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase +function Set-HVlicense { + <# + .Synopsis + Sets or changes the license for Horizon View + + .DESCRIPTION + Sets or changes the license for Horizon View + + .PARAMETER license + License key (string) + + .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-hvlicense -license "LICENSE-KEY" + Returns information about the sites within a Horizon View Pod Federation. + + .NOTES + Author : Wouter Kursten + Author email : wouter@retouw.nl + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.4,7.5 + PowerCLI Version : PowerCLI 10 + PowerShell Version : 5.0 + #> + + [CmdletBinding( + SupportsShouldProcess = $false, + ConfirmImpact = 'High' + )] + + param( + [Parameter(Mandatory = $true)] + [string] + $license, + + [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 + } + + try { + $services.license.license_set($license) + } + catch { + write-error $_.exception message + break + } + $licenseresult=$services.license.license_get() + return $licenseresult + [System.gc]::collect() +} + + +function Get-HVlicense { + <# + .Synopsis + Gets the license for Horizon View + + .DESCRIPTION + Gets the license for Horizon View + + + .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-hvlicense + + + .NOTES + Author : Wouter Kursten + Author email : wouter@retouw.nl + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.4,7.5 + PowerCLI Version : PowerCLI 10 + PowerShell Version : 5.0 + #> + + [CmdletBinding( + SupportsShouldProcess = $false, + 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 + } + + $license=$services.license.license_get() + return $license + [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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase,Get-HVlicense,Set-HVlicense From 9e569b139aeee0a9e994ff1bc07f6e99ef3b16ff Mon Sep 17 00:00:00 2001 From: AndyG Date: Tue, 18 Sep 2018 09:32:36 -0500 Subject: [PATCH 019/175] Added ShouldProcess to Set functions Added ShouldProcess to Set functions --- Modules/NSXT/NSXT.psm1 | 111 ++++++++++++++++++++++++++++++----------- 1 file changed, 83 insertions(+), 28 deletions(-) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 07befe2..4616168 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -1121,7 +1121,8 @@ Function Set-NSXTLogicalRouter { Set-NSXTLogicalRouter -display_name "Name" -high_availability_mode "ACTIVE_STANDBY" -router_type "TIER1" -description "this is my new tier1 lr" #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='Medium')] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( @@ -1191,8 +1192,11 @@ Function Set-NSXTLogicalRouter { try { - # - $NSXTLogicalRouter = $NSXTLogicalRouterService.create($logical_router_request) + # Should process + if ($pscmdlet.ShouldProcess($logical_router_request.display_name, "Create logical router")) + { + $NSXTLogicalRouter = $NSXTLogicalRouterService.create($logical_router_request) + } } catch @@ -1217,7 +1221,8 @@ Function Set-NSXTLogicalSwitch { Set-NSXTLogicalSwitch -display_name "Name" -transport_zone_id "TP Zone ID" -admin_state "UP" -replication_mode "MTEP" -ip_pool_id "IP Pool Name" #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='Medium')] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( @@ -1274,8 +1279,12 @@ Function Set-NSXTLogicalSwitch { try { - # - $NSXTLogicalSwitch = $NSXTLogicalSwitchService.create($logical_switch_request) + # Should process + if ($pscmdlet.ShouldProcess($logical_switch_request.display_name, "Create logical switch")) + { + $NSXTLogicalSwitch = $NSXTLogicalSwitchService.create($logical_switch_request) + } + } catch @@ -1303,7 +1312,8 @@ Function Set-NSXTTraceFlow { Set-NSXTTraceFlow -transport_type "UNICAST" -lport_id "LP ID" -src_ip "IP Address" -src_mac "MAC" -dst_ip "IP Address" -dst_mac "MAC" | Get-NSXTTraceFlow | Get-NSXTTraceFlowObservations #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='Medium')] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( @@ -1429,8 +1439,12 @@ Function Set-NSXTTraceFlow { try { - # This does not work, bug report submitted to PowerCLI team - $NSXTraceFlow = $NSXTraceFlowService.create($traceflow_request) + # Should process + if ($pscmdlet.ShouldProcess($traceflow_request.lport_id, "Create traceflow")) + { + # This does not work, bug report submitted to PowerCLI team + $NSXTraceFlow = $NSXTraceFlowService.create($traceflow_request) + } } catch @@ -1455,7 +1469,8 @@ Function Set-NSXTIPPool { Set-NSXTIPPool -display_name "Test Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='Medium')] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( @@ -1497,29 +1512,65 @@ Function Set-NSXTIPPool { } $NSXTIPPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" + + class allocation_ranges { + [string]$start + [string]$end + $self + } + + class subnets { + [string]$dns_nameservers + [string]$dns_suffix + [string]$cidr + [string]$gateway_ip + $allocation_ranges = [allocation_ranges]::new() + hidden $self + + } + + class ip_pool { + [string]$display_name + [string]$description + [string]$resource_type = 'IpPool' + [long]$revision = '0' + #$subnets = [subnets]::new() + $subnets = [System.Collections.Generic.List[subnets]]::new() + hidden $pool_usage + hidden $tags + hidden $self + hidden $links = [System.Collections.Generic.List[System.Management.Automation.PSObject]]::new() + } + } Process { - $ip_pool_request = $NSXTIPPoolService.help.create.ip_pool.Create() - $ip_pool_request.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Create() - $ip_pool_request.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create() - $ip_pool_request.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create() - $ip_pool_request.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create() + $ip_pool = [ip_pool]::new() + $ip_pool = $NSXTIPPoolService.help.create.ip_pool.Create() + $ip_pool.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Create() + $ip_pool.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create() + $ip_pool.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create() + $ip_pool.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create() + #$ip_pool = [ip_pool]::new() - $ip_pool_request.display_name = $display_name - $ip_pool_request.description = $description - $ip_pool_request.resource_type = "IpPool" - $ip_pool_request.subnets.dns_nameservers = $dns_nameservers - $ip_pool_request.subnets.allocation_ranges.start = $allocation_start - $ip_pool_request.subnets.allocation_ranges.end = $allocation_end - $ip_pool_request.subnets.cidr = $cidr - $ip_pool_request.subnets.gateway_ip = $gateway_ip + $ip_pool.display_name = $display_name + $ip_pool.description = $description + $ip_pool.resource_type = "IpPool" + $ip_pool.subnets.dns_nameservers = $dns_nameservers + $ip_pool.subnets.allocation_ranges.start = $allocation_start + $ip_pool.subnets.allocation_ranges.end = $allocation_end + $ip_pool.subnets.cidr = $cidr + $ip_pool.subnets.gateway_ip = $gateway_ip + $ip_pool.revision = 0 try { - # - $NSXTIPPool = $NSXTIPPoolService.create($ip_pool_request) + # Should process + if ($pscmdlet.ShouldProcess($ip_pool.display_name, "Create IP Pool")) + { + $NSXTIPPool = $NSXTIPPoolService.create($ip_pool) + } } catch @@ -1618,7 +1669,8 @@ Function Set-NSXTThingTemplate { Set-NSXTThingTemplateh -param1 "Name" -param2 "TP Zone ID" #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='Medium')] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( @@ -1675,8 +1727,11 @@ Function Set-NSXTThingTemplate { try { - # - $NSXTTHING = $NSXTTHINGService.create($logical_THING_request) + # Should process + if ($pscmdlet.ShouldProcess($ip_pool.display_name, "Create IP Pool")) + { + $NSXTTHING = $NSXTTHINGService.create($logical_THING_request) + } } catch From e8b64517c7b6a5121eba2c0725db3149e7da9010 Mon Sep 17 00:00:00 2001 From: AndyG Date: Tue, 18 Sep 2018 16:45:59 -0500 Subject: [PATCH 020/175] Added Get/Set/Remove IPAMIPBlock Added Get/Set/Remove IPAMIPBlock --- Modules/NSXT/NSXT.psd1 | 5 +- Modules/NSXT/NSXT.psm1 | 281 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 278 insertions(+), 8 deletions(-) diff --git a/Modules/NSXT/NSXT.psd1 b/Modules/NSXT/NSXT.psd1 index 537bf49..83026e8 100644 --- a/Modules/NSXT/NSXT.psd1 +++ b/Modules/NSXT/NSXT.psd1 @@ -29,7 +29,10 @@ 'Set-NSXTIPPool', 'Set-NSXTLogicalRouter', 'Set-NSXTLogicalSwitch', - 'Set-NSXTTraceFlow' + 'Set-NSXTTraceFlow', + 'Get-NSXTIPAMIPBlock', + 'Set-NSXTIPAMIPBlock', + 'Remove-NSXTIPAMIPBlock' PrivateData = @{ PSData = @{ diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 4616168..3d6a4f7 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -1106,6 +1106,72 @@ Function Get-NSXTIPPool { } } +Function Get-NSXTIPAMIPBlock { + <# + .Synopsis + Retrieves the IPAM IP Block information + .DESCRIPTION + Retrieves IPAM IP Block information for a single or multiple ports. Execute with no parameters to get all ports, specify a PARAM if known. + .EXAMPLE + Get-NSXTIPAMIPBlock + .EXAMPLE + Get-NSXTIPAMIPBlock -block_id "Block Id" + .EXAMPLE + Get-NSXTIPAMIPBlock -name "Block Name" + +#> + + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$block_id, + [parameter(Mandatory=$false)] + [string]$name + ) + + begin + { + $NSXTIPAMIPBlocksService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_blocks" + + class ip_block { + [string]$Name + [string]$block_id + hidden [string]$Tags = [System.Collections.Generic.List[string]]::new() + [string]$protection + #[ValidateSet("TIER0","TIER1")] + [string]$cidr + hidden [string]$resource_type + } + } + + Process + { + if($block_id) { + $NSXTIPAMIPBlocks = $NSXTIPAMIPBlocksService.get($block_id) + } else { + if ($name) { + $NSXTIPAMIPBlocks = $NSXTIPAMIPBlocksService.list().results | where {$_.display_name -eq $name} + } + else { + $NSXTIPAMIPBlocks = $NSXTIPAMIPBlocksService.list().results + } + } + + foreach ($NSXTIPAMIPBlock in $NSXTIPAMIPBlocks) { + + $results = [ip_block]::new() + $results.Name = $NSXTIPAMIPBlock.display_name; + $results.block_id = $NSXTIPAMIPBlock.id; + $results.Tags = $NSXTIPAMIPBlock.tags; + $results.protection = $NSXTIPAMIPBlock.protection; + $results.cidr = $NSXTIPAMIPBlock.cidr; + $results.resource_type = $NSXTIPAMIPBlock.resource_type + + $results + } + } +} + # Working Set Functions Function Set-NSXTLogicalRouter { <# @@ -1297,6 +1363,140 @@ Function Set-NSXTLogicalSwitch { } } +Function Set-NSXTIPAMIPBlock { + <# + .Synopsis + Creates an IPAM IP Block + .DESCRIPTION + Creates a IPAM IP Block with a cidr parameter. + .EXAMPLE + Set-NSXTIPAMIPBlock -name "IPAM Block Name" -cidr "192.168.0.0/24" +#> + + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='Medium')] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$false)] + [string]$description, + + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$display_name, + + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$cidr + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTIPAMIPBlockService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_blocks" + } + + Process + { + $IPAMIPBlock_request = $NSXTIPAMIPBlockService.help.create.ip_block.Create() + + $IPAMIPBlock_request.display_name = $display_name + $IPAMIPBlock_request.description = $description + $IPAMIPBlock_request.resource_type = "IpBlock" + $IPAMIPBlock_request.cidr = $cidr + + + try + { + # Should process + if ($pscmdlet.ShouldProcess($ip_pool.display_name, "Create IP Pool")) + { + $NSXTIPAMIPBlock = $NSXTIPAMIPBlockService.create($IPAMIPBlock_request) + } + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + } + + $NSXTIPAMIPBlock + } +} + +# Remove functions +Function Remove-NSXTIPAMIPBlock { + <# + .Synopsis + Removes an IPAM IP Block + .DESCRIPTION + Removes a IPAM IP Block with a block_id parameter. + .EXAMPLE + Remove-NSXTIPAMIPBlock -block_id "id" + .EXAMPLE + Get-NSXTIPAMIPBlock | where name -eq "IPAM Test2" | Remove-NSXTIPAMIPBlock +#> + + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='High')] + + Param ( + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [ValidateNotNullOrEmpty()] + [Alias("Id")] + [string]$block_id + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTIPAMIPBlockService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_blocks" + } + + Process + { + try + { + # Should process + if ($pscmdlet.ShouldProcess($block_id, "Delete IP Pool")) + { + $NSXTIPAMIPBlockService.delete($block_id) + } + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + } + } +} + # Non-working Set Functions Function Set-NSXTTraceFlow { <# @@ -1475,6 +1675,7 @@ Function Set-NSXTIPPool { # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$display_name, [parameter(Mandatory=$false)] @@ -1484,12 +1685,15 @@ Function Set-NSXTIPPool { [string]$dns_nameservers, [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$allocation_start, [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$allocation_end, [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$cidr, [parameter(Mandatory=$false)] @@ -1534,25 +1738,22 @@ Function Set-NSXTIPPool { [string]$description [string]$resource_type = 'IpPool' [long]$revision = '0' - #$subnets = [subnets]::new() - $subnets = [System.Collections.Generic.List[subnets]]::new() + $subnets = [subnets]::new() hidden $pool_usage hidden $tags hidden $self - hidden $links = [System.Collections.Generic.List[System.Management.Automation.PSObject]]::new() + hidden $links = [System.Collections.Generic.List[string]]::new() } } Process { - $ip_pool = [ip_pool]::new() $ip_pool = $NSXTIPPoolService.help.create.ip_pool.Create() $ip_pool.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Create() $ip_pool.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create() $ip_pool.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create() $ip_pool.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create() - #$ip_pool = [ip_pool]::new() $ip_pool.display_name = $display_name $ip_pool.description = $description @@ -1563,6 +1764,9 @@ Function Set-NSXTIPPool { $ip_pool.subnets.cidr = $cidr $ip_pool.subnets.gateway_ip = $gateway_ip $ip_pool.revision = 0 + + # Accepted JSON object ok yet it did not interpret any of the parameters + #$ip_pool_json = ConvertTo-Json $ip_pool try { @@ -1576,7 +1780,7 @@ Function Set-NSXTIPPool { catch { $Error[0].Exception.ServerError.data - # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file; grep POOL-MGMT throw } @@ -1584,6 +1788,8 @@ Function Set-NSXTIPPool { } } +########################### + # Get Template Function Get-NSXTThingTemplate { <# @@ -1678,9 +1884,11 @@ Function Set-NSXTThingTemplate { [string]$description, [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$display_name, [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$transport_zone_id, [parameter(Mandatory=$true)] @@ -1692,6 +1900,7 @@ Function Set-NSXTThingTemplate { [string]$replication_mode, [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] [string]$ip_pool_id ) @@ -1744,6 +1953,64 @@ Function Set-NSXTThingTemplate { } } - +# Remove Template +Function Remove-NSXTThingTemplate { + <# + .Synopsis + Removes an IPAM IP Block + .DESCRIPTION + Removes a IPAM IP Block with a block_id parameter. + .EXAMPLE + Remove-NSXTIPAMIPBlock -block_id "id" +#> + + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='High')] + + Param ( + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [ValidateNotNullOrEmpty()] + [Alias("Id")] + [string]$thing_id + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTTHINGkService = Get-NsxtService -Name "com.vmware.nsx.THING" + } + + Process + { + try + { + # Should process + if ($pscmdlet.ShouldProcess($thing_id, "Delete IP Pool")) + { + $NSXTTHINGkService.delete($thing_id) + } + } + + catch + { + throw $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file. + } + } +} + +$NSXTIPSubnetsService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_subnets" From 526f6a8ad902d99e334ccb869372d8475bf79f4c Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 18 Sep 2018 14:47:36 -0700 Subject: [PATCH 021/175] Check $global:DefaultVMCServers.IsConnected during NSX-T Proxy Connect --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 72f5ebc..126cad5 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -24,7 +24,7 @@ Function Connect-NSXTProxy { [Parameter(Mandatory=$true)][String]$SDDCName ) - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; exit } Else { + If (-Not $global:DefaultVMCServers.IsConnected) { Write-error "No valid VMC Connection found, please use the Connect-VMC to connect"; break } Else { $sddcService = Get-VmcService "com.vmware.vmc.orgs.sddcs" $orgId = (Get-VMCOrg -Name $OrgName).Id $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id From 16b32f1b03dd96c96a7091d7cb104a2355f4272b Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 19 Sep 2018 05:34:20 -0700 Subject: [PATCH 022/175] Additional NSX-T Policy API functions --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 766 ++++++++++++++++++- 2 files changed, 762 insertions(+), 6 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index 0e68563..c7feb19 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 126cad5..09b6b4d 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -81,7 +81,7 @@ Function Get-NSXTSegment { [Switch]$Troubleshoot ) - If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { $method = "GET" $segmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments" @@ -89,10 +89,15 @@ Function Get-NSXTSegment { Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$segmentsURL`n" } - if($PSVersionTable.PSEdition -eq "Core") { - $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck - } else { - $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break } if($requests.StatusCode -eq 200) { @@ -124,4 +129,755 @@ Function Get-NSXTSegment { Write-Error "Failed to retrieve NSX-T Segments" } } +} + +Function New-NSXTSegment { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a new NSX-T Segment (Logical Networks) + .DESCRIPTION + This cmdlet creates a new NSX-T Segment (Logical Networks) + .EXAMPLE + New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1" -Prefix "24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Parameter(Mandatory=$True)]$Gateway, + [Parameter(Mandatory=$True)]$Prefix, + [Parameter(Mandatory=$False)]$DHCPRange, + [Switch]$DHCP, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + if($DHCP) { + $dhcpConf = @($DHCPRange) + } else { + $dhcpConf = @($null) + } + + $subnets = @{ + gateway_addresses = @($gateway); + prefix_len = $Prefix; + dhcp_ranges = $dhcpConf + } + + $payload = @{ + display_name = $Name; + subnets = @($subnets) + } + $body = $payload | ConvertTo-Json -depth 4 + + $method = "PUT" + $newSegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments/$Name" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newSegmentsURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $newSegmentsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $newSegmentsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully created new NSX-T Segment $Name" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } else { + Write-Error "Failed to create new NSX-T Segment" + + } + } +} + +Function Remove-NSXTSegment { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes an NSX-T Segment (Logical Networks) + .DESCRIPTION + This cmdlet removes an NSX-T Segment (Logical Networks) + .EXAMPLE + Remove-NSXTSegment -Id "sddc-cgw-network-4" +#> + Param ( + [Parameter(Mandatory=$True)]$Id, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "DELETE" + $deleteSegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments/$Id" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteSegmentsURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteSegmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteSegmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully removed NSX-T Segment $Name" + } else { + Write-Error "Failed to remove NSX-T Segments" + + } + } +} + +Function Get-NSXTFirewall { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Firewall Rules on MGW or CGW + .DESCRIPTION + This cmdlet retrieves all NSX-T Firewall Rules on MGW or CGW + .EXAMPLE + Get-NSXTFirewall -GatewayType MGW + .EXAMPLE + Get-NSXTFirewall -GatewayType MGW -Name "Test" +#> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $edgeFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/edge-communication-maps/default" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$edgeFirewallURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $edgeFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $edgeFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + $rules = ($requests.Content | ConvertFrom-Json).communication_entries + + if ($PSBoundParameters.ContainsKey("Name")){ + $rules = $rules | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($rule in $rules | Sort-Object -Property sequence_number) { + $sourceGroups = $rule.source_groups + $source = @() + foreach ($sourceGroup in $sourceGroups) { + if($sourceGroup -eq "ANY") { + $source += $sourceGroup + break + } else { + $sourceGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $sourceGroup + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$sourceGroupURL`n" + } + try { + $requests = Invoke-WebRequest -Uri $sourceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + $group = ($requests.Content | ConvertFrom-Json) + $source += $group.display_name + } + } + + $destinationGroups = $rule.destination_groups + $destination = @() + foreach ($destinationGroup in $destinationGroups) { + if($destinationGroup -eq "ANY") { + $destination += $destinationGroup + break + } else { + $destionationGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $destinationGroup + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$destionationGroupURL`n" + } + try { + $requests = Invoke-WebRequest -Uri $destionationGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + $group = ($requests.Content | ConvertFrom-Json) + $destination += $group.display_name + } + } + + $serviceGroups = $rule.services + $service = @() + foreach ($serviceGroup in $serviceGroups) { + if($serviceGroup -eq "ANY") { + $service += $serviceGroup + break + } else { + $serviceGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $serviceGroup + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$serviceGroupURL`n" + } + try { + $requests = Invoke-WebRequest -Uri $serviceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + $group = ($requests.Content | ConvertFrom-Json) + $service += $group.display_name + } + } + + $tmp = [pscustomobject] @{ + SequenceNumber = $rule.sequence_number; + Name = $rule.display_name; + ID = $rule.id; + Source = $source; + Destination = $destination; + Services = $service; + Action = $rule.action; + } + $results+=$tmp + } + $results + + } else { + Write-Error "Failed to retrieve NSX-T Firewall Rules" + } + } +} + +Function New-NSXTFirewall { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a new NSX-T Firewall Rule on MGW or CGW + .DESCRIPTION + This cmdlet creates a new NSX-T Firewall Rule on MGW or CGW + .EXAMPLE + New-NSXTFirewall -GatewayType MGW -Name TEST -Id TEST -SourceGroupId ESXI -DestinationGroupId ANY -Service ANY -Logged $true -SequenceNumber 7 -Action ALLOW +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Parameter(Mandatory=$True)]$Id, + [Parameter(Mandatory=$True)]$SequenceNumber, + [Parameter(Mandatory=$True)]$SourceGroupId, + [Parameter(Mandatory=$True)]$DestinationGroupId, + [Parameter(Mandatory=$True)]$Service, + [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, + [Parameter(Mandatory=$false)][Boolean]$Logged=$false, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + + if($DestinationGroupId -eq "ANY") { + $destinationGroups = $DestinationGroupId + } else { + $destinationGroups = "/infra/domains/$($GatewayType.toLower())/groups/$DestinationGroupId" + } + + $sourceGroups = @() + foreach ($group in $SourceGroupId) { + $tmp = "/infra/domains/$($GatewayType.toLower())/groups/$group" + $sourceGroups+= $tmp + } + + $services = @() + foreach ($serviceName in $Service) { + if($serviceName -eq "ANY") { + $tmp = "ANY" + } else { + $tmp = "/infra/services/$serviceName" + } + $services+=$tmp + } + + $payload = @{ + display_name = $Name; + resource_type = "CommunicationEntry"; + id = $Id; + sequence_number = $SequenceNumber; + destination_groups = @($destinationGroups); + source_groups = $sourceGroups; + logged = $Logged; + scope = @("/infra/labels/$($GatewayType.toLower())"); + services = $services; + action = $Action; + } + + $body = $payload | ConvertTo-Json -depth 5 + + $method = "PUT" + $newFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/edge-communication-maps/default/communication-entries/$Id" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newFirewallURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $newFirewallURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $newFirewallURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully created new NSX-T Firewall Rule $Name" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } else { + Write-Error "Failed to create new NSX-T Firewall Rule" + } + } +} + +Function Remove-NSXTFirewall { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes an NSX-T Firewall Rule on MGW or CGW + .DESCRIPTION + This cmdlet removes an NSX-T Firewall Rule on MGW or CGW + .EXAMPLE + Remove-NSXTFirewall -Id TEST -GatewayType MGW -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Id, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "DELETE" + $deleteGgroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/edge-communication-maps/default/communication-entries/$Id" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteGgroupURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteGgroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteGgroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully removed NSX-T Firewall Rule $Name" + } else { + Write-Error "Failed to create new NSX-T Firewall Rule" + } + } +} + +Function Get-NSXTGroup { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Groups for MGW or CGW + .DESCRIPTION + This cmdlet retrieves all NSX-T Groups for MGW or CGW + .EXAMPLE + Get-NSXTGroup -GatewayType MGW + .EXAMPLE + Get-NSXTGroup -GatewayType MGW -Name "Test" +#> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $edgeFirewallGroupsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/groups" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$edgeFirewallGroupsURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $edgeFirewallGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $edgeFirewallGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + $groups = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $groups = $groups | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($group in $groups) { + if($group.tags.tag -eq $null) { + $groupType = "USER_DEFINED" + } else { $groupType = $group.tags.tag } + + $members = @() + foreach ($member in $group.expression) { + $members += $member.ip_addresses + } + + $tmp = [pscustomobject] @{ + Name = $group.display_name; + ID = $group.id; + Type = $groupType; + Members = $members; + } + $results+=$tmp + } + $results + } else { + Write-Error "Failed to retrieve NSX-T Groups" + } + } +} + +Function New-NSXTGroup { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a new NSX-T Group on MGW or CGW + .DESCRIPTION + This cmdlet creates a new NSX-T Firewall Rule on MGW or CGW + .EXAMPLE + New-NSXTGroup -GatewayType MGW -Name Foo -IPAddress @("172.31.0.0/24") +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Parameter(Mandatory=$True)][String[]]$IPAddress, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $expression = @{ + resource_type = "IPAddressExpression"; + ip_addresses = $IPAddress; + } + + $payload = @{ + display_name = $Name; + expression = @($expression); + } + $body = $payload | ConvertTo-Json -depth 5 + + $method = "PUT" + $newGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/groups/$Name" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newGroupURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $newGroupURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $newGroupURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully created new NSX-T Group $Name" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } else { + Write-Error "Failed to create new NSX-T Group" + } + } +} + +Function Remove-NSXTGROUP { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes an NSX-T Group + .DESCRIPTION + This cmdlet removes an NSX-T Group + .EXAMPLE + Remove-NSXTGROUP -Id Foo -GatewayType MGW -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Id, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "DELETE" + $deleteGgroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/groups/$Id" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteGgroupURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteGgroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteGgroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully removed NSX-T Group $Name" + } else { + Write-Error "Failed to create new NSX-T Group" + } + } +} + +Function Get-NSXTService { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Services + .DESCRIPTION + This cmdlet retrieves all NSX-T Services + .EXAMPLE + Get-NSXTService + .EXAMPLE + Get-NSXTService -Name "WINS" +#> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $serviceGroupsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/services" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$serviceGroupsURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $serviceGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $serviceGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + $services = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $services = $services | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($service in $services | Sort-Object -Propert display_name) { + $serviceEntry = $service.service_entries + $serviceProtocol = $serviceEntry.l4_protocol + $serviceSourcePorts = $serviceEntry.source_ports + $serviceDestinationPorts = $serviceEntry.destination_ports + + $tmp = [pscustomobject] @{ + Name = $service.display_name; + Id = $service.id; + Protocol = $serviceProtocol; + Source = $serviceSourcePorts; + Destination = $serviceDestinationPorts; + } + $results += $tmp + } + $results + } else { + Write-Error "Failed to retrieve NSX-T Services" + } + } +} + +Function New-NSXTService { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a new NSX-T Service + .DESCRIPTION + This cmdlet creates a new NSX-T Service + .EXAMPLE + New-NSXTService -Name "MyHTTP2" -Protocol TCP -DestinationPorts @("8080","8081") +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Parameter(Mandatory=$True)][String[]]$DestinationPorts, + [Parameter(Mandatory=$True)][ValidateSet("TCP","UDP")][String]$Protocol, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $serviceEntry = @() + $entry = @{ + display_name = $name + "-$destinationPort" + resource_type = "L4PortSetServiceEntry"; + destination_ports = @($DestinationPorts); + l4_protocol = $Protocol; + } + $serviceEntry+=$entry + + $payload = @{ + display_name = $Name; + service_entries = $serviceEntry; + } + $body = $payload | ConvertTo-Json -depth 5 + + $method = "PUT" + $newServiceURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/services/$Name" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newServiceURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $newServiceURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $newServiceURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully created new NSX-T Service $Name" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } else { + Write-Error "Failed to create new NSX-T Service" + } + } } \ No newline at end of file From 691709dd40d1f8b0c33bd78adcd6d6d9618f7732 Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 19 Sep 2018 05:34:54 -0700 Subject: [PATCH 023/175] Initial commit for HCX PowerShell Module --- Modules/VMware.HCX/VMware.HCX.psd1 | 88 +++++++++++++++ Modules/VMware.HCX/VMware.HCX.psm1 | 176 +++++++++++++++++++++++++++++ 2 files changed, 264 insertions(+) create mode 100644 Modules/VMware.HCX/VMware.HCX.psd1 create mode 100644 Modules/VMware.HCX/VMware.HCX.psm1 diff --git a/Modules/VMware.HCX/VMware.HCX.psd1 b/Modules/VMware.HCX/VMware.HCX.psd1 new file mode 100644 index 0000000..de1f200 --- /dev/null +++ b/Modules/VMware.HCX/VMware.HCX.psd1 @@ -0,0 +1,88 @@ +# +# Module manifest for module 'VMware.HCX' +# +# Generated by: wlam@vmware.com +# +# Generated on: 09/11/18 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'VMware.HCX.psm1' + +# Version number of this module. +ModuleVersion = '1.0.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = '88898ed6-26e8-4dfa-a9de-10d3a12571de' + +# Author of this module +Author = 'William Lam' + +# Company or vendor of this module +CompanyName = 'VMware' + +# Copyright statement for this module +Copyright = '(c) 2018 VMware. All rights reserved.' + +# Description of the functionality provided by this module +Description = 'PowerShell Module for Managing Hybrid Cloud Extension (HCX) on VMware Cloud on AWS' + +# Minimum version of the Windows PowerShell engine required by this module +PowerShellVersion = '6.0' + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Connect-HcxVAMI', 'Get-HcxVAMIVCConfig' +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() + +# Variables to export from this module +VariablesToExport = '*' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} \ No newline at end of file diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 new file mode 100644 index 0000000..222f8d1 --- /dev/null +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -0,0 +1,176 @@ +Function Connect-HcxServer { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Connect to the HCX Enterprise Manager + .DESCRIPTION + This cmdlet connects to the HCX Enterprise Manager + .EXAMPLE + Connect-HcxServer -Server $HCXServer -Username $Username -Password $Password +#> + Param ( + [Parameter(Mandatory=$true)][String]$Server, + [Parameter(Mandatory=$true)][String]$Username, + [Parameter(Mandatory=$true)][String]$Password + ) + + $payload = @{ + "username" = $Username + "password" = $Password + } + $body = $payload | ConvertTo-Json + + $hcxLoginUrl = "https://$Server/hybridity/api/sessions" + + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $hcxLoginUrl -Body $body -Method POST -UseBasicParsing -ContentType "application/json" -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $hcxLoginUrl -Body $body -Method POST -UseBasicParsing -ContentType "application/json" + } + + if($results.StatusCode -eq 200) { + $hcxAuthToken = $results.Headers.'x-hm-authorization' + + $headers = @{ + "x-hm-authorization"="$hcxAuthToken" + "Content-Type"="application/json" + "Accept"="application/json" + } + + $global:hcxConnection = new-object PSObject -Property @{ + 'Server' = "https://$server/hybridity/api"; + 'headers' = $headers + } + $global:hcxConnection + } else { + Write-Error "Failed to connect to HCX Manager, please verify your vSphere SSO credentials" + } +} + +Function Get-HcxCloudConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the Cloud HCX information that is registerd with HCX Manager + .DESCRIPTION + This cmdlet returns the Cloud HCX information that is registerd with HCX Manager + .EXAMPLE + Get-HcxCloudConfig +#> + If (-Not $global:hcxConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxServer " } Else { + $cloudConfigUrl = $global:hcxConnection.Server + "/cloudConfigs" + + if($PSVersionTable.PSEdition -eq "Core") { + $cloudvcRequests = Invoke-WebRequest -Uri $cloudConfigUrl -Method GET -Headers $global:hcxConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $cloudvcRequests = Invoke-WebRequest -Uri $cloudConfigUrl -Method GET -Headers $global:hcxConnection.headers -UseBasicParsing + } + + $cloudvcData = ($cloudvcRequests.content | ConvertFrom-Json).data.items + + $tmp = [pscustomobject] @{ + Name = $cloudvcData.cloudName; + Version = $cloudvcData.version; + Build = $cloudvcData.buildNumber; + HCXUUID = $cloudvcData.endpointId; + } + $tmp + } +} + +Function Connect-HcxVAMI { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Connect to the HCX Enterprise Manager VAMI + .DESCRIPTION + This cmdlet connects to the HCX Enterprise Manager VAMI + .EXAMPLE + Connect-HcxVAMI -Server $HCXServer -Username $VAMIUsername -Password $VAMIPassword +#> + Param ( + [Parameter(Mandatory=$true)][String]$Server, + [Parameter(Mandatory=$true)][String]$Username, + [Parameter(Mandatory=$true)][String]$Password + ) + + $pair = "${Username}:${Password}" + $bytes = [System.Text.Encoding]::ASCII.GetBytes($pair) + $base64 = [System.Convert]::ToBase64String($bytes) + $basicAuthValue = "Basic $base64" + + $headers = @{ + "authorization"="$basicAuthValue" + "Content-Type"="application/json" + "Accept"="application/json" + } + + $global:hcxVAMIConnection = new-object PSObject -Property @{ + 'Server' = "https://${server}:9443"; + 'headers' = $headers + } + $global:hcxVAMIConnection +} + +Function Get-HcxVAMIVCConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the onPrem vCenter Server registered with HCX Manager + .DESCRIPTION + This cmdlet returns the onPrem vCenter Server registered with HCX Manager + .EXAMPLE + Get-HcxVAMIVCConfig +#> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $vcConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/vcenter" + + if($PSVersionTable.PSEdition -eq "Core") { + $vcRequests = Invoke-WebRequest -Uri $vcConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $vcRequests = Invoke-WebRequest -Uri $vcConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + $vcData = ($vcRequests.content | ConvertFrom-Json).data.items + + $tmp = [pscustomobject] @{ + Name = $vcData.config.name; + Version = $vcData.config.version; + Build = $vcData.config.buildNumber; + UUID = $vcData.config.vcuuid; + HCXUUID = $vcData.config.uuid; + } + $tmp + } +} \ No newline at end of file From 39c179ae1a2b114d81545bb15794f09824812d2a Mon Sep 17 00:00:00 2001 From: AndyG Date: Wed, 19 Sep 2018 15:01:25 -0500 Subject: [PATCH 024/175] Added Get-NSXTClusterNode Added Get-NSXTClusterNode --- Modules/NSXT/NSXT.psd1 | 2 + Modules/NSXT/NSXT.psm1 | 160 ++++++++++++++++++++++++++++++++--------- 2 files changed, 129 insertions(+), 33 deletions(-) diff --git a/Modules/NSXT/NSXT.psd1 b/Modules/NSXT/NSXT.psd1 index 83026e8..3cee460 100644 --- a/Modules/NSXT/NSXT.psd1 +++ b/Modules/NSXT/NSXT.psd1 @@ -26,6 +26,7 @@ 'Get-NSXTTraceFlowObservations', 'Get-NSXTTransportNode', 'Get-NSXTTransportZone', + 'Get-NSXTClusterNode', 'Set-NSXTIPPool', 'Set-NSXTLogicalRouter', 'Set-NSXTLogicalSwitch', @@ -33,6 +34,7 @@ 'Get-NSXTIPAMIPBlock', 'Set-NSXTIPAMIPBlock', 'Remove-NSXTIPAMIPBlock' + PrivateData = @{ PSData = @{ diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 3d6a4f7..99e149b 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -1172,6 +1172,84 @@ Function Get-NSXTIPAMIPBlock { } } +Function Get-NSXTClusterNode { + <# + .Synopsis + Retrieves the cluster node information + .DESCRIPTION + Retrieves cluster node information including manager and controller nodes. + .EXAMPLE + Get-NSXTClusterNode + .EXAMPLE + Get-NSXTClusterNode -node_id "Node Id" + .EXAMPLE + Get-NSXTClusterNode -name "Name" +#> + + Param ( + [parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)] + [Alias("Id")] + [string]$node_id, + [parameter(Mandatory=$false)] + [string]$name + ) + + begin + { + $NSXTClusterNodesService = Get-NsxtService -Name "com.vmware.nsx.cluster.nodes" + + class NSXTClusterNode { + [string]$Name + [string]$node_id + hidden [array]$Tags = [System.Collections.Generic.List[string]]::new() + hidden [string]$controller_role + hidden [array]$manager_role + [string]$protection + [string]$appliance_mgmt_listen_addr + hidden [string]$external_id + hidden [string]$description + [string]$role + } + } + + Process + { + if($node_id) { + $NSXTThings = $NSXTClusterNodesService.get($node_id) + } else { + if ($name) { + $NSXTClusterNodes = $NSXTClusterNodesService.list().results | where {$_.display_name -eq $name} + } + else { + $NSXTClusterNodes = $NSXTClusterNodesService.list().results + } + } + + foreach ($NSXTClusterNode in $NSXTClusterNodes) { + + $results = [NSXTClusterNode]::new() + $results.Name = $NSXTClusterNode.display_name; + $results.node_id = $NSXTClusterNode.Id; + $results.Tags = $NSXTClusterNode.tags; + $results.controller_role = $NSXTClusterNode.controller_role; + $results.manager_role = $NSXTClusterNode.manager_role; + $results.protection = $NSXTClusterNode.protection; + $results.appliance_mgmt_listen_addr = $NSXTClusterNode.appliance_mgmt_listen_addr; + $results.external_id = $NSXTClusterNode.external_id; + $results.description = $NSXTClusterNode.description + + if ($NSXTClusterNode.manager_role -ne $null) { + $results.role = "Manager" + } + elseif ($NSXTClusterNode.controller_role -ne $null) { + $results.role = "Controller" + } + + $results + } + } +} + # Working Set Functions Function Set-NSXTLogicalRouter { <# @@ -1453,11 +1531,11 @@ Function Remove-NSXTIPAMIPBlock { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] - Param ( - [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] - [ValidateNotNullOrEmpty()] - [Alias("Id")] - [string]$block_id + Param ( + [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] + [ValidateNotNullOrEmpty()] + [Alias("Id")] + [string]$block_id ) Begin @@ -1664,13 +1742,13 @@ Function Set-NSXTIPPool { .DESCRIPTION Creates a IP Pool with a number of required parameters. Supported IP formats include 192.168.1.1, 192.168.1.1-192.168.1.100, 192.168.0.0/24 .EXAMPLE - Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" + Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.2" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" .EXAMPLE - Set-NSXTIPPool -display_name "Test Pool Name" -allocation_start "192.168.1.1" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" + Set-NSXTIPPool -display_name "Test Pool Name" -allocation_start "192.168.1.2" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" -dns_suffix "evil corp" #> [CmdletBinding(SupportsShouldProcess=$true, - ConfirmImpact='Medium')] + ConfirmImpact='High')] # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types Param ( @@ -1684,6 +1762,9 @@ Function Set-NSXTIPPool { [parameter(Mandatory=$false)] [string]$dns_nameservers, + [parameter(Mandatory=$false)] + [string]$dns_suffix, + [parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$allocation_start, @@ -1720,17 +1801,16 @@ Function Set-NSXTIPPool { class allocation_ranges { [string]$start [string]$end - $self + #$self } class subnets { - [string]$dns_nameservers + [array]$allocation_ranges = [allocation_ranges]::new() + [array]$dns_nameservers [string]$dns_suffix [string]$cidr [string]$gateway_ip - $allocation_ranges = [allocation_ranges]::new() - hidden $self - + #hidden $self } class ip_pool { @@ -1738,42 +1818,51 @@ Function Set-NSXTIPPool { [string]$description [string]$resource_type = 'IpPool' [long]$revision = '0' - $subnets = [subnets]::new() + [array]$subnets = [subnets]::new() hidden $pool_usage - hidden $tags - hidden $self - hidden $links = [System.Collections.Generic.List[string]]::new() + hidden [array]$tags + # hidden $self + hidden $links } - } Process { - $ip_pool = $NSXTIPPoolService.help.create.ip_pool.Create() - $ip_pool.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Create() - $ip_pool.subnets = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create() - $ip_pool.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create() - $ip_pool.subnets.allocation_ranges = $NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create() + $sample_ip_pool = $NSXTIPPoolService.help.create.ip_pool.Create() + $sample_ip_pool.subnets = @($NSXTIPPoolService.help.create.ip_pool.subnets.Create()) + $sample_ip_pool.subnets = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create()) + $sample_ip_pool.subnets[0].allocation_ranges = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create()) + $sample_ip_pool.subnets[0].allocation_ranges = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create()) + #Remove buggy self object + $ip_pool = $sample_ip_pool | select -Property * -ExcludeProperty self + $ip_pool.subnets[0] = $sample_ip_pool.subnets[0] | select -Property * -ExcludeProperty self + $ip_pool.subnets[0].allocation_ranges[0] = $sample_ip_pool.subnets[0].allocation_ranges[0] | select -Property * -ExcludeProperty self + + # Assign objects $ip_pool.display_name = $display_name $ip_pool.description = $description $ip_pool.resource_type = "IpPool" - $ip_pool.subnets.dns_nameservers = $dns_nameservers - $ip_pool.subnets.allocation_ranges.start = $allocation_start - $ip_pool.subnets.allocation_ranges.end = $allocation_end - $ip_pool.subnets.cidr = $cidr - $ip_pool.subnets.gateway_ip = $gateway_ip + $ip_pool.subnets[0].dns_nameservers = @($dns_nameservers) + $ip_pool.subnets[0].dns_suffix = $dns_suffix + $ip_pool.subnets[0].allocation_ranges[0].start = $allocation_start + $ip_pool.subnets[0].allocation_ranges[0].end = $allocation_end + $ip_pool.subnets[0].cidr = $cidr + $ip_pool.subnets[0].gateway_ip = $gateway_ip $ip_pool.revision = 0 + $ip_pool.tags = @() # Accepted JSON object ok yet it did not interpret any of the parameters - #$ip_pool_json = ConvertTo-Json $ip_pool + $ip_pool_json = ConvertTo-Json $ip_pool -Depth 10 try { # Should process if ($pscmdlet.ShouldProcess($ip_pool.display_name, "Create IP Pool")) { - $NSXTIPPool = $NSXTIPPoolService.create($ip_pool) + $ip_pool_json + #$NSXTIPPool = $NSXTIPPoolService.create($ip_pool_json) + $NSXTIPPoolService.create($ip_pool_json) } } @@ -1784,10 +1873,14 @@ Function Set-NSXTIPPool { throw } - $NSXTIPPool + #$NSXTIPPool } } +########################### +# # +# TEMPLATES!! # +# # ########################### # Get Template @@ -1934,6 +2027,8 @@ Function Set-NSXTThingTemplate { $logical_THING_request.replication_mode = $replication_mode $logical_THING_request.ip_pool_id = $ip_pool_id + $logical_THING_request_json = ConvertTo-Json $logical_THING_request -Depth 10 + try { # Should process @@ -1967,7 +2062,7 @@ Function Remove-NSXTThingTemplate { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] - Param ( + Param ( [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Id")] @@ -2011,6 +2106,5 @@ Function Remove-NSXTThingTemplate { } } -$NSXTIPSubnetsService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_subnets" From 179cfa82bee88f33e57927d30570f4104bfdf77a Mon Sep 17 00:00:00 2001 From: AndyG Date: Wed, 19 Sep 2018 21:35:23 -0500 Subject: [PATCH 025/175] Set-NSXTIPPool finally working Set-NSXTIPPool finally working --- Modules/NSXT/NSXT.psm1 | 275 ++++++++++++++++++++--------------------- 1 file changed, 135 insertions(+), 140 deletions(-) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 99e149b..3a0d270 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -1515,6 +1515,141 @@ Function Set-NSXTIPAMIPBlock { } } +Function Set-NSXTIPPool { + <# + .Synopsis + Creates an IP Pool + .DESCRIPTION + Creates a IP Pool with a number of required parameters. Supported IP formats include 192.168.1.1, 192.168.1.1-192.168.1.100, 192.168.0.0/24 + .EXAMPLE + Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.2" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" + .EXAMPLE + Set-NSXTIPPool -display_name "Test Pool Name" -allocation_start "192.168.1.2" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" -dns_suffix "evil corp" +#> + + [CmdletBinding(SupportsShouldProcess=$true, + ConfirmImpact='High')] + + # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types + Param ( + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$display_name, + + [parameter(Mandatory=$false)] + [string]$description, + + [parameter(Mandatory=$false)] + [string]$dns_nameservers, + + [parameter(Mandatory=$false)] + [string]$dns_suffix, + + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$allocation_start, + + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$allocation_end, + + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string]$cidr, + + [parameter(Mandatory=$false)] + [string]$gateway_ip + ) + + Begin + { + if (-not $global:DefaultNsxtServers.isconnected) + { + try + { + Connect-NsxtServer -Menu -ErrorAction Stop + } + + catch + { + throw "Could not connect to an NSX-T Manager, please try again" + } + } + + $NSXTIPPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" + + class allocation_ranges { + [string]$start + [string]$end + #$self + } + + class subnets { + [array]$allocation_ranges = [allocation_ranges]::new() + [array]$dns_nameservers + [string]$dns_suffix + [string]$cidr + [string]$gateway_ip + #hidden $self + } + + class ip_pool { + [string]$display_name + [string]$description + [string]$resource_type = 'IpPool' + [long]$revision = '0' + [array]$subnets = [subnets]::new() + hidden $pool_usage + hidden [array]$tags + # hidden $self + hidden $links + } + } + + Process + { + $sample_ip_pool = $NSXTIPPoolService.help.create.ip_pool.Create() + $sample_ip_pool.subnets = @($NSXTIPPoolService.help.create.ip_pool.subnets.Create()) + $sample_ip_pool.subnets = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create()) + $sample_ip_pool.subnets[0].allocation_ranges = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create()) + $sample_ip_pool.subnets[0].allocation_ranges = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create()) + + #Remove buggy self object + $ip_pool = $sample_ip_pool | select -Property * -ExcludeProperty self + $ip_pool.subnets[0] = $sample_ip_pool.subnets[0] | select -Property * -ExcludeProperty self + $ip_pool.subnets[0].allocation_ranges[0] = $sample_ip_pool.subnets[0].allocation_ranges[0] | select -Property * -ExcludeProperty self + + # Assign objects + $ip_pool.display_name = $display_name + $ip_pool.description = $description + $ip_pool.resource_type = "IpPool" + $ip_pool.subnets[0].dns_nameservers = @($dns_nameservers) + $ip_pool.subnets[0].dns_suffix = $dns_suffix + $ip_pool.subnets[0].allocation_ranges[0].start = $allocation_start + $ip_pool.subnets[0].allocation_ranges[0].end = $allocation_end + $ip_pool.subnets[0].cidr = $cidr + $ip_pool.subnets[0].gateway_ip = $gateway_ip + $ip_pool.revision = 0 + $ip_pool.tags = @() + + try + { + # Should process + if ($pscmdlet.ShouldProcess($ip_pool.display_name, "Create IP Pool")) + { + $NSXTIPPoolService.create($ip_pool) + } + } + + catch + { + $Error[0].Exception.ServerError.data + # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file; grep POOL-MGMT + throw + } + } +} + # Remove functions Function Remove-NSXTIPAMIPBlock { <# @@ -1735,147 +1870,7 @@ Function Set-NSXTTraceFlow { } } -Function Set-NSXTIPPool { - <# - .Synopsis - Creates an IP Pool - .DESCRIPTION - Creates a IP Pool with a number of required parameters. Supported IP formats include 192.168.1.1, 192.168.1.1-192.168.1.100, 192.168.0.0/24 - .EXAMPLE - Set-NSXTIPPool -display_name "Pool Name" -allocation_start "192.168.1.2" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" - .EXAMPLE - Set-NSXTIPPool -display_name "Test Pool Name" -allocation_start "192.168.1.2" -allocation_end "192.168.1.100" -cidr "192.168.1.0/24" -dns_nameservers "192.168.1.1" -gateway_ip "192.168.1.1" -dns_suffix "evil corp" -#> - [CmdletBinding(SupportsShouldProcess=$true, - ConfirmImpact='High')] - - # Paramameter Set variants will be needed Multicast & Broadcast Traffic Types as well as VM & Logical Port Types - Param ( - [parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$display_name, - - [parameter(Mandatory=$false)] - [string]$description, - - [parameter(Mandatory=$false)] - [string]$dns_nameservers, - - [parameter(Mandatory=$false)] - [string]$dns_suffix, - - [parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$allocation_start, - - [parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$allocation_end, - - [parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$cidr, - - [parameter(Mandatory=$false)] - [string]$gateway_ip - ) - - Begin - { - if (-not $global:DefaultNsxtServers.isconnected) - { - try - { - Connect-NsxtServer -Menu -ErrorAction Stop - } - - catch - { - throw "Could not connect to an NSX-T Manager, please try again" - } - } - - $NSXTIPPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" - - class allocation_ranges { - [string]$start - [string]$end - #$self - } - - class subnets { - [array]$allocation_ranges = [allocation_ranges]::new() - [array]$dns_nameservers - [string]$dns_suffix - [string]$cidr - [string]$gateway_ip - #hidden $self - } - - class ip_pool { - [string]$display_name - [string]$description - [string]$resource_type = 'IpPool' - [long]$revision = '0' - [array]$subnets = [subnets]::new() - hidden $pool_usage - hidden [array]$tags - # hidden $self - hidden $links - } - } - - Process - { - $sample_ip_pool = $NSXTIPPoolService.help.create.ip_pool.Create() - $sample_ip_pool.subnets = @($NSXTIPPoolService.help.create.ip_pool.subnets.Create()) - $sample_ip_pool.subnets = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.Create()) - $sample_ip_pool.subnets[0].allocation_ranges = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.create()) - $sample_ip_pool.subnets[0].allocation_ranges = @($NSXTIPPoolService.help.create.ip_pool.subnets.Element.allocation_ranges.element.create()) - - #Remove buggy self object - $ip_pool = $sample_ip_pool | select -Property * -ExcludeProperty self - $ip_pool.subnets[0] = $sample_ip_pool.subnets[0] | select -Property * -ExcludeProperty self - $ip_pool.subnets[0].allocation_ranges[0] = $sample_ip_pool.subnets[0].allocation_ranges[0] | select -Property * -ExcludeProperty self - - # Assign objects - $ip_pool.display_name = $display_name - $ip_pool.description = $description - $ip_pool.resource_type = "IpPool" - $ip_pool.subnets[0].dns_nameservers = @($dns_nameservers) - $ip_pool.subnets[0].dns_suffix = $dns_suffix - $ip_pool.subnets[0].allocation_ranges[0].start = $allocation_start - $ip_pool.subnets[0].allocation_ranges[0].end = $allocation_end - $ip_pool.subnets[0].cidr = $cidr - $ip_pool.subnets[0].gateway_ip = $gateway_ip - $ip_pool.revision = 0 - $ip_pool.tags = @() - - # Accepted JSON object ok yet it did not interpret any of the parameters - $ip_pool_json = ConvertTo-Json $ip_pool -Depth 10 - - try - { - # Should process - if ($pscmdlet.ShouldProcess($ip_pool.display_name, "Create IP Pool")) - { - $ip_pool_json - #$NSXTIPPool = $NSXTIPPoolService.create($ip_pool_json) - $NSXTIPPoolService.create($ip_pool_json) - } - } - - catch - { - $Error[0].Exception.ServerError.data - # more error data found in the NSX-T Manager /var/log/vmware/nsx-manager.log file; grep POOL-MGMT - throw - } - - #$NSXTIPPool - } -} ########################### # # From 3a022777d37e9dff6b2b9fdadc03567fcd650fb7 Mon Sep 17 00:00:00 2001 From: AndyG Date: Wed, 19 Sep 2018 22:06:01 -0500 Subject: [PATCH 026/175] Removed unnecessary JSON conversion in template Removed unnecessary JSON conversion in template --- Modules/NSXT/NSXT.psm1 | 2 -- 1 file changed, 2 deletions(-) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 3a0d270..6d52412 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -2022,8 +2022,6 @@ Function Set-NSXTThingTemplate { $logical_THING_request.replication_mode = $replication_mode $logical_THING_request.ip_pool_id = $ip_pool_id - $logical_THING_request_json = ConvertTo-Json $logical_THING_request -Depth 10 - try { # Should process From 5052044ae1c7cfd35c85be6d18eaf17a96733e81 Mon Sep 17 00:00:00 2001 From: AndyG Date: Wed, 19 Sep 2018 22:08:39 -0500 Subject: [PATCH 027/175] Added Comment to Set-NSXTIPPool Added Comment to Set-NSXTIPPool --- Modules/NSXT/NSXT.psm1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Modules/NSXT/NSXT.psm1 b/Modules/NSXT/NSXT.psm1 index 6d52412..4e135e8 100644 --- a/Modules/NSXT/NSXT.psm1 +++ b/Modules/NSXT/NSXT.psm1 @@ -1577,7 +1577,8 @@ Function Set-NSXTIPPool { } $NSXTIPPoolService = Get-NsxtService -Name "com.vmware.nsx.pools.ip_pools" - + + # Classes unused - part of early testing class allocation_ranges { [string]$start [string]$end From a1c3c01f05f59ebf33f02fa20e9f6b23bdd49247 Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 20 Sep 2018 04:56:43 -0700 Subject: [PATCH 028/175] Added NSX-T Policy Firewall cmdlets --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index c7feb19..9eca367 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() From 8402e6999384464c94b3fefa4ff1c5ca6f1d8243 Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 20 Sep 2018 05:04:18 -0700 Subject: [PATCH 029/175] Fixed caps --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 09b6b4d..b87d788 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -688,7 +688,7 @@ Function New-NSXTGroup { } } -Function Remove-NSXTGROUP { +Function Remove-NSXTGroup { <# .NOTES =========================================================================== @@ -704,7 +704,7 @@ Function Remove-NSXTGROUP { .DESCRIPTION This cmdlet removes an NSX-T Group .EXAMPLE - Remove-NSXTGROUP -Id Foo -GatewayType MGW -Troubleshoot + Remove-NSXTGroup -Id Foo -GatewayType MGW -Troubleshoot #> Param ( [Parameter(Mandatory=$True)]$Id, From ea4ab5f61d806f80925f06dcf5cf660944a01afb Mon Sep 17 00:00:00 2001 From: William Lam Date: Mon, 24 Sep 2018 14:17:39 -0700 Subject: [PATCH 030/175] Updated function to support Cloud Motion & other HCX Migrations --- Modules/VMware.HCX/VMware.HCX.psd1 | 4 +- Modules/VMware.HCX/VMware.HCX.psm1 | 407 ++++++++++++++++++++++++++++- 2 files changed, 407 insertions(+), 4 deletions(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psd1 b/Modules/VMware.HCX/VMware.HCX.psd1 index de1f200..cd957ac 100644 --- a/Modules/VMware.HCX/VMware.HCX.psd1 +++ b/Modules/VMware.HCX/VMware.HCX.psd1 @@ -12,7 +12,7 @@ RootModule = 'VMware.HCX.psm1' # Version number of this module. -ModuleVersion = '1.0.0' +ModuleVersion = '1.0.1' # Supported PSEditions # CompatiblePSEditions = @() @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing Hybrid Cloud Extension (HCX) on VM PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Connect-HcxVAMI', 'Get-HcxVAMIVCConfig' +FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index 222f8d1..c066f87 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -94,6 +94,409 @@ Function Get-HcxCloudConfig { } } +Function Get-HcxEndpoint { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/24/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + List all HCX endpoints (onPrem and Cloud) + .DESCRIPTION + This cmdlet lists all HCX endpoints (onPrem and Cloud) + .EXAMPLE + Get-HcxEndpoint -cloudVCConnection $cloudVCConnection +#> + Param ( + [Parameter(Mandatory=$true)]$cloudVCConnection + ) + + If (-Not $global:hcxConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxManager " } Else { + #Cloud HCX Manager + $cloudHCXConnectionURL = $global:hcxConnection.Server + "/cloudConfigs" + + if($PSVersionTable.PSEdition -eq "Core") { + $cloudRequests = Invoke-WebRequest -Uri $cloudHCXConnectionURL -Method GET -Headers $global:hcxConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $cloudRequests = Invoke-WebRequest -Uri $cloudHCXConnectionURL -Method GET -Headers $global:hcxConnection.headers -UseBasicParsing + } + $cloudData = ($cloudRequests.Content | ConvertFrom-Json).data.items[0] + + $hcxInventoryUrl = $global:hcxConnection.Server + "/service/inventory/resourcecontainer/list" + + $payload = @{ + "cloud" = @{ + "local"="true"; + "remote"="true"; + } + } + $body = $payload | ConvertTo-Json + + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $hcxInventoryUrl -Body $body -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $hcxInventoryUrl -Body $body -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing + } + if($requests.StatusCode -eq 200) { + $items = ($requests.Content | ConvertFrom-Json).data.items + + $results = @() + foreach ($item in $items) { + $tmp = [pscustomobject] @{ + SourceResourceName = $item.resourceName; + SourceResourceType = $item.resourceType; + SourceResourceId = $item.resourceId; + SourceEndpointName = $item.endpoint.name; + SourceEndpointType = "VC" + SourceEndpointId = $item.endpoint.endpointId; + RemoteResourceName = $cloudVCConnection.name; + RemoteResourceType = "VC" + RemoteResourceId = $cloudVCConnection.InstanceUuid + RemoteEndpointName = $cloudData.cloudName; + RemoteEndpointType = $cloudData.cloudType; + RemoteEndpointId = $cloudData.endpointId; + } + $results+=$tmp + } + return $results + } else { + Write-Error "Failed to list HCX Connection Resources" + } + } +} + +Function New-HcxMigration { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/24/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Initiate a "Bulk" migrations supporting Cold, vMotion, VR or new Cloud Motion + .DESCRIPTION + This cmdlet initiates a "Bulk" migrations supporting Cold, vMotion, VR or new Cloud Motionn + .EXAMPLE + Validate Migration request only + + New-HcxMigration -onPremVCConnection $onPremVC -cloudVCConnection $cloudVC ` + -MigrationType bulkVMotion ` + -VMs @("SJC-CNA-34","SJC-CNA-35","SJC-CNA-36") ` + -NetworkMappings @{"SJC-CORP-WORKLOADS"="sddc-cgw-network-1";"SJC-CORP-INTERNAL-1"="sddc-cgw-network-2";"SJC-CORP-INTERNAL-2"="sddc-cgw-network-3"} ` + -StartTime "Sep 24 2018 1:30 PM" ` + -EndTime "Sep 24 2018 2:30 PM" + .EXAMPLE + Start Migration request + + New-HcxMigration -onPremVCConnection $onPremVC -cloudVCConnection $cloudVC ` + -MigrationType bulkVMotion ` + -VMs @("SJC-CNA-34","SJC-CNA-35","SJC-CNA-36") ` + -NetworkMappings @{"SJC-CORP-WORKLOADS"="sddc-cgw-network-1";"SJC-CORP-INTERNAL-1"="sddc-cgw-network-2";"SJC-CORP-INTERNAL-2"="sddc-cgw-network-3"} ` + -StartTime "Sep 24 2018 1:30 PM" ` + -EndTime "Sep 24 2018 2:30 PM" ` + -MigrationType bulkVMotion +#> + Param ( + [Parameter(Mandatory=$true)][String[]]$VMs, + [Parameter(Mandatory=$true)][Hashtable]$NetworkMappings, + [Parameter(Mandatory=$true)]$onPremVCConnection, + [Parameter(Mandatory=$true)]$cloudVCConnection, + [Parameter(Mandatory=$true)][String]$StartTime, + [Parameter(Mandatory=$true)][String]$EndTime, + [Parameter(Mandatory=$true)][ValidateSet("Cold","vMotion","VR","bulkVMotion")][String]$MigrationType, + [Parameter(Mandatory=$false)]$ValidateOnly=$true + ) + + If (-Not $global:hcxConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxManager " } Else { + $hcxEndpointInfo = Get-HcxEndpoint -cloudVCConnection $cloudVCConnection + + $inputArray = @() + foreach ($vm in $VMs) { + $vmView = Get-View -Server $onPremVCConnection -ViewType VirtualMachine -Filter @{"name"=$vm} + + $cloudResourcePoolName = "Compute-ResourcePool" + $cloudFolderName = "Workloads" + $cloudDatastoreName = "WorkloadDatastore" + $cloudDatacenterName = "SDDC-Datacenter" + + $cloudResourcePool = (Get-ResourcePool -Server $cloudVCConnection -Name $cloudResourcePoolName).ExtensionData + $cloudFolder = (Get-Folder -Server $cloudVCConnection -Name $cloudFolderName).ExtensionData + $cloudDatastore = (Get-Datastore -Server $cloudVCConnection -Name $cloudDatastoreName).ExtensionData + $cloudDatacenter = (Get-Datacenter -Server $cloudVCConnection -Name $cloudDatacenterName).ExtensionData + + $placementArray = @() + $placement = @{ + "containerType"="folder"; + "containerId"=$cloudFolder.MoRef.Value; + "containerName"=$cloudFolderName; + } + $placementArray+=$placement + $placement = @{ + "containerType"="resourcePool"; + "containerId"=$cloudResourcePool.MoRef.Value; + "containerName"=$cloudResourcePoolName; + } + $placementArray+=$placement + $placement = @{ + "containerType"="dataCenter"; + "containerId"=$cloudDatacenter.MoRef.Value; + "containerName"=$cloudDatacenterName; + } + $placementArray+=$placement + + $networkArray = @() + $vmNetworks = $vmView.Network + foreach ($vmNetwork in $vmNetworks) { + if($vmNetwork.Type -eq "Network") { + $sourceNetworkType = "VirtualNetwork" + } else { $sourceNetworkType = $vmNetwork.Type } + + $sourceNetworkRef = New-Object VMware.Vim.ManagedObjectReference + $sourceNetworkRef.Type = $vmNetwork.Type + $sourceNetworkRef.Value = $vmNetwork.Value + $sourceNetwork = Get-View -Server $onPremVCConnection $sourceNetworkRef + + $sourceNetworkName = $sourceNetwork.Name + $destNetworkName = $NetworkMappings[$sourceNetworkName] + + $destNetwork = Get-VDPortGroup -Server $cloudVCConnection -Name $destNetworkName + + if($destNetwork.Id -match "DistributedVirtualPortgroup") { + $destNetworkType = "DistributedVirtualPortgroup" + $destNetworkId = ($destNetwork.Id).Replace("DistributedVirtualPortgroup-","") + } else { + $destNetworkType = "Network" + $destNetworkId = ($destNetwork.Id).Replace("Network-","") + } + + $tmp = @{ + "srcNetworkType" = $sourceNetworkType; + "srcNetworkValue" = $vmNetwork.Value; + "srcNetworkHref" = $vmNetwork.Value; + "srcNetworkName" = $sourceNetworkName; + "destNetworkType" = $destNetworkType; + "destNetworkValue" = $destNetworkId; + "destNetworkHref" = $destNetworkId; + "destNetworkName" = $destNetworkName; + } + $networkArray+=$tmp + } + + $input = @{ + "input" = @{ + "migrationType"=$MigrationType; + "entityDetails" = @{ + "entityId"=$vmView.MoRef.Value; + "entityName"=$vm; + } + "source" = @{ + "endpointType"=$hcxEndpointInfo.SourceEndpointType; + "endpointId"=$hcxEndpointInfo.SourceEndpointId; + "endpointName"=$hcxEndpointInfo.SourceEndpointName; + "resourceType"=$hcxEndpointInfo.SourceResourceType; + "resourceId"=$hcxEndpointInfo.SourceResourceId; + "resourceName"=$hcxEndpointInfo.SourceResourceName; + } + "destination" = @{ + "endpointType"=$hcxEndpointInfo.RemoteEndpointType; + "endpointId"=$hcxEndpointInfo.RemoteEndpointId; + "endpointName"=$hcxEndpointInfo.RemoteEndpointName; + "resourceType"=$hcxEndpointInfo.RemoteResourceType; + "resourceId"=$hcxEndpointInfo.RemoteResourceId; + "resourceName"=$hcxEndpointInfo.RemoteResourceName; + } + "placement" = $placementArray + "storage" = @{ + "datastoreId"=$cloudDatastore.Moref.Value; + "datastoreName"=$cloudDatastoreName; + "diskProvisionType"="thin"; + } + "networks" = @{ + "retainMac" = $true; + "targetNetworks" = $networkArray; + } + "decisionRules" = @{ + "removeSnapshots"=$true; + "removeISOs"=$true; + "forcePowerOffVm"=$false; + "upgradeHardware"=$false; + "upgradeVMTools"=$false; + } + "schedule" = @{} + } + } + $inputArray+=$input + } + + $spec = @{ + "migrations"=$inputArray + } + $body = $spec | ConvertTo-Json -Depth 20 + + Write-Verbose -Message "Pre-Validation JSON Spec: $body" + $hcxMigrationValiateUrl = $global:hcxConnection.Server+ "/migrations?action=validate" + + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $hcxMigrationValiateUrl -Body $body -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing -ContentType "application/json" -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $hcxMigrationValiateUrl -Body $body -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing -ContentType "application/json" + } + + if($requests.StatusCode -eq 200) { + $validationErrors = ($requests.Content|ConvertFrom-Json).migrations.validationInfo.validationResult.errors + if($validationErrors -ne $null) { + Write-Host -Foreground Red "`nThere were validation errors found for this HCX Migration Spec ..." + foreach ($message in $validationErrors) { + Write-Host -Foreground Yellow "`t" $message.message + } + } else { + Write-Host -Foreground Green "`nHCX Pre-Migration Spec successfully validated" + if($ValidateOnly -eq $false) { + try { + $startDateTime = $StartTime | Get-Date + } catch { + Write-Host -Foreground Red "Invalid input for -StartTime, please check for typos" + exit + } + + try { + $endDateTime = $EndTime | Get-Date + } catch { + Write-Host -Foreground Red "Invalid input for -EndTime, please check for typos" + exit + } + + $offset = (Get-TimeZone).GetUtcOffset($startDateTime).TotalMinutes + $offset = [int]($offSet.toString().replace("-","")) + + $schedule = @{ + scheduledFailover = $true; + startYear = $startDateTime.Year; + startMonth = $startDateTime.Month; + startDay = $startDateTime.Day; + startHour = $startDateTime | Get-Date -UFormat %H; + startMinute = $startDateTime | Get-Date -UFormat %M; + endYear = $endDateTime.Year; + endMonth = $endDateTime.Month; + endDay = $endDateTime.Day; + endHour = $endDateTime | Get-Date -UFormat %H; + endMinute = $endDateTime | Get-Date -UFormat %M; + timezoneOffset = $offset; + } + + foreach ($migration in $spec.migrations) { + $migration.input.schedule = $schedule + } + $body = $spec | ConvertTo-Json -Depth 8 + + Write-Verbose -Message "Validated JSON Spec: $body" + $hcxMigrationStartUrl = $global:hcxConnection.Server+ "/migrations?action=start" + + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $hcxMigrationStartUrl -Body $body -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing -ContentType "application/json" -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $hcxMigrationStartUrl -Body $body -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing -ContentType "application/json" + } + + if($requests.StatusCode -eq 200) { + $migrationIds = ($requests.Content | ConvertFrom-Json).migrations.migrationId + Write-Host -ForegroundColor Green "Starting HCX Migration ..." + foreach ($migrationId in $migrationIds) { + Write-Host -ForegroundColor Green "`tMigrationID: $migrationId" + } + } else { + Write-Error "Failed to start HCX Migration" + } + } + } + } else { + Write-Error "Failed to validate HCX Migration spec" + } + } +} + +Function Get-HcxMigration { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/24/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + List all HCX Migrations that are in-progress, have completed or failed + .DESCRIPTION + This cmdlet lists ist all HCX Migrations that are in-progress, have completed or failed + .EXAMPLE + List all HCX Migrations + + Get-HcxMigration + .EXAMPLE + List all running HCX Migrations + + Get-HcxMigration -RunningMigrations + .EXAMPLE + List all HCX Migrations + + Get-HcxMigration -MigrationId +#> + Param ( + [Parameter(Mandatory=$false)][String]$MigrationId, + [Switch]$RunningMigrations + ) + + If (-Not $global:hcxConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxManager " } Else { + $spec = @{} + $body = $spec | ConvertTo-Json + + $hcxQueryUrl = $global:hcxConnection.Server + "/migrations?action=query" + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $hcxQueryUrl -Method POST -body $body -Headers $global:hcxConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $hcxQueryUrl -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing + } + + $migrations = ($requests.content | ConvertFrom-Json).rows + + if($PSBoundParameters.ContainsKey("MigrationId")){ + $migrations = $migrations | where { $_.migrationId -eq $MigrationId } + } + + if($RunningMigrations){ + $migrations = $migrations | where { $_.jobInfo.state -ne "MIGRATE_FAILED" -and $_.jobInfo.state -ne "MIGRATE_CANCELED"-and $_.jobInfo.state -ne "MIGRATED" } + } + + $results = @() + foreach ($migration in $migrations) { + $tmp = [pscustomobject] @{ + ID = $migration.migrationId; + VM = $migration.migrationInfo.entityDetails.entityName; + State = $migration.jobInfo.state; + Progress = ($migration.migrationInfo.progressDetails.progressPercentage).toString() + " %"; + DataCopied = ([math]::round($migration.migrationInfo.progressDetails.diskCopyBytes/1Gb, 2)).toString() + " GB"; + Message = $migration.migrationInfo.message; + InitiatedBy = $migration.jobInfo.username; + CreateDate = $migration.jobInfo.creationDate; + LastUpdated = $migration.jobInfo.lastUpdated; + } + $results+=$tmp + } + $results + } +} + Function Connect-HcxVAMI { <# .NOTES @@ -136,7 +539,7 @@ Function Connect-HcxVAMI { $global:hcxVAMIConnection } -Function Get-HcxVAMIVCConfig { +Function Get-HcxVCConfig { <# .NOTES =========================================================================== @@ -152,7 +555,7 @@ Function Get-HcxVAMIVCConfig { .DESCRIPTION This cmdlet returns the onPrem vCenter Server registered with HCX Manager .EXAMPLE - Get-HcxVAMIVCConfig + Get-HcxVCConfig #> If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { $vcConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/vcenter" From 82b5b2eb1e85a598314f8bd0583b7ebadb412b3d Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 27 Sep 2018 15:55:12 -0700 Subject: [PATCH 031/175] Adding VM & Criteria types into Get-NSXTGroup function --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index b87d788..3bfdfe3 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -605,7 +605,13 @@ Function Get-NSXTGroup { $members = @() foreach ($member in $group.expression) { - $members += $member.ip_addresses + if($member.ip_addresses) { + $members += $member.ip_addresses + } else { + if($member.resource_type -eq "Condition") { + $members += $member.value + } + } } $tmp = [pscustomobject] @{ From b25c2807149fc9d8267ac8e5b9a8f76ebd06e2a9 Mon Sep 17 00:00:00 2001 From: Doug Taliaferro Date: Wed, 3 Oct 2018 21:09:18 -0400 Subject: [PATCH 032/175] Sample script to set VM tags in the guestinfo --- Scripts/Set-TagsInGuestinfo.ps1 | 98 +++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Scripts/Set-TagsInGuestinfo.ps1 diff --git a/Scripts/Set-TagsInGuestinfo.ps1 b/Scripts/Set-TagsInGuestinfo.ps1 new file mode 100644 index 0000000..e895759 --- /dev/null +++ b/Scripts/Set-TagsInGuestinfo.ps1 @@ -0,0 +1,98 @@ +<# +.NOTES + Script name: Set-TagsInGuestinfo.ps1 + Created on: 10/02/2018 + Author: Doug Taliaferro, @virtually_doug + Description: Gets the vSphere Tags assigned to a VM and makes them available to the guest OS. + Dependencies: None known + + ===Tested Against Environment==== + vSphere Version: 6.5 + PowerCLI Version: 10.0.0.7893909 + PowerShell Version: 5.1.14409.1005 + OS Version: Windows 7, 10 + Keyword: VM, Tags, Guestinfo + +.SYNOPSIS + Gets the vSphere Tags assigned to a VM and makes them available to the guest OS. + +.DESCRIPTION + Gets the tags assigned to one or more VMs from one or more categories and sets the tag values + in the VM's 'guestinfo' advanced settings. This makes the tags available within the guest OS + using VM tools (vmtoolsd.exe) and allows the tags to be used as metadata for applications or + management agents that run inside the guest. + + For example, if a VM has a tag named 'Accounting' from the + category 'Departments', the advanced setting becomes: + guestinfo.Departments = Accounting + + This can be retrieved in the guest OS by running: + vmtoolsd.exe --cmd "info-get guestinfo.Departments" + + If multiple tags are assigned from the same category, they are joined using the specified + delimter (a semicolon by default): + guestinfo.Departments = Accounting;Sales + +.PARAMETER VMs + One or more VMs returned from the Get-VM cmdlet. + +.PARAMETER Categories + The names of tag categories that should be set in the advanced settings. + + .PARAMETER Delimiter + The delimiting character used for multiple tags of the same category. Defaults to a + semicolon. + +.PARAMETER vCenter + The vCenter server to connect to. Optional if you are already connected. + +.EXAMPLE + .\Set-TagsInGuestInfo.ps1 -VM (get-vm testvm01) -Categories Departments, Environment + + Gets tags assigned to 'testvm01' in the Departments and Environment categories and + sets their values in 'guestinfo.Departments' and 'guestinfo.Environment'. + +.EXAMPLE + .\Set-TagsInGuestInfo.ps1 -VM (get-cluster Dev-01 | get-vm) -Categories Departments + + Gets tags assigned to all VMs in the Dev-01 cluster and sets 'guestinfo.Departments' + on each VM. +#> +#Requires -modules VMware.VimAutomation.Core +[CmdletBinding()] +param ( + [Parameter(Mandatory=$true,Position=0)] + $VMs, + [Parameter(Mandatory=$true,Position=1)] + [string[]]$Categories, + [string]$Delimiter = ';', + [string]$vCenter +) +if ($vCenter) { + Connect-VIServer $vCenter +} + +ForEach ($categoryName in $Categories) { + $category = Get-TagCategory -Name $categoryName + if ($category) { + $guestinfoName = "guestinfo.$category" + + # Get Tag assignments for the VMs + $tags = Get-TagAssignment -Entity $VMs -Category $category + + # Group the tags by VM (in this case the Entity property of Group-Object) + $groups = $tags | Group-Object -Property Entity + + # Get each VM and set the guestinfo + ForEach ($item in $groups) { + $vm = get-vm $item.Name + # Multiple tags of the same category are joined + $guestinfoValue = $item.Group.Tag.Name -join $Delimiter + + Write-Host "$($vm): setting '$guestinfoName' = '$guestinfoValue'" + New-AdvancedSetting -Entity $vm -Name $guestinfoName -Value $guestinfoValue -Confirm:$false -Force | Out-Null + } + } else { + Write-Host "Category '$categoryName' was not found." + } +} From 0581d89cbe79ccca9968761e9a70ad11cc513113 Mon Sep 17 00:00:00 2001 From: Doug Taliaferro Date: Wed, 3 Oct 2018 21:16:50 -0400 Subject: [PATCH 033/175] Sample script to set VM tags in the guestinfo --- Scripts/Set-TagsInGuestinfo.ps1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Scripts/Set-TagsInGuestinfo.ps1 b/Scripts/Set-TagsInGuestinfo.ps1 index e895759..c245c05 100644 --- a/Scripts/Set-TagsInGuestinfo.ps1 +++ b/Scripts/Set-TagsInGuestinfo.ps1 @@ -79,16 +79,16 @@ ForEach ($categoryName in $Categories) { # Get Tag assignments for the VMs $tags = Get-TagAssignment -Entity $VMs -Category $category - - # Group the tags by VM (in this case the Entity property of Group-Object) + + # Group the tags by VM (in this case the Entity property of Group-Object) $groups = $tags | Group-Object -Property Entity - - # Get each VM and set the guestinfo + + # Get each VM and set the guestinfo ForEach ($item in $groups) { $vm = get-vm $item.Name - # Multiple tags of the same category are joined + # Multiple tags of the same category are joined $guestinfoValue = $item.Group.Tag.Name -join $Delimiter - + Write-Host "$($vm): setting '$guestinfoName' = '$guestinfoValue'" New-AdvancedSetting -Entity $vm -Name $guestinfoName -Value $guestinfoValue -Confirm:$false -Force | Out-Null } From 4246cfc71f9f185e8d7f6ccc9460782575dbdf09 Mon Sep 17 00:00:00 2001 From: Doug Taliaferro Date: Thu, 4 Oct 2018 19:53:08 -0400 Subject: [PATCH 034/175] Script to set custom attributes in guestinfo --- Scripts/Set-CustomAttributesInGuestinfo.ps1 | 84 +++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Scripts/Set-CustomAttributesInGuestinfo.ps1 diff --git a/Scripts/Set-CustomAttributesInGuestinfo.ps1 b/Scripts/Set-CustomAttributesInGuestinfo.ps1 new file mode 100644 index 0000000..d76d3ee --- /dev/null +++ b/Scripts/Set-CustomAttributesInGuestinfo.ps1 @@ -0,0 +1,84 @@ +<# +.NOTES + Script name: Set-CustomAttributesInGuestinfo.ps1 + Created on: 10/04/2018 + Author: Doug Taliaferro, @virtually_doug + Description: Gets Custom Attributes assigned to a VM and makes them available to the guest OS. + Dependencies: None known + + ===Tested Against Environment==== + vSphere Version: 6.5 + PowerCLI Version: 10.0.0.7893909 + PowerShell Version: 5.1.14409.1005 + OS Version: Windows 7, 10 + Keyword: VM, Attributes, Guestinfo + +.SYNOPSIS + Gets Custom Attributes assigned to a VM and makes them available to the guest OS. + +.DESCRIPTION + Gets the custom attributes assigned to one or more VMs and sets their values in the + VM's 'guestinfo' advanced settings. This makes the attributes available within the + guest OS using VM tools (vmtoolsd.exe) and allows the attributes to be used as metadata + for applications or management agents that run inside the guest. If the attribute name + contains spaces they are removed in naming the advanced setting. + + For example, if a VM has a custom attribute named 'Created On', the advanced setting + becomes: + 'guestinfo.CreatedOn' = '08/08/2018 14:24:17' + + This can be retrieved in the guest OS by running: + vmtoolsd.exe --cmd "info-get guestinfo.CreatedOn" + +.PARAMETER VMs + One or more VMs returned from the Get-VM cmdlet. + +.PARAMETER Attributes + The names of the Custom Attributes to get. If the names contain spaces they must be + enclosed in quotes. The spaces will be removed to name the advanced setting. + +.PARAMETER vCenter + The vCenter server to connect to. Optional if you are already connected. + +.EXAMPLE + .\Set-CustomAttributesInGuestInfo.ps1 -VM (get-vm testvm01) -Attributes 'Created On', 'Created By' + + Gets the custom attributes 'Created On' and 'Created By' for 'testvm01' and sets their + values in 'guestinfo.CreatedOn' and 'guestinfo.CreatedBy'. + +.EXAMPLE + .\Set-CustomAttributesInGuestInfo.ps1-VM (get-cluster Dev-01 | get-vm) -Attributes 'Created On' + + Gets the custom attribute 'Created On' for all VMs in the Dev-01 cluster and sets 'guestinfo.CreatedOn' + on each VM. +#> +#Requires -modules VMware.VimAutomation.Core +[CmdletBinding()] +param ( + [Parameter(Mandatory=$true,Position=0)] + $VMs, + [Parameter(Mandatory=$true,Position=1)] + [string[]]$Attributes, + [string]$vCenter +) +if ($vCenter) { + Connect-VIServer $vCenter +} + +ForEach ($vm in $VMs) { + ForEach ($attributeName in $Attributes) { + # Get the custom attribute with a matcing key name + $customField = $vm.CustomFields | Where-Object Key -eq $attributeName + if ($customField) { + # Remove white space from the attribute name because the advanced + # setting name cannot contain spaces + $attributeNameNoSpaces = $customField.Key -replace '\s','' + $guestinfoName = "guestinfo.$attributeNameNoSpaces" + $guestinfoValue = $customField.Value + Write-Host "$($vm): setting '$guestinfoName' = '$guestinfoValue'" + New-AdvancedSetting -Entity $vm -Name $guestinfoName -Value $guestinfoValue -Confirm:$false -Force | Out-Null + } else { + Write-Host "$($vm): custom attribute '$attributeName' not set on this VM" + } + } +} From 501bfa7fd2b5ea1111f321caab418faf9a7d8f35 Mon Sep 17 00:00:00 2001 From: Gerasimos Alexiou Date: Tue, 9 Oct 2018 22:48:07 +0300 Subject: [PATCH 035/175] backup-esxi-host-configuration backup-esxi-host-configuration powershell script --- Scripts/backup-esxi-host-configuration.ps1 | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Scripts/backup-esxi-host-configuration.ps1 diff --git a/Scripts/backup-esxi-host-configuration.ps1 b/Scripts/backup-esxi-host-configuration.ps1 new file mode 100644 index 0000000..924ca06 --- /dev/null +++ b/Scripts/backup-esxi-host-configuration.ps1 @@ -0,0 +1,22 @@ +<# +Script name: backup-esxi-host-configuration.ps1 +Created on: 09/10/2018 +Author: Gerasimos Alexiou, @jerrak0s +Description: The purpose of the script is to backup esxi host configuration for restore purposes. +Dependencies: None known + +===Tested Against Environment==== +vSphere Version: 6.5 U2 +PowerCLI Version: PowerCLI 10.1.1 +PowerShell Version: 5.1 +OS Version: Windows 10 +Keyword: Backup Configuration ESXi Host +#> + + +$serverIp = Read-Host 'What is the server ip address:' +$path = Read-Host 'Give path where backup configuration will be stored:' +$serverPass = Read-Host 'What is the server root password:' -AsSecureString +Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false +Connect-VIServer serverip -user "root" -password $serverPass +Get-VMHostFirmware -vmhost serverip -BackupConfiguration -DestinationPath $path \ No newline at end of file From 48d2db91d8cd840c4657bef053541b8a34e778c9 Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 9 Oct 2018 13:36:45 -0700 Subject: [PATCH 036/175] Added new functions to configure HCX Manager --- Modules/VMware.HCX/VMware.HCX.psd1 | 4 +- Modules/VMware.HCX/VMware.HCX.psm1 | 566 ++++++++++++++++++++++++++++- 2 files changed, 567 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psd1 b/Modules/VMware.HCX/VMware.HCX.psd1 index cd957ac..4e1e68b 100644 --- a/Modules/VMware.HCX/VMware.HCX.psd1 +++ b/Modules/VMware.HCX/VMware.HCX.psd1 @@ -12,7 +12,7 @@ RootModule = 'VMware.HCX.psm1' # Version number of this module. -ModuleVersion = '1.0.1' +ModuleVersion = '1.0.2' # Supported PSEditions # CompatiblePSEditions = @() @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing Hybrid Cloud Extension (HCX) on VM PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig' +FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', 'Get-HcxRoleMapping', 'Set-HcxRoleMapping' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index c066f87..7e5093c 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -576,4 +576,568 @@ Function Get-HcxVCConfig { } $tmp } -} \ No newline at end of file +} + +Function Set-HcxLicense { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Activate HCX Manager with HCX Cloud + .DESCRIPTION + This cmdlet activates HCX Manager with HCX Cloud + .EXAMPLE + Set-HcxLicense -LicenseKey +#> + Param ( + [Parameter(Mandatory=$True)]$LicenseKey + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $hcxConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/hcx" + $method = "POST" + + $hcxConfig = @{ + config = @{ + url = "https://connect.hcx.vmware.com"; + activationKey = $LicenseKey; + } + } + + $payload = @{ + data = @{ + items = @($hcxConfig) + } + } + + $body = $payload | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$vcConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $hcxConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $hcxConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully registered HCX Manager with HCX Cloud" + if($Troubleshoot) { ($results.Content | ConvertFrom-Json).data.items } + } else { + Write-Error "Failed to registered HCX Manager" + } + } +} + +Function Set-HcxVCConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Registers on-prem vCenter Server with HCX Manager + .DESCRIPTION + This cmdlet registers on-prem vCenter Server with HCX Manager + .EXAMPLE + Set-HcxVC -VIServer -VIUsername -VIPassword +#> + Param ( + [Parameter(Mandatory=$True)]$VIServer, + [Parameter(Mandatory=$True)]$PSCServer, + [Parameter(Mandatory=$True)]$VIUsername, + [Parameter(Mandatory=$True)]$VIPassword, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $vcConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/vcenter" + $pscConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/lookupservice" + $method = "POST" + + + $bytes = [System.Text.Encoding]::ASCII.GetBytes($VIPassword) + $base64 = [System.Convert]::ToBase64String($bytes) + + $vcConfig = @{ + config = @{ + url = "https://$VIServer"; + userName = $VIUsername; + password = $base64; + } + } + + $payload = @{ + data = @{ + items = @($vcConfig) + } + } + + $body = $payload | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$vcConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $vcConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $vcConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully registered vCenter Server with HCX Manager" + if($Troubleshoot) { ($results.Content | ConvertFrom-Json).data.items.config } + + $pscConfig = @{ + config = @{ + lookupServiceUrl = "https://$PSCServer" + providerType = "PSC" + } + } + + $payload = @{ + data = @{ + items = @($pscConfig) + } + } + + $body = $payload | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$pscConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $pscConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $pscConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully registered PSC with HCX Manager" + if($Troubleshoot) { ($results.Content | ConvertFrom-Json).data.items.config } + + } else { + Write-Error "Failed to registered PSC Server" + } + } else { + Write-Error "Failed to registered vCenter Server" + } + } +} + +Function Get-HcxNSXConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the onPrem NSX-V Server registered with HCX Manager + .DESCRIPTION + This cmdlet returns the onPrem NSX-V Server registered with HCX Manager + .EXAMPLE + Get-HcxNSXConfig +#> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $nsxConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/nsx" + + if($PSVersionTable.PSEdition -eq "Core") { + $nsxRequests = Invoke-WebRequest -Uri $nsxConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $nsxRequests = Invoke-WebRequest -Uri $nsxConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + $nsxData = ($nsxRequests.content | ConvertFrom-Json).data.items + + $tmp = [pscustomobject] @{ + Name = $nsxData.config.url; + Version = $nsxData.config.version; + HCXUUID = $nsxData.config.uuid; + } + $tmp + } +} + +Function Set-HcxNSXConfig { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Registers on-prem NSX-V Server with HCX Manager + .DESCRIPTION + This cmdlet registers on-prem NSX-V Server with HCX Manager + .EXAMPLE + Set-HcxNSXConfig -NSXServer -NSXUsername -NSXPassword +#> + Param ( + [Parameter(Mandatory=$True)]$NSXServer, + [Parameter(Mandatory=$True)]$NSXUsername, + [Parameter(Mandatory=$True)]$NSXPassword, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $nsxConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/nsx" + $method = "POST" + + $bytes = [System.Text.Encoding]::ASCII.GetBytes($NSXPassword) + $base64 = [System.Convert]::ToBase64String($bytes) + + $nsxConfig = @{ + config = @{ + url = "https://$NSXServer"; + userName = $NSXUsername; + password = $base64; + } + } + + $payload = @{ + data = @{ + items = @($nsxConfig) + } + } + + $body = $payload | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$nsxConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $nsxConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $nsxConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully registered NSX Server with HCX Manager" + if($Troubleshoot) { ($results.Content | ConvertFrom-Json).data.items.config } + } else { + Write-Error "Failed to registered NSX Server" + } + return $config + } +} + +Function Get-HcxCity { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the available HCX Location based on user City and Country input + .DESCRIPTION + This cmdlet returns the available HCX Location based on user City and Country input + .EXAMPLE + Get-HcxCity -City -Country + #> + Param ( + [Parameter(Mandatory=$True)]$City, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $citySearchUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/searchCities?searchString=$City" + $method = "GET" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$citySearchUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $citySearchUrl -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $citySearchUrl -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully returned results for City search: $City" + + $cityDetails = ($results.Content | ConvertFrom-Json).items + $cityDetails | select City,Country + } else { + Write-Error "Failed to search for city $City" + } + } + } + +Function Get-HcxLocation { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the registered City/Country location for HCX Manager + .DESCRIPTION + This cmdlet returns the registered City/Country location for HCX Manager + .EXAMPLE + Get-HcxLocation +#> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $locationConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/location" + + if($PSVersionTable.PSEdition -eq "Core") { + $locationRequests = Invoke-WebRequest -Uri $locationConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $locationRequests = Invoke-WebRequest -Uri $locationConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + ($locationRequests.content | ConvertFrom-Json) + } +} + +Function Set-HcxLocation { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Register HCX Manager to a specific City/Country + .DESCRIPTION + This cmdlet register HCX Manager to a specific City/Country + .EXAMPLE + Set-HcxLocation -City -Country +#> + Param ( + [Parameter(Mandatory=$True)]$City, + [Parameter(Mandatory=$True)]$Country, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $citySearchUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/searchCities?searchString=$City" + $method = "GET" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$citySearchUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $citySearchUrl -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $citySearchUrl -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + if($Troubleshoot) { ($results.Content | ConvertFrom-Json).items } + + $locationConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/location" + $method = "PUT" + + $cityDetails = ($results.Content | ConvertFrom-Json).items + $cityDetails = $cityDetails | where { $_.city -eq $City -and $_.country -match $Country } + + if(-not $cityDetails) { + Write-Host -ForegroundColor Red "Invalid input for City and/or Country, please provide the exact input from Get-HcxCity cmdlet" + break + } + + $locationConfig = @{ + city = $cityDetails.city; + country = $cityDetails.country; + province = $cityDetails.province; + latitude = $cityDetails.latitude; + longitude = $cityDetails.longitude; + } + + $body = $locationConfig | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$locationConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $locationConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $locationConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 204) { + Write-Host -ForegroundColor Green "Successfully registered datacenter location $City to HCX Manager" + } else { + Write-Error "Failed to registerd datacenter location in HCX Manager" + } + } else { + Write-Error "Failed to search for city $City" + } + } +} +Function Get-HcxRoleMapping { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the System Admin and Enterprise User Group role mappings for HCX Manager + .DESCRIPTION + This cmdlet returns the System Admin and Enterprise User Group role mappings for HCX Manager + .EXAMPLE + Get-HcxRoleMapping + #> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/roleMappings" + + if($PSVersionTable.PSEdition -eq "Core") { + $roleRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $roleRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + ($roleRequests.content | ConvertFrom-Json) + } + } + + Function Set-HcxRoleMapping { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Configures the System Admin and Enterprise User Group role mappings for HCX Manager + .DESCRIPTION + This cmdlet configures the System Admin and Enterprise User Group role mappings for HCX Manager + .EXAMPLE + Set-HcxRoleMapping -SystemAdminGroup @("DOMAIN\GROUP") -EnterpriseAdminGroup @("DOMAIN\GROUP") + #> + Param ( + [Parameter(Mandatory=$True)][String[]]$SystemAdminGroup, + [Parameter(Mandatory=$True)][String[]]$EnterpriseAdminGroup, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/roleMappings" + $method = "PUT" + + $roleConfig = @() + $systemAdminRole = @{ + role = "System Administrator"; + userGroups = $SystemAdminGroup + } + $enterpriseAdminRole = @{ + role = "Enterprise Administrator" + userGroups = $EnterpriseAdminGroup + } + $roleConfig+=$systemAdminRole + $roleConfig+=$enterpriseAdminRole + + $body = $roleConfig | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$locationConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $roleConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $roleConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully updated vSphere Group Mappings in HCX Manager" + } else { + Write-Error "Failed to update vSphere Group Mappings" + } + } + } \ No newline at end of file From b68dc6c4e08b7d401f77d291c56ab5c4fee7d1dc Mon Sep 17 00:00:00 2001 From: LucD Date: Thu, 25 Oct 2018 10:02:23 +0200 Subject: [PATCH 037/175] Updated VMware.VMC Fix issue #176 Added functions: - Get-VMCEdge - Get-VMCEdgeNic - Get-VMCEdgeStatus - Get-VMCEdgeNicStat - Get-VMCEdgeUplinkStat --- Modules/VMware.VMC/VMware.VMC.psd1 | Bin 8332 -> 8558 bytes Modules/VMware.VMC/VMware.VMC.psm1 | 573 ++++++++++++++++++++++------- 2 files changed, 435 insertions(+), 138 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psd1 b/Modules/VMware.VMC/VMware.VMC.psd1 index b33fca99fccc962543854a8ef2a85c1d00f7e2e2..105fec0612b9384cc68ec1d1240ff768945cef05 100755 GIT binary patch delta 162 zcmeBieCM=bj}SW-g8~Rnz9=ZX_?!?UoPSpMJf{u=k}SI`LkdGWL+WICA#q+Po57DE zlOY)-A`BA=W+-7u1maSLVvx8fOdPC|0V)fUk%q~HG88c60L{r`$cD*po+ -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" #> - param( + param( [Parameter(Mandatory=$false)][String]$SDDCName, [Parameter(Mandatory=$false)][String]$OrgName, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$false)][String]$Path ) - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - if($GatewayType -eq "MGW") { + if($GatewayType -eq "MGW") { $EdgeId = "edge-1" } else { $EdgeId = "edge-2" } - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - if(-not $orgId) { + if(-not $orgId) { Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" break } - if(-not $sddcId) { + if(-not $sddcId) { Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" break } - $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config + $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config - $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules - if(-not $ShowAll) { + $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules + if(-not $ShowAll) { $firewallRules = $firewallRules | where { $_.rule_type -ne "default_policy" -and $_.rule_type -ne "internal_high" -and $_.name -ne "vSphere Cluster HA" -and $_.name -ne "Outbound Access" } | Sort-Object -Property rule_tag } else { $firewallRules = $firewallRules | Sort-Object -Property rule_tag } - $results = @() - $count = 0 - foreach ($firewallRule in $firewallRules) { + $results = @() + $count = 0 + foreach ($firewallRule in $firewallRules) { if($firewallRule.source.ip_address.Count -ne 0) { $source = $firewallRule.source.ip_address } else { @@ -473,16 +471,15 @@ Function Get-VMCFirewallRule { $count+=1 $results+=$tmp } - if($Path) { + if($Path) { Write-Host -ForegroundColor Green "Exporting $count VMC Firewall Rules to $Path ..." $results | ConvertTo-Json | Out-File $Path } else { $results | ConvertTo-Json } - } - - Function Import-VMCFirewallRule { - <# +} +Function Import-VMCFirewallRule { +<# .NOTES =========================================================================== Created by: William Lam @@ -499,43 +496,43 @@ Function Get-VMCFirewallRule { .EXAMPLE Import-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" #> - param( + param( [Parameter(Mandatory=$false)][String]$SDDCName, [Parameter(Mandatory=$false)][String]$OrgName, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$false)][String]$Path ) - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - if($GatewayType -eq "MGW") { + if($GatewayType -eq "MGW") { $EdgeId = "edge-1" } else { $EdgeId = "edge-2" } - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - if(-not $orgId) { + if(-not $orgId) { Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" break } - if(-not $sddcId) { + if(-not $sddcId) { Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" break } - $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules - $vmcFirewallRulesJSON = Get-Content -Raw $Path | ConvertFrom-Json + $vmcFirewallRulesJSON = Get-Content -Raw $Path | ConvertFrom-Json - # Create top level Firewall Rules Object - $firewallRules = $firewallService.Help.add.firewall_rules.Create() - # Create top top level Firewall Rule Spec which will be an array of individual Firewall rules as we process them in next section - $ruleSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Create() + # Create top level Firewall Rules Object + $firewallRules = $firewallService.Help.add.firewall_rules.Create() + # Create top top level Firewall Rule Spec which will be an array of individual Firewall rules as we process them in next section + $ruleSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Create() - foreach ($vmcFirewallRule in $vmcFirewallRulesJSON) { + foreach ($vmcFirewallRule in $vmcFirewallRulesJSON) { # Create Individual Firewall Rule Element Spec $ruleElementSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.Create() @@ -632,14 +629,13 @@ Function Get-VMCFirewallRule { Write-host "Creating VMC Firewall Rule Spec:" $vmcFirewallRule.Name "..." $ruleSpecAdd = $ruleSpec.Add($ruleElementSpec) } - $firewallRules.firewall_rules = $ruleSpec + $firewallRules.firewall_rules = $ruleSpec - Write-host "Adding VMC Firewall Rules ..." - $firewallRuleAdd = $firewallService.add($orgId,$sddcId,$EdgeId,$firewallRules) - } - - Function Remove-VMCFirewallRule { - <# + Write-host "Adding VMC Firewall Rules ..." + $firewallRuleAdd = $firewallService.add($orgId,$sddcId,$EdgeId,$firewallRules) +} +Function Remove-VMCFirewallRule { +<# .NOTES =========================================================================== Created by: William Lam @@ -656,38 +652,37 @@ Function Get-VMCFirewallRule { .EXAMPLE Remove-VMCFirewallRule -OrgName -SDDCName -GatewayType -RuleId #> - param( + param( [Parameter(Mandatory=$false)][String]$SDDCName, [Parameter(Mandatory=$false)][String]$OrgName, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$false)][String]$RuleId ) - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - if($GatewayType -eq "MGW") { + if($GatewayType -eq "MGW") { $EdgeId = "edge-1" } else { $EdgeId = "edge-2" } - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - if(-not $orgId) { + if(-not $orgId) { Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" break } - if(-not $sddcId) { + if(-not $sddcId) { Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" break } - $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules - Write-Host "Removing VMC Firewall Rule Id $RuleId ..." - $firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId) - } - + $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + Write-Host "Removing VMC Firewall Rule Id $RuleId ..." + $firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId) +} Function Get-VMCLogicalNetwork { <# .NOTES @@ -727,9 +722,17 @@ Function Get-VMCLogicalNetwork { break } - $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical + # @LucD22 - 21/10/18 - Fix for issue #176 VMware.VMC module only lists firts 20 Logical networks + # Loop until entries (total_count) are returned - $logicalNetworks = ($logicalNetworkService.get_0($orgId, $sddcId)).data | Sort-Object -Property id + $index = [long]0 + + $logicalNetworks = do{ + $netData = $logicalNetworkService.get_0($orgId,$sddcId,$pagesize,$index) + $netData.data | Sort-Object -Property id + $index = $index + $netdata.paging_info.page_size + } + until($index -ge $netData.paging_info.total_count) if($LogicalNetworkName) { $logicalNetworks = $logicalNetworks | Where-Object {$_.Name -eq $LogicalNetworkName} @@ -751,7 +754,6 @@ Function Get-VMCLogicalNetwork { } $results } - Function Remove-VMCLogicalNetwork { <# .NOTES @@ -799,25 +801,24 @@ Function Remove-VMCLogicalNetwork { $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical $logicalNetworkService.delete($orgId,$sddcId,$lsId) } - Function New-VMCLogicalNetwork { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/06/2018 - Organization: VMware - Blog: https://thatcouldbeaproblem.com - Twitter: @kmruddy - =========================================================================== +<# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/06/2018 + Organization: VMware + Blog: https://thatcouldbeaproblem.com + Twitter: @kmruddy + =========================================================================== - .SYNOPSIS - Creates a new Logical Network - .DESCRIPTION - Creates a new Logical Network - .EXAMPLE - New-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName -SubnetMask -Gateway - #> + .SYNOPSIS + Creates a new Logical Network + .DESCRIPTION + Creates a new Logical Network + .EXAMPLE + New-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName -SubnetMask -Gateway +#> [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] param( [Parameter(Mandatory=$true)][String]$SDDCName, @@ -854,7 +855,6 @@ Function New-VMCLogicalNetwork { $logicalNetworkService.create($orgId, $sddcId, $logicalNetworkSpec) Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName } - Function Get-VMCSDDCSummary { <# .NOTES @@ -899,7 +899,6 @@ Function Get-VMCSDDCSummary { $results } } - Function Get-VMCPublicIP { <# .NOTES @@ -933,79 +932,377 @@ Function Get-VMCPublicIP { $publicIPs | select public_ip, name, allocation_id } } +Function New-VMCPublicIP { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== - Function New-VMCPublicIP { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== + .SYNOPSIS + Request a new public IP Address for a given SDDC + .DESCRIPTION + This cmdlet requests a new public IP Address for a given SDDC + .EXAMPLE + New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" +#> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$False)]$Description + ) - .SYNOPSIS - Request a new public IP Address for a given SDDC - .DESCRIPTION - This cmdlet requests a new public IP Address for a given SDDC - .EXAMPLE - New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" - #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$False)]$Description - ) + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + $publicIPSpec = $publicIPService.Help.create.spec.Create() + $publicIPSpec.count = 1 + $publicIPSpec.names = @($Description) - $publicIPSpec = $publicIPService.Help.create.spec.Create() - $publicIPSpec.count = 1 - $publicIPSpec.names = @($Description) + Write-Host "Requesting a new public IP Address for your SDDC ..." + $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) + } +} +Function Remove-VMCPublicIP { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== - Write-Host "Requesting a new public IP Address for your SDDC ..." - $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) + .SYNOPSIS + Removes a specific public IP Addresses for a given SDDC + .DESCRIPTION + This cmdlet removes a specific public IP Address for a given SDDC + .EXAMPLE + Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" +#> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$AllocationId + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + Write-Host "Deleting public IP Address with ID $AllocationId ..." + $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + } +} +Function Get-VMCEdge { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns all the VMC Edges +.DESCRIPTION + Returns all the VMC Edges +.EXAMPLE + Get-VMCEdge -OrgName $orgName -SddcName $SDDCName -EdgeType gatewayServices +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [ValidateSet('gatewayServices','distributedRouter')] + [string]$EdgeType = '' + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $edgeService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges' + $index = [long]0 + $edges = do{ + $edgeData = $edgeService.get($orgId,$sddcId,$EdgeType,'',$index) + $edgeData.edge_page.data | Sort-Object -Property id + $index = $index + $edgeData.edge_page.paging_info.page_size + } + until($index -ge $edgeData.paging_info.total_count) + $edges | %{ + [pscustomobject]@{ + Name = $_.Name + Id = $_.id + Type = $_.edge_type + State = $_.state + Status = $_.edge_status + VNics = $_.number_of_connected_vnics + TenantId = $_.tenant_id + } } } +} +Function Get-VMCEdgeStatus { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== - Function Remove-VMCPublicIP { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== +.SYNOPSIS + Returns the status of the gateway +.DESCRIPTION + Retrieve the status of the specified management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeStatus -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName + ) - .SYNOPSIS - Removes a specific public IP Addresses for a given SDDC - .DESCRIPTION - This cmdlet removes a specific public IP Address for a given SDDC - .EXAMPLE - Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" - #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$True)]$AllocationId - ) + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $statusService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.status' + $status = $statusService.get($orgId,$sddcId,$edgeId) - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - - Write-Host "Deleting public IP Address with ID $AllocationId ..." - $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + $vmStatus = $status.edge_vm_status | %{ + [pscustomobject]@{ + Name = $_.name + State = $_.edge_VM_status + HAState = $_.ha_state + Index = $_.index + } + } + $featureStatus = $status.feature_statuses | %{ + [pscustomobject]@{ + Service = $_.service + Status = $_.status + } + } + [pscustomobject]@{ + Time = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($status.timestamp/1000)) + Status = $status.edge_status + PublishStatus = $status.publish_status + SystemStatus = $_.system_status + NicInUse = $status.ha_vnic_in_use } } +} +Function Get-VMCEdgeNic { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP' +.SYNOPSIS + Returns all interfaces for the gateway +.DESCRIPTION + Retrieve all interfaces for the specified management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeNic -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + + $vnicService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.vnics' + $vnicService.get($orgId,$sddcId,$edgeId) | select -ExpandProperty vnics | %{ + [pscustomobject]@{ + Label = $_.label + Name = $_.Name + Type = $_.type + Index = $_.index + IsConnected = $_.is_connected + Portgroup = $_.portgroup_name + } + } + } +} +Function Get-VMCEdgeNicStat { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns statistics for the gateway interfaces +.DESCRIPTION + Retrieve interface statistics for a management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeNicStat -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + [CmdletBinding(DefaultParameterSetName='Default')] + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName +# [DateTime]$Start, +# [DateTime]$Finish + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + +# $epoch = Get-Date 01/01/1970 +# +# if($start){ +# $startEpoch = (New-TimeSpan -Start $epoch -End $Start.ToUniversalTime()).TotalMilliseconds +# } +# if($Finish){ +# $finishEpoch = (New-TimeSpan -Start $epoch -End $Finish.ToUniversalTime()).TotalMilliseconds +# } + + $vnicStatService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.statistics.interfaces' +# $stats = $vnicStatService.get($orgId,$sddcId,$edgeId,[long]$startEpoch,[long]$finishEpoch) + $stats = $vnicStatService.get($orgId,$sddcId,$edgeId) + + $stats.data_dto | Get-Member -MemberType NoteProperty | where{$_.Name -ne 'Help'} | %{$_.Name} | %{ + $stats.data_dto."$_" | %{ + [pscustomobject]@{ + vNIC = $_.vnic + Timestamp = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.timestamp)) + In = $_.in + Out = $_.out + Unit = 'Kbps' + Interval = $stats.meta_dto.interval + } + } + } + } +} +Function Get-VMCEdgeUplinkStat { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns statistics for the uplink interfaces +.DESCRIPTION + Retrieve uplink interface statistics for a management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeUplinkStat -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName +# [DateTime]$Start, +# [DateTime]$Finish + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + +# $epoch = Get-Date 01/01/1970 +# +# if($start){ +# $startEpoch = (New-TimeSpan -Start $epoch -End $Start.ToUniversalTime()).TotalMilliseconds +# } +# if($Finish){ +# $finishEpoch = (New-TimeSpan -Start $epoch -End $Finish.ToUniversalTime()).TotalMilliseconds +# } + + $uplinkStatService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.statistics.interfaces.uplink' +# $stats = $uplinkStatService.get($orgId,$sddcId,$edgeId,[long]$startEpoch,[long]$finishEpoch) + $stats = $uplinkStatService.get($orgId,$sddcId,$edgeId) + + $stats.data_dto | Get-Member -MemberType NoteProperty | where{$_.Name -ne 'Help'} | %{$_.Name} | %{ + if($stats.data_dto."$_".Count -ne 0){ + $stats.data_dto."$_" | %{ + [pscustomobject]@{ + vNIC = $_.vnic + Timestamp = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.timestamp)) + In = $_.in + Out = $_.out + Unit = 'Kbps' + Interval = $stats.meta_dto.interval + } + } + } + } + } +} + +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', + 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', + 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', + 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', + 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', + 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat' From 3904b416b3ddd74827374735911d286437890997 Mon Sep 17 00:00:00 2001 From: LucD Date: Thu, 25 Oct 2018 10:43:04 +0200 Subject: [PATCH 038/175] XRef for VMC services and functions Requires ImportExcel module --- .../VMware_Cloud_on_AWS/XRef-VMC-Services.ps1 | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Scripts/VMware_Cloud_on_AWS/XRef-VMC-Services.ps1 diff --git a/Scripts/VMware_Cloud_on_AWS/XRef-VMC-Services.ps1 b/Scripts/VMware_Cloud_on_AWS/XRef-VMC-Services.ps1 new file mode 100644 index 0000000..eb591bb --- /dev/null +++ b/Scripts/VMware_Cloud_on_AWS/XRef-VMC-Services.ps1 @@ -0,0 +1,37 @@ +$refreshToken = 'your-refresh-token' + +$reportPath = '.\VMC-services.xlsx' + +Connect-Vmc -RefreshToken $refreshToken > $null + +$columns = @{} +$services = Get-VmcService | Sort-Object -Property Name +$services | ForEach-Object -Process { + $_.Help | Get-Member -MemberType NoteProperty | where{'Constants','Documentation' -notcontains $_.Name} | + ForEach-Object -Process { + if(-not $columns.ContainsKey($_.Name)){ + $columns.Add($_.Name,'') + } + } +} +$columns = $columns.Keys | Sort-Object +$report = @() +foreach($service in $services){ + $obj = [ordered]@{ + Name = $service.Name + } + $columns | ForEach-Object -Process { + $obj.Add($_,'') + } + + $service.Help | Get-Member -MemberType NoteProperty | where{'Constants','Documentation' -notcontains $_.Name} | + ForEach-Object -Process { +# $obj.Item($_.Name) = "$($service.Help.$($_.Name).Documentation)" + $obj.Item($_.Name) = "X" + } + $report += New-Object PSObject -Property $obj +} +$report | Export-Excel -Path $reportPath -WorksheetName 'Services' -FreezeTopRow -BoldTopRow -AutoSize -Show + +Disconnect-Vmc -Confirm:$false + From 578d3c5deb27e3a945a6a12112d8a266e3491161 Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 1 Nov 2018 07:33:40 -0700 Subject: [PATCH 039/175] Updated to include configuringn Proxy Settings --- Modules/VMware.HCX/VMware.HCX.psd1 | 2 +- Modules/VMware.HCX/VMware.HCX.psm1 | 298 ++++++++++++++++++++++------- 2 files changed, 233 insertions(+), 67 deletions(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psd1 b/Modules/VMware.HCX/VMware.HCX.psd1 index 4e1e68b..a5e74f0 100644 --- a/Modules/VMware.HCX/VMware.HCX.psd1 +++ b/Modules/VMware.HCX/VMware.HCX.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing Hybrid Cloud Extension (HCX) on VM PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', 'Get-HcxRoleMapping', 'Set-HcxRoleMapping' +FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', 'Get-HcxRoleMapping', 'Set-HcxRoleMapping', 'Get-HcxProxy', 'Set-HcxProxy', 'Remove-HcxProxy' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index 7e5093c..cfbe95b 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -1047,87 +1047,250 @@ Function Set-HcxLocation { } } Function Get-HcxRoleMapping { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/16/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== - .SYNOPSIS - Returns the System Admin and Enterprise User Group role mappings for HCX Manager - .DESCRIPTION - This cmdlet returns the System Admin and Enterprise User Group role mappings for HCX Manager - .EXAMPLE - Get-HcxRoleMapping - #> - If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { - $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/roleMappings" + .SYNOPSIS + Returns the System Admin and Enterprise User Group role mappings for HCX Manager + .DESCRIPTION + This cmdlet returns the System Admin and Enterprise User Group role mappings for HCX Manager + .EXAMPLE + Get-HcxRoleMapping +#> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/roleMappings" + if($PSVersionTable.PSEdition -eq "Core") { + $roleRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $roleRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + ($roleRequests.content | ConvertFrom-Json) + } +} + +Function Set-HcxRoleMapping { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/16/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Configures the System Admin and Enterprise User Group role mappings for HCX Manager + .DESCRIPTION + This cmdlet configures the System Admin and Enterprise User Group role mappings for HCX Manager + .EXAMPLE + Set-HcxRoleMapping -SystemAdminGroup @("DOMAIN\GROUP") -EnterpriseAdminGroup @("DOMAIN\GROUP") +#> + Param ( + [Parameter(Mandatory=$True)][String[]]$SystemAdminGroup, + [Parameter(Mandatory=$True)][String[]]$EnterpriseAdminGroup, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/roleMappings" + $method = "PUT" + + $roleConfig = @() + $systemAdminRole = @{ + role = "System Administrator"; + userGroups = $SystemAdminGroup + } + $enterpriseAdminRole = @{ + role = "Enterprise Administrator" + userGroups = $EnterpriseAdminGroup + } + $roleConfig+=$systemAdminRole + $roleConfig+=$enterpriseAdminRole + + $body = $roleConfig | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$locationConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { if($PSVersionTable.PSEdition -eq "Core") { - $roleRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + $results = Invoke-WebRequest -Uri $roleConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck } else { - $roleRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + $results = Invoke-WebRequest -Uri $roleConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing } - ($roleRequests.content | ConvertFrom-Json) + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully updated vSphere Group Mappings in HCX Manager" + } else { + Write-Error "Failed to update vSphere Group Mappings" } } +} - Function Set-HcxRoleMapping { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/16/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== +Function Get-HcxProxy { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 10/31/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== - .SYNOPSIS - Configures the System Admin and Enterprise User Group role mappings for HCX Manager - .DESCRIPTION - This cmdlet configures the System Admin and Enterprise User Group role mappings for HCX Manager - .EXAMPLE - Set-HcxRoleMapping -SystemAdminGroup @("DOMAIN\GROUP") -EnterpriseAdminGroup @("DOMAIN\GROUP") - #> - Param ( - [Parameter(Mandatory=$True)][String[]]$SystemAdminGroup, - [Parameter(Mandatory=$True)][String[]]$EnterpriseAdminGroup, - [Switch]$Troubleshoot - ) + .SYNOPSIS + Returns the proxy settings for HCX Manager + .DESCRIPTION + This cmdlet returns the proxy settings for HCX Manager + .EXAMPLE + Get-HcxProxy +#> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $proxyConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/proxy" - If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { - $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/roleMappings" - $method = "PUT" + if($PSVersionTable.PSEdition -eq "Core") { + $proxyRequests = Invoke-WebRequest -Uri $proxyConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $proxyRequests = Invoke-WebRequest -Uri $proxyConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + $proxySettings = ($proxyRequests.content | ConvertFrom-Json).data.items + if($proxyRequests) { + $proxySettings.config + } + } +} - $roleConfig = @() - $systemAdminRole = @{ - role = "System Administrator"; - userGroups = $SystemAdminGroup +Function Set-HcxProxy { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 10/31/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Configure proxy settings on HCX Manager + .DESCRIPTION + This cmdlet configure proxy settings on HCX Manager + .EXAMPLE + Set-HcxProxy -ProxyServer proxy.vmware.com -ProxyPort 3124 + .EXAMPLE + Set-HcxProxy -ProxyServer proxy.vmware.com -ProxyPort 3124 -ProxyUser foo -ProxyPassword bar +#> + Param ( + [Parameter(Mandatory=$True)]$ProxyServer, + [Parameter(Mandatory=$True)]$ProxyPort, + [Parameter(Mandatory=$False)]$ProxyUser, + [Parameter(Mandatory=$False)]$ProxyPassword, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX VAMI Auth Token not found, please run Connect-HcxVAMI " } Else { + $proxyConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/proxy" + $method = "POST" + + if(-not $ProxyUser) { $ProxyUser = ""} + if(-not $ProxyPassword) { $ProxyPassword = ""} + + $proxyConfig = @{ + config = @{ + proxyHost = "$ProxyServer"; + proxyPort = "$ProxyPort"; + nonProxyHosts = ""; + userName = "$ProxyUser"; + password = "$ProxyPassword"; } - $enterpriseAdminRole = @{ - role = "Enterprise Administrator" - userGroups = $EnterpriseAdminGroup - } - $roleConfig+=$systemAdminRole - $roleConfig+=$enterpriseAdminRole + } - $body = $roleConfig | ConvertTo-Json -Depth 5 - - if($Troubleshoot) { - Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$locationConfigUrl`n" - Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + $payload = @{ + data = @{ + items = @($proxyConfig) } + } + + $body = $payload | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$proxyConfigUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $proxyConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $proxyConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + } catch { + Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" + break + } + + if($results.StatusCode -eq 200) { + Write-Host -ForegroundColor Green "Successfully updated proxy settings in HCX Manager" + if($Troubleshoot) { ($results.Content | ConvertFrom-Json).data.items.config } + } else { + Write-Error "Failed to update proxy settings" + } + } +} + +Function Remove-HcxProxy { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 10/31/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the proxy settings for HCX Manager + .DESCRIPTION + This cmdlet returns the proxy settings for HCX Manager + .EXAMPLE + Remove-HcxProxy +#> + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $roleConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/proxy" + + if($PSVersionTable.PSEdition -eq "Core") { + $proxyRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $proxyRequests = Invoke-WebRequest -Uri $roleConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + $proxySettings = ($proxyRequests.content | ConvertFrom-Json).data.items + if($proxyRequests) { + $proxyUUID = $proxySettings.config.UUID + + $deleteProxyConfigURl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/proxy/$proxyUUID" + $method = "DELETE" try { if($PSVersionTable.PSEdition -eq "Core") { - $results = Invoke-WebRequest -Uri $roleConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + $results = Invoke-WebRequest -Uri $deleteProxyConfigURl -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck } else { - $results = Invoke-WebRequest -Uri $roleConfigUrl -Body $body -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + $results = Invoke-WebRequest -Uri $deleteProxyConfigURl -Method $method -Headers $global:hcxVAMIConnection.headers -UseBasicParsing } } catch { Write-Host -ForegroundColor Red "`nRequest failed: ($_.Exception)`n" @@ -1135,9 +1298,12 @@ Function Get-HcxRoleMapping { } if($results.StatusCode -eq 200) { - Write-Host -ForegroundColor Green "Successfully updated vSphere Group Mappings in HCX Manager" + Write-Host -ForegroundColor Green "Successfully deleted proxy settings in HCX Manager" } else { - Write-Error "Failed to update vSphere Group Mappings" + Write-Error "Failed to delete proxy settings" } + } else { + Write-Warning "No proxy settings were configured" } - } \ No newline at end of file + } +} \ No newline at end of file From 37c9effbd79b78337e382ec1290dfb6d974bb810 Mon Sep 17 00:00:00 2001 From: Franciosi Date: Fri, 2 Nov 2018 15:08:07 -0300 Subject: [PATCH 040/175] Update README.md Small typo fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 86afe3e..a82900f 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,8 @@ * [Security](https://github.com/vmware/PowerCLI-Example-Scripts#security) * [Resource Maintenance](https://github.com/vmware/PowerCLI-Example-Scripts#resource-maintenance) * [Maintenance Ownership](https://github.com/vmware/PowerCLI-Example-Scripts#maintenance-ownership) - * [Filing issues](https://github.com/vmware/PowerCLI-Example-Scripts#filing-isssues) - * [Resolving issues](https://github.com/vmware/PowerCLI-Example-Scripts#resolving-issues) + * [Filing Issues](https://github.com/vmware/PowerCLI-Example-Scripts#filing-isssues) + * [Resolving Issues](https://github.com/vmware/PowerCLI-Example-Scripts#resolving-issues) * [Additional Resources](https://github.com/vmware/PowerCLI-Example-Scripts#additional-resources) * [Discussions](https://github.com/vmware/PowerCLI-Example-Scripts#discussions) * [VMware Sample Exchange](https://github.com/vmware/PowerCLI-Example-Scripts#vmware-sample-exchange) From ce32e7ab1d5a8706aac618e254f46b243f9fd25b Mon Sep 17 00:00:00 2001 From: Wouter Kursten Date: Thu, 15 Nov 2018 10:07:01 +0100 Subject: [PATCH 041/175] bugfix viewStorageAcceleratorSettings --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 6f176b4..c58e1c0 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -4270,20 +4270,20 @@ function New-HVPool { $redirectWindowsProfile = $false } } - if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings) { - $useViewStorageAccelerator = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.UseViewStorageAccelerator + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.viewStorageAcceleratorSettings) { + $useViewStorageAccelerator = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.viewStorageAcceleratorSettings.UseViewStorageAccelerator if ($useViewStorageAccelerator -and $LinkedClone) { - $viewComposerDiskTypes = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.viewStorageAcceleratorSettings.ViewComposerDiskTypes + $viewComposerDiskTypes = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.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 + $regenerateViewStorageAcceleratorDays = $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.viewStorageAcceleratorSettings.RegenerateViewStorageAcceleratorDays + if ($null -ne $jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.viewStorageAcceleratorSettings.blackoutTimes) { + $blackoutTimesList =$jsonObject.AutomatedDesktopSpec.VirtualCenterProvisioningSettings.VirtualCenterStorageSettings.viewStorageAcceleratorSettings.blackoutTimes foreach ($blackout in $blackoutTimesList) { $blackoutObj = New-Object VMware.Hv.DesktopBlackoutTime $blackoutObj.Days = $blackout.Days $blackoutObj.StartTime = $blackout.StartTime - $blackoutObj.EndTime = $blackoutObj.EndTime + $blackoutObj.EndTime = $blackout.EndTime $blackoutTimes += $blackoutObj } } From 0743c67799b35e155f5e7aaf93b0facdb9a80884 Mon Sep 17 00:00:00 2001 From: Zhoulin Dai Date: Mon, 19 Nov 2018 22:41:26 +0800 Subject: [PATCH 042/175] Initial commit of VMware.VCGChecker module --- .../VMware.VCGChecker/Export-VCGReport.ps1 | 1057 +++++++++++++++++ Modules/VMware.VCGChecker/Get-VCGHWInfo.ps1 | 310 +++++ Modules/VMware.VCGChecker/Get-VCGStatus.ps1 | 168 +++ Modules/VMware.VCGChecker/README.md | 41 + .../VMware.VCGChecker/Save-VCGJsonFile.ps1 | 17 + .../VMware.VCGChecker/VMware.VCGChecker.psd1 | 90 ++ Modules/VMware.VCGChecker/logger.ps1 | 112 ++ 7 files changed, 1795 insertions(+) create mode 100644 Modules/VMware.VCGChecker/Export-VCGReport.ps1 create mode 100644 Modules/VMware.VCGChecker/Get-VCGHWInfo.ps1 create mode 100644 Modules/VMware.VCGChecker/Get-VCGStatus.ps1 create mode 100644 Modules/VMware.VCGChecker/README.md create mode 100644 Modules/VMware.VCGChecker/Save-VCGJsonFile.ps1 create mode 100644 Modules/VMware.VCGChecker/VMware.VCGChecker.psd1 create mode 100644 Modules/VMware.VCGChecker/logger.ps1 diff --git a/Modules/VMware.VCGChecker/Export-VCGReport.ps1 b/Modules/VMware.VCGChecker/Export-VCGReport.ps1 new file mode 100644 index 0000000..1b1253d --- /dev/null +++ b/Modules/VMware.VCGChecker/Export-VCGReport.ps1 @@ -0,0 +1,1057 @@ +# +# Generate the html report and save it to the report folder +# TODO: change to the class +Function Export-VCGReport { + Param( + [Parameter(Mandatory=$true)] $Data, + [Parameter(Mandatory=$true)] $Dir + ) + if (!(Test-Path $Dir)) { + New-Item -Type directory -Confirm:$false -Path $Dir -Force |Out-Null + } + + $Data,$flag = refactorData $Data + + $null=Generate_CsvReport $Data $Dir + $null=Generate_HtmlReport $Data $Dir + $null=Generate_SummaryReport $Data $Dir +} +Function Generate_HtmlReport($Data, $Dir) { + info ("Generating compatibility detail report...") + $content = $generalHead + $content += '

ESXi Hardware Compatibility Report for {0}

' -f $Data.hostname + $content += $generalBodyBase + if (-not(checkVersion($Data))) { + $content += 'Installed Release' + } + else { + $content += 'Checked Release' + } + $content += $generalBodyRest + foreach ($VCResource in $Data) { + $checkVersion = $VCResource.checkRelease + $Count1 = $VCResource.DCResource.HostResource.ComponentResource.Count + $Process = '' + if ($VCResource.hostname -ne 'null') { + $Process += '{1}' -f $Count1, [string]$VCResource.hostname + } + else { + $Process += '{1}' -f $Count1, '/' + } + foreach ($DCResource in $VCResource.DCResource) { + $Count2 = $DCResource.HostResource.ComponentResource.Count + if ($DCResource.dcname -ne 'null') { + $Process += '{1}' -f [string]$Count2, [string]$DCResource.dcname + } + else { + $Process += '{1}' -f [string]$Count2, '/' + } + foreach ($HostResourceOne in $DCResource.HostResource) { + $Count = $HostResourceOne.ComponentResource.count + $Process += '{1}' -f $Count, $HostResourceOne.HostName + foreach ($OneDevice in $HostResourceOne.ComponentResource) { + if ($OneDevice.type -eq 'Server') { + # $InfoServer = "" | Select HostName, Manufacturer, Model, CPU, Version, Bios, CpuFeature, Uuid, VcgLink, Status, FoundRelease, MatchResult, Warnings + $InfoServer = @{} + $InfoServer.HostName = $HostResourceOne.hostname + $InfoServer.Version = $HostResourceOne.version + $InfoServer.Manufacturer = $OneDevice.vendor + $InfoServer.Model = $OneDevice.model + $InfoServer.CPU = $OneDevice.cpumodel + $InfoServer.Bios = $OneDevice.biosversion + $InfoServer.CpuFeature = $OneDevice.cpufeatureid + $InfoServer.Uuid = $OneDevice.uuid + $InfoServer.VcgLink = $OneDevice.vcgLink + $InfoServer.Status = formatStatus($OneDevice.status) + $InfoServer.MatchResult = $OneDevice.matchResult + $InfoServer.Warnings = (([string]$OneDevice.warnings) -split "More information")[0] + # server info + $Process += 'Server' + $Process += '{0}' -f $InfoServer.Model + $Process += '{0}' -f $InfoServer.Manufacturer + if (-not $checkVersion) { + $Process += '{0}' -f $InfoServer.Version + } + else { + $Process += '{0}' -f $checkVersion + } + $Process += '{0}' -f $InfoServer.Status + $Process += '{0},
CpuFeature:{1},
Bios:{2}' -f $InfoServer.CPU, $InfoServer.CpuFeature, $InfoServer.Bios + if ($InfoServer.VcgLink.Count -gt 0) { + $Process += '{0}
' -f $InfoServer.Warnings + foreach ($link in $InfoServer.VcgLink) { + $Process += ' VCG link
' -f $link + } + $Process += '' + } + else + {$Process += '{0}
N/A' -f $InfoServer.Warnings} + $Process += '' + } + else { + # $InfoPci = "" | Select model, vendor, Vid, Did, Svid, Ssid, Driver, DriverVersion, Version, Pccid, VcgLink, Status, FoundRelease, MatchResult, Warnings + $InfoPci = @{} + $InfoPci.model = $OneDevice.model + $InfoPci.vendor = $OneDevice.vendor + $InfoPci.Vid = $OneDevice.vid + $InfoPci.Did = $OneDevice.did + $InfoPci.Svid = $OneDevice.svid + $InfoPci.Ssid = $OneDevice.ssid + $InfoPci.Driver = $OneDevice.driver + $InfoPci.DriverVersion = $OneDevice.driverversion + $InfoPci.Version = $HostResourceOne.version + $InfoPci.Pccid = $OneDevice.pciid + $InfoPci.VcgLink = $OneDevice.vcgLink + $InfoPci.Status = formatStatus($OneDevice.status) + $InfoPci.MatchResult = $OneDevice.matchResult + $InfoPci.Warnings = (([string]$OneDevice.warnings) -split "More information")[0] + # IO info + # TODO:Variable information coverage, need to be modified + $Process += '' + $Process += 'IO Device' + $Process += '{0}' -f $InfoPci.model + $Process += '{0}' -f $InfoPci.vendor + if (-not $checkVersion) { + $Process += '{0}' -f $InfoPci.Version + } + else { + $Process += '{0}' -f $checkVersion + } + $Process += '{0}' -f $InfoPci.Status + $Process += 'PCI ID:{0}
Driver:{1} Version:{2}' -f $InfoPci.Pccid, $InfoPci.Driver, $InfoPci.DriverVersion + if ($InfoPci.VcgLink.Count -gt 0) { + $Process += '{0}
' -f $InfoPci.Warnings + foreach ($link in $InfoPci.VcgLink) { + $Process += ' VCG link
' -f $link + } + $Process += '' + } + else + {$Process += '{0}
N/A' -f $InfoPci.Warnings} + $Process += '' + } + } + } + } + $content += $Process + } + $content += $generalFooter + #define filename and filepath + $dataTime = Get-Date -Format 'yyyy-M-d_h-m' + $vcName = vcName($Data) + $filename = 'compreport_' + $vcName + $dataTime + '.html' + $filePath = $Dir + $filename + #save report + $content |Out-File -FilePath $filePath -Encoding utf8| Out-Null + info ("Report " + "'" + $Dir + $filename + "'" + " has been created!") +} + +Function Generate_SummaryReport($Data, $Dir) { + info ("Generating compatibility summary report...") + $content = $summaryHead + $vcCount = $Data.length + $barsWidth = 45 / ($vcCount+1) + $content += 'var barsWidth = {0};' -f $barsWidth + # get vCName arry and host count + $vcNameArray = @() + foreach ($DCResource in $Data) { + $vcNameArray += $DCResource.DCResource[0].vcname + } + + $content += "var vCname = [" + foreach ($vc in $vcNameArray) { + $content += '"{0}",' -f $vc + } + $content += "];" + # Count Compatible or unpgrade + $compatibleCountFormat = '[' + $mayNotCompatibleCountFormat = '[' + $UnabletoUpgradeCountFormat = '[' + foreach ($VCResource in $Data) { + $checkVersion = $VCResource.checkRelease + $compatibleCount = 0 + $notcompatibleCount = 0 + $UnabletoUpgradeCount = 0 + foreach ($DCResource in $VCResource.DCResource) { + foreach ($HostResourceOne in $DCResource.HostResource) { + foreach ($OneDevice in $HostResourceOne.ComponentResource) { + $flagcompatible = 0 + # if($checkVersion){ + # if(-not($OneDevice.upgrade)){ + # $flagcompatible = 'null' + # break + # } + # } + #whether compatible + if ($OneDevice.status -ne 'Compatible') { + $flagcompatible = 0 + break + } + else { + $flagcompatible = 1 + } + #whether upgrade + } + + if ($flagcompatible -eq 1) { + $compatibleCount += 1 + } + elseif($flagcompatible -eq 0){ + $notcompatibleCount += 1 + } + + elseif($flagcompatible -eq 'null') { + $UnabletoUpgradeCount += 1 + } + } + } + $compatibleCountFormat += $compatibleCount + $compatibleCountFormat += ',' + $mayNotCompatibleCountFormat += $notcompatibleCount + $mayNotCompatibleCountFormat += ',' + $UnabletoUpgradeCountFormat += $UnabletoUpgradeCount + $UnabletoUpgradeCountFormat += ',' + } + $compatibleCountFormat += ',]' + $mayNotCompatibleCountFormat += ',]' + $UnabletoUpgradeCountFormat += ']' + + $dataDict = [Ordered]@{} + + if (-not(checkVersion($Data))) { + $content += 'var lengendSeries = ["Compatible","May Not Compatible"];' + $content += $hostCountHead + + $dataDict.Insert(0, "Compatible", $compatibleCountFormat) + $dataDict.Insert(1, "May Not Compatible", $mayNotCompatibleCountFormat) + } + else { + $content += 'var lengendSeries = ["Compatible","May Not Compatible","Unable to upgrade"];' + $content += $hostCountHead + + $dataDict.Insert(0, "Compatible", $compatibleCountFormat) + $dataDict.Insert(1, "May Not Compatible", $mayNotCompatibleCountFormat) + $dataDict.Insert(2, "Unable to upgrade", $UnabletoUpgradeCountFormat) + } + [System.Collections.IEnumerator]$dataDict = $dataDict.Keys.GetEnumerator(); + $formatContent = formatHostCountGraphic $dataDict + + $content += $formatContent + $content += $hostCountRest + + + # Host Compatibility + $compatibleCount = 0 + $mayNotcompatibleCount = 0 + $unableUpgradeCount = 0 + foreach ($VCResource in $Data) { + foreach ($DCResource in $VCResource.DCResource) { + foreach ($HostResourceOne in $DCResource.HostResource) { + foreach ($OneDevice in $HostResourceOne.ComponentResource) { + #whether compatible + $flagcompatible = 0 + # if ($checkVersion){ + # if (-not($OneDevice.upgrade)){ + # $flagcompatible = 'null' + # break + # } + # } + if ($OneDevice.status -ne 'Compatible') { + $flagcompatible = 0 + break + } + else { + $flagcompatible = 1 + } + + } + if ($flagcompatible -eq 1) { + $compatibleCount += 1 + } + elseif ($flagcompatible -eq 0) { + $mayNotcompatibleCount += 1 + } + elseif ($flagcompatible -eq 'null') { + $unableUpgradeCount += 1 + } + } + } + } + + if (-not(checkVersion($Data))) { + $content += "var seriesCount = {'Compatible':$compatibleCount, 'May Not Compatible':$mayNotcompatibleCount,};" + $content += "var lengendSeries = ['Compatible','May Not Compatible'];" + $content += "var catalog = [ + {value:seriesCount['Compatible'], name:'Compatible'}, + {value:seriesCount['May Not Compatible'], name:'May Not Compatible'}, + ];" + $content += "var colors = [colorsC,colorsM];" + } + else { + $content += "var seriesCount = {'Compatible':$compatibleCount, 'May Not Compatible':$mayNotcompatibleCount,'Unable to Upgrade':$unableUpgradeCount};" + $content += "var lengendSeries = ['Compatible','May Not Compatible','Unable to Upgrade'];" + $content += "var catalog = [ + {value:seriesCount['Compatible'], name:'Compatible'}, + {value:seriesCount['May Not Compatible'], name:'May Not Compatible'}, + {value:seriesCount['Unable to Upgrade'], name:'Unable to Upgrade'}, + ];" + $content += "var colors = [colorsC,colorsM,colorsU];" + } + + $content += $hostCompatible + + + #Host Model Compatibility by vCenter + if (-not(checkVersion($Data))) { + $serverSource = "[['series', 'Compatible', 'May Not Compatible',]," + } + else { + $serverSource = "[['series', 'Compatible','May Not compatible','No Upgrade Path']," + } + + foreach ($VCResource in $Data) { + $compatibleCount = 0 + $mayNotCompatibleCount = 0 + $unableUpgradeCount = 0 + $checkVersion = $VCResource.checkRelease + foreach ($DCResourceOne in $VCResource.DCResource) { + foreach ($HostResourceOne in $DCResourceOne.HostResource) { + $flagcompatible = 0 + foreach ($ComoenentResourceOne in $HostResourceOne.ComponentResource) { + #whether compatible + if ($ComoenentResourceOne.type -eq 'Server') { + # if ($checkVersion) { + # if (-not($ComoenentResourceOne.upgrade)) { + # $flagcompatible = 'null' + # break + # } + # } + if ($ComoenentResourceOne.status -ne 'Compatible') { + $flagcompatible = 0 + } + else { + $flagcompatible = 1 + } + break + + } + } + if ($flagcompatible -eq 1) { + $compatibleCount += 1 + } + elseif ($flagcompatible -eq 0) { + $mayNotcompatibleCount += 1 + } + elseif ($flagcompatible -eq 'null') { + $unableUpgradeCount += 1 + } + } + } + if (-not $checkVersion) { + $serverSource += '["{0}",{1},{2}],' -f $DCResourceOne.vcname, $compatibleCount, $mayNotCompatibleCount + } + else { + $serverSource += '["{0}",{1},{2},{3}],' -f $DCResourceOne.vcname, $compatibleCount, $mayNotCompatibleCount, $unableUpgradeCount + } + } + $serverSource += '];' + $content += 'var serverSource = {0}' -f $serverSource + $content += $hostModelCompatibleHead + + if (-not $checkVersion) { + $colorsArray = 'colorsC', 'colorsM' + } + else { + $colorsArray = 'colorsC', 'colorsM', 'colorsU' + } + foreach ($colors in $colorsArray) { + $content += $hostModelCompatibleBody + $content += "color:$colors}," + } + $content += $hostModelCompatibleRest + + #count IO Device compatibility by vCenter + if (-not(checkVersion($Data))) { + $ioSource = "[['series', 'Compatible', 'May Not Compatible',]," + } + else { + $ioSource = "[['series', 'Compatible','May Not Compatible','No Upgrade Path',]," + } + + foreach ($VCResource in $Data) { + $compatibleCount = 0 + $mayNotCompatibleCount = 0 + $unableUpgradeCount = 0 + $checkVersion = $VCResource.checkRelease + foreach ($DCResourceOne in $VCResource.DCResource) { + foreach ($HostResourceOne in $DCResourceOne.HostResource) { + $flagcompatible = 0 + foreach ($ComoenentResourceOne in $HostResourceOne.ComponentResource) { + if ($ComoenentResourceOne.type -eq 'IO Device') { + # if ($checkVersion) { + # if (-not($ComoenentResourceOne.upgrade)) { + # $flagcompatible = 'null' + # } + # } + if ($ComoenentResourceOne.status -ne 'Compatible') { + $flagcompatible = 0 + } + else { + $flagcompatible = 1 + } + + if ($flagcompatible -eq 1) { + $compatibleCount += 1 + } + elseif ($flagcompatible -eq 0) { + $mayNotCompatibleCount += 1 + } + elseif ($flagcompatible -eq 'null') { + $unableUpgradeCount += 1 + } + } + } + + } + } + if (-not $checkVersion) { + $ioSource += '["{0}",{1},{2}],' -f $DCResourceOne.vcname, $compatibleCount, $mayNotCompatibleCount + } + else { + $ioSource += '["{0}",{1},{2},{3}],' -f $DCResourceOne.vcname, $compatibleCount, $mayNotCompatibleCount, $unableUpgradeCount + } + } + + $ioSource += '];' + $content += 'var ioSource = {0}' -f $ioSource + $content += $ioCompatibleHead + if (-not $checkVersion) { + $colorsArray = 'colorsC', 'colorsM' + } + else { + $colorsArray = 'colorsC', 'colorsM', 'colorsU' + } + foreach ($colors in $colorsArray) { + $content += $ioCompatibleBody + $content += "color:$colors}," + } + $content += $ioCompatibleRest + + $dataTime = Get-Date -Format 'yyyy-M-d_h-m' + $vcName = vcName($Data) + $filename = 'sumreport_' + $vcName + $dataTime + '.html' + $filePath = $Dir + $filename + # Out-put a html report + $content |Out-File -FilePath $filePath -Encoding utf8| Out-Null + info ("Report " + "'" + $Dir + $filename + "'" + " has been created!") +} + +Function Generate_CsvReport($Data, $Dir) { + info("Generating compatibility csv report") + #define header + $content = '' + $content += "VC," + $content += "DataCenter," + $content += "Host," + $content += "Type," + $content += "Model Name," + $content += "Vendor," + if (-not(checkVersion($Data))) { + $content += "Installed Release," + } + else { + $content += "Checked Release," + } + $content += "Compatible Status," + $content += "Hardware Detail," + $content += "Comments," + $content += 'VCG Link,' + $content += "`n" + + #formate content + foreach ($VCResource in $Data) { + $checkVersion = $VCResource.checkRelease + foreach ($DCResourceOne in $VCResource.DCResource) { + foreach ($HostResourceOne in $DCResourceOne.HostResource) { + $installVersion = $HostResourceOne.version + foreach ($ComoenentResourceOne in $HostResourceOne.ComponentResource) { + if ($DCResourceOne.vcname -ne 'null') { + $content += "{0}," -f $DCResourceOne.vcname + } + else { + $content += "{0}," -f '/' + } + #DataCenterDetail + if ($DCResourceOne.dcname -ne 'null') { + $content += "{0}," -f $DCResourceOne.dcname + } + else { + $content += "{0}," -f '/' + } + #Host + $content += "{0}," -f $HostResourceOne.hostname + #Type + $content += "{0}," -f $ComoenentResourceOne.type + #Model Name + $content += '"{0}",' -f $ComoenentResourceOne.model + #Vendor + $content += '"{0}",' -f $ComoenentResourceOne.vendor + if (-not $checkVersion) { + #Installed Release + $content += '"{0}",' -f $installVersion + } + else { + $content += '"{0}",' -f $checkVersion + } + #Status + $content += '"{0}",' -f (formatStatus($ComoenentResourceOne.status)) + #CompatibleHardware + if ($ComoenentResourceOne.type -eq 'IO Device') { + $CompatibleHardware = "'PCI ID:{0}, Driver:{1} {2}" -f $ComoenentResourceOne.pciid, $ComoenentResourceOne.Driver, $ComoenentResourceOne.DriverVersion + } + else { + $CompatibleHardware = "'CPU: {0}(Feature:{1}) BIOS:{2}" -f $ComoenentResourceOne.cpumodel, $ComoenentResourceOne.cpufeatureid, $ComoenentResourceOne.biosversion + } + $content += '"{0}",' -f $CompatibleHardware + + #Comments + + if ($ComoenentResourceOne.Warnings.Count -gt 0) { + $Comments = $ComoenentResourceOne.Warnings + } + else { + $Comments ='N/A' + } + + $content += '"{0}",' -f $Comments + + #VCG Link + $VCGLink = '' + foreach ($link in $ComoenentResourceOne.VcgLink) { + $VCGLink += $link + $VCGLink += ' ' + } + $content += '"{0}",' -f $VCGLink + $content += "`n" + } + } + } + } + + #define filename and path + $dataTime = Get-Date -Format 'yyyy-M-d_h-m' + $vcName = vcName($Data) + $filename = 'compreport_' + $vcName + $dataTime + '.csv' + $filePath = $Dir + $filename + #save csv report + info ("Report " + "'" + $Dir + $filename + "'" + " has been created!") + $content |Out-File -FilePath $filePath -Encoding utf8| Out-Null + return $content +} +Function refactorData ($data) { + $DCResource,$flag = refactorDC $data + $data,$flag = refactorVC $DCResource + return $data, $true +} + +Function refactorDC($data) { + $DCResource = @() + $HostResource = @() + $HR = @{} + $DC = @{} + + $ReData = $data + + $HR.__type__ = $ReData[0].__type__ + $HR.vcname = $ReData[0].vcname + $HR.dcname = $ReData[0].dcname + $HR.hostname = $ReData[0].hostname + $HR.apitype = $ReData[0].apitype + $HR.powerstatus = $ReData[0].powerstatus + $HR.version = $ReData[0].version + $HR.fullname = $ReData[0].fullname + $HR.connectionstatus = $ReData[0].connectionstatus + $HR.ComponentResource = $ReData[0].ComponentResource + $HostResource += $HR # HostResource = [{'hostname':'10.110.126.170'}] + $DC.dcname = $ReData[0].dcname #$DC={'dcname':'ha-datacenter'} + $DC.vcname = $ReData[0].vcname + $DC.HostResource = $HostResource #$DC={'dcname':'ha-datacenter','HostResource':[{'hostname':'10.110.126.170'}]} + $DC.checkRelease = $ReData[0].checkRelease + + $DCResource += $DC #$DCResource = [{'dcname':'ha-datacenter','HostResource':[{'hostname':'10.110.126.170'},]}] + $dcname = $ReData[0].dcname + $vcname = $ReData[0].vcname + $DcIndex = 0 + for ($i = 1; $i -lt $ReData.Count; $i++) { + $temp = $ReData[$i] + $HR = @{} + if ($temp.dcname -eq $dcname -and $temp.vcname -eq $vcname) { + $HR.__type__ = $temp.__type__ + $HR.vcname = $temp.vcname + $HR.dcname = $temp.dcname + $HR.hostname = $temp.hostname + $HR.apitype = $temp.apitype + $HR.powerstatus = $temp.powerstatus + $HR.version = $temp.version + $HR.fullname = $temp.fullname + $HR.connectionstatus = $temp.connectionstatus + $HR.ComponentResource = $temp.ComponentResource + $DCResource[$DcIndex].HostResource += $HR + } + else { + $DcIndex += 1 + $DCResource += @{} #$DCResource = [{'dcname':'ha-datacenter','HostResource':[{'hostname':'10.110.126.170'},{'hostname':'10.110.126.171'}]},{}] + $DCResource[$DcIndex].dcname = $temp.dcname # [{'dcname':'ha-datacenter','HostResource':[{'hostname':'10.110.126.170'},{'hostname':'10.110.126.171'}]},{'dcname':'hw-datacenter'}] + $DCResource[$DcIndex].vcname = $temp.vcname + $DCResource[$DcIndex].checkRelease = $temp.checkRelease + $DCResource[$DcIndex].HostResource = @() # [{'dcname':'ha-datacenter','HostResource':[{'hostname':'10.110.126.170'},{'hostname':'10.110.126.171'}]},{'dcname':'hw-datacenter','HostResource':[]}] + $HR = @{} + $HR.__type__ = $temp.__type__ + $HR.vcname = $temp.vcname + $HR.dcname = $temp.dcname + $HR.hostname = $temp.hostname + $HR.apitype = $temp.apitype + $HR.powerstatus = $temp.powerstatus + $HR.version = $temp.version + $HR.fullname = $temp.fullname + $HR.connectionstatus = $temp.connectionstatus + $HR.ComponentResource = $temp.ComponentResource + $DCResource[$DcIndex].HostResource += $HR # [{'dcname':'ha-datacenter','HostResource':[{'hostname':'10.110.126.170'},{'hostname':'10.110.126.171'}]},{'dcname':'hw-datacenter','HostResource':[{'hostname':'10.110.126.173'}]}] + $dcname = $temp.dcname + $vcname = $temp.vcname + } + } + return $DCResource,$true + # return $DCResource +} + +Function refactorVC ($data) { + $VCResource = @() + $DCResource = @() + $VC = @{} + $DCResource += $data[0] + $VC.DCResource = $DCResource + $VC.hostname = $data[0].vcName + $VC.checkRelease = $data[0].checkRelease + + $VCResource += $VC + $vcname = $data[0].vcname + $VcIndex = 0 + for ($i = 1 ; $i -lt $data.Count; $i++){ + $temp = $data[$i] + if ($vcname -eq $temp.vcname) { + $VCResource[$VcIndex].DCResource += $temp + } + else { + $VcIndex += 1 + $DCResource = @() + $VC = @{} + $DCResource += $temp + $VC.hostname = $temp.vcName + $VC.DCResource = $DCResource + $VC.checkRelease = $temp.checkRelease + $VCResource += $VC + $vcname = $temp.vcname + } + } + return $VCResource,$true +} + +Function vcName($Data) { + $vcName = '' + foreach ($VCResource in $Data) { + $vcName += $VCResource.hostname + $vcName += '_' + } + return $vcName +} + +Function checkVersion($Data) { + foreach ($VCResource in $Data) { + $checkVersion = $VCResource.checkRelease + return $checkVersion + } +} + +Function formatStatus($status) { + if ($status -eq 'MayNotBeCompatible') { + return 'May Not Be Compatible' + } + else { + return $status + } +} + +Function formatHostCountGraphic($dataDict) { + while ($dataDict.MoveNext()) { + $items = $dataDict.Key + + if ($items -eq 'Compatible') { + $colors = 'colorsC' + } + elseif ($items -eq 'May Not Compatible') { + $colors = 'colorsM' + } + elseif ($items -eq 'Unable to upgrade') { + $colors = 'colorsU' + } + + $content += $hostCountBody + $items = "'{0}'" -f $items + $content += 'name: {0},' -f $items + $content += 'data: {0},' -f $dataDict.Value + $content += 'color: {0},' -f $colors + $content += '},' + } + + return $content +} + + +#Detail report +$generalHead = @' + + + + + + + + + ESXi Compatible Report + + + +'@ + +$generalBodyBase = @' +

[WARNING] The compatible status may not be fully accurate, please validate it with the official VMware Compatibility Guide

+ + +
+ + + + + + + + + + +'@ + +$generalBodyRest = @' + + + + + + +'@ + +$generalFooter = @' + +
VCDataCenterHostTypeModel NameVendorCompatible StatusHardware DetailComments
+
+ + + +'@ + + +#Summary report +$summaryHead = @' + + + + + Summary Report + + + + + + + +
+
+
+
+
+ +
+ + +'@ + diff --git a/Modules/VMware.VCGChecker/Get-VCGHWInfo.ps1 b/Modules/VMware.VCGChecker/Get-VCGHWInfo.ps1 new file mode 100644 index 0000000..229608f --- /dev/null +++ b/Modules/VMware.VCGChecker/Get-VCGHWInfo.ps1 @@ -0,0 +1,310 @@ +<# +Copyright 2018 VMware, Inc. All rights reserved. +#> + +# Class to manage Host resources +Class HostResource { + [VMware.VimAutomation.Types.VMHost] $vmhost + [string] $vcname + [string] $clustername + [string] $dcname + [string] $hostname + [string] $apitype + [string] $powerstatus + [string] $productname + [string] $version + [string] $fullname + [string] $connectionstatus + [string] $checkRelease + [int] $port + [Array] $ComponentResource = @() + [Array] $JsonProperties = @('__type__', 'dcname', 'vcname','clustername','hostname', 'apitype', + 'powerstatus', 'productname', 'version', 'fullname', 'connectionstatus','checkRelease') + + HostResource( + [VMware.VimAutomation.Types.VMHost] $vmhost) { + $this.vmhost = $vmhost + $view =$vmhost|Get-View + $vCenter_IP = $view.Summary.ManagementServerIp + if($vCenter_IP){ + $this.vcname =$vCenter_IP + $this.dcname = (Get-Datacenter -VMHost $vmhost).Name + $this.clustername = (Get-Cluster -VMHost $vmhost).Name + }else{ + $this.vcname =$this.vmhost.Name + } + $this.hostname = $this.vmhost.Name + $summary = $this.vmhost.ExtensionData.Summary + $this.powerstatus = $summary.runtime.powerState + $this.connectionstatus = $summary.runtime.connectionState + $this.apitype = $summary.Config.Product.apiType + $this.fullname = $summary.Config.Product.FullName + $this.version = $summary.Config.Product.version + $this.productname = $summary.Config.Product.licenseProductName + $this.port = 443 + } + + [Array] query_components() { + if ($this.ComponentResource.Count -eq 0) { + # Get server info + for($count_retry=0;$count_retry -lt 3;$count_retry ++){ + try{ + $svrResoure = [ServerResource]::new() + $svrResoure.set_data($this.vmhost) + $this.ComponentResource += $svrResoure + break + }catch{ + error('query components server for '+$this.vmhost.Name +' error, retry it ' +($count_retry+1) +' times') + } + } + # Get PCI devices + for($count_retry=0;$count_retry -lt 3;$count_retry ++){ + try{ + $this.query_pcidevices() + break + }catch{ + error('query components pcidevice for '+$this.vmhost.Name +' error, retry it ' +($count_retry+1) +' times') + if($count_retry -eq 2){ + error('query components pcidevice for '+$this.vmhost.Name +' faild') + } + } + } + } + return $this.ComponentResource + } + + [void] query_pcidevices() { + $EsxCliV2 = Get-EsxCli -V2 -VMHost $this.vmhost + $AllPciDevice = $EsxCliV2.hardware.pci.list.invoke() + foreach ($Pci in $AllPciDevice) { + # Ignore USB controllers, iLO/iDRAC devices + if ($Pci.DeviceName -like "*USB*" -or $Pci.DeviceName -like "*iLO*" -or $Pci.DeviceName -like "*iDRAC*") { + continue + } + # Get the NICs and storage adapters. + # We found NIC and storage adapters usually have module ID other than 0 or 1 + $pciDevice = [IoDeviceResource]::new() + if ($Pci.ModuleID -ne 0 -and $Pci.ModuleID -ne -1) { + if (!$this.is_pcidevice_exist($Pci)) { + $pciDevice.set_data($Pci, $EsxCliV2) + $this.ComponentResource += $pciDevice + } + } + } + } + + [boolean] is_pcidevice_exist($device) { + foreach ($pci in $this.ComponentResource) { + if ($pci.psobject.TypeNames[0] -eq "IoDeviceResource") { + $vid = [String]::Format("{0:x4}", [int]$device.VendorID) + $did = [String]::Format("{0:x4}", [int]$device.DeviceID) + $svid = [String]::Format("{0:x4}", [int]$device.SubVendorID) + $ssid = [String]::Format("{0:x4}", [int]$device.SubDeviceID) + if ($pci.vid -eq $vid -and $pci.did -eq $did -and + $pci.svid -eq $svid -and $pci.ssid -eq $ssid) { + return $true + } + } + } + return $false + } + + [object] to_jsonobj() { + $Json = $this | Select-Object -Property $this.JsonProperties + $ComponentChildren = @() + $this.ComponentResource | ForEach-Object {$ComponentChildren += $_.to_jsonobj()} + $Json | Add-Member -Name "ComponentResource" -Value $ComponentChildren -MemberType NoteProperty + + return $Json + } + + [string] get_host_status() { + if ($this.powerstatus -and $this.powerstatus -ne 'unknown') { + return $this.powerstatus + } + if ($this.connectionstatus) { + return ("Server " + $this.connectionstatus) + } + else { + return "Server status is unknown" + } + } + + [string] get_prompt_name() { + if ($this.apitype) { + $start = $this.apitype + } + else { + $start = "Host" + } + return $start + " " + $this.hostname + } +} + + +# Class to manage server resources +Class ServerResource { + [string] $type + [string] $model + [string] $vendor + [string] $biosversion + [string] $cpumodel + [string] $cpufeatureid + [string] $uuid + [string] $status + [array] $matchResult + [array] $warnings + [string] $vcgLink + [array] $updateRelease + + [VMware.VimAutomation.Types.VMHost] $vmhost + [Array] $JsonProperties = @('__type__','type', 'model', 'vendor', 'biosversion', + 'cpumodel', 'cpufeatureid', 'uuid','status','matchResult','warnings','vcgLink','updateRelease') + + + [void] set_data( + [VMware.VimAutomation.Types.VMHost] $vmhost) { + $this.vmhost = $vmhost + $this.type = "Server" + $this.model = $this.vmhost.Model + $this.vendor = $this.vmhost.Manufacturer + $this.biosversion = $this.vmhost.ExtensionData.Hardware.BiosInfo.BiosVersion + $this.cpumodel = $this.vmhost.ProcessorType + $cpuFeature = $this.vmhost.ExtensionData.Hardware.CpuFeature + if ($cpuFeature -and $cpuFeature.Count -gt 2) { + $this.cpufeatureid = $this.vmhost.ExtensionData.Hardware.CpuFeature[1].Eax + } + $this.uuid = $this.vmhost.ExtensionData.Hardware.systeminfo.uuid + } + + [object] to_jsonobj() { + return $this | Select-Object -Property $this.JsonProperties + } + +} + +# Class to manage each IO device +Class IoDeviceResource { + + [string] $type + [string] $model + [string] $deviceid + [string] $device + [string] $comptype + [string] $vid + [string] $did + [string] $svid + [string] $ssid + [string] $pciid + [string] $vendor + [string] $driver + [string] $driverversion + [string] $firmware + [string] $status + [array] $matchResult + [array] $warnings + [string] $vcgLink + [array] $updateRelease + + [Array] $JsonProperties = @('__type__','type', 'model', 'deviceid', 'device', + 'comptype', 'vid', 'did', 'svid', 'ssid', 'pciid', + 'vendor', 'driver', 'driverversion', 'firmware','status','matchResult','warnings','vcgLink','updateRelease') + + [void] set_data( + [object] $pci, + [object] $EsxCli) { + $this.type = "IO Device" + $this.model = $Pci.DeviceName + $this.deviceid = $pci.Address + $this.device = $pci.VMKernelName + $this.vid = [String]::Format("{0:x4}", [int]$Pci.VendorID) + $this.did = [String]::Format("{0:x4}", [int]$Pci.DeviceID) + $this.svid = [String]::Format("{0:x4}", [int]$Pci.SubVendorID) + $this.ssid = [String]::Format("{0:x4}", [int]$Pci.SubDeviceID) + $this.pciid = $this.vid + ":" + $this.did + ":" + $this.svid + ":" + $this.ssid + $this.vendor = $pci.VendorName + $this.driver = $Pci.ModuleName + $this.driverversion = "N/A" + $this.firmware = "N/A" + + + # Set component type and driverversion, firmware + if ($this.device -match 'nic') { + $arg = @{} + $arg['nicname'] = $this.device + $nic = $EsxCli.network.nic.get.invoke($arg) + $this.comptype = "Physical NIC" + $this.driverversion = $nic.driverinfo.Version + $this.firmware = $nic.driverinfo.FirmwareVersion + } + elseif ($this.device -match 'hba') { + $arg = @{} + $arg['module'] = $this.driver + $module = $EsxCli.system.module.get.invoke($arg) + $this.comptype = "Storage Adapter" + $this.driverversion = $module.Version + } + } + + [object] to_jsonobj() { + return $this | Select-Object -Property $this.JsonProperties + } + + [string] get_id_detail() { + return $this.driver + " (PCIId:" + $this.pciid + ")" + } +} + +# Class to manage IO device group +Class IoDeviceResourceGroup { + [Array] $iodevices = @() + [Array] $nics = @() + [Array] $adapters = @() + + [void] append_nic([IODeviceResource] $nic) { + $this.iodevices += $nic + $this.nics += $nic + } + + [void] append_storage_adapter([IODeviceResource] $adapter) { + $this.iodevices += $adapter + $this.adapters += $adapter + } + + [boolean] has_nics() { + return $this.nics.Count > 0 + } + + [boolean] has_storage_adapters() { + return $this.adapters.Count > 0 + } + +} + + +# +# Collect hardware inventory data from all the hosts +# +Function Get-VCGHWInfo { + Param( + [Parameter(Mandatory=$true)] $vmHosts + ) + # Collect the hardware data + $Data = @() + foreach($vmHost in $vmHosts) { + $vm = [HostResource]::new($vmHost) + try { + info ("Collecting hardware data from " + $vm.hostname) + $null = $vm.query_components() + if($vm.powerstatus -eq 'poweredOn' -and $vm.connectionstatus -eq 'connected'){ + $Data += $vm + info ("Collecting hardware data from " + $vm.hostname +' success') + } + } + catch { + error ("Failed to collect hardware data from " + $vm.hostname) + } + } + + return $Data +} \ No newline at end of file diff --git a/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 b/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 new file mode 100644 index 0000000..0f7a5de --- /dev/null +++ b/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 @@ -0,0 +1,168 @@ +$Uuid = [guid]::NewGuid() +$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" +$Headers.add("x-request-id", $Uuid) +$Headers.add("x-api-toolid", "180209100001") +$Headers.add("x-api-key", "SJyb8QjK2L") +$Url_Perfix = 'https://apigw.vmware.com/m4/compatibility/v1' +$Url = $Url_Perfix + "/compatible/servers/search?" +$UrlPci = $Url_Perfix + "/compatible/iodevices/search?" +$apiQurryDict=@{} + +# +# Ping remote api server. +# +Function PingApiServer(){ + $apiServerIp='apigw.vmware.com' + $results =Test-NetConnection $apiServerIp -InformationLevel 'Quiet' + if($results -ne $true){ + error ("Failed to access VMware Compatibility API, + Unable to use comparison function, only view basic hardware information; + you can use 'Get-VCGHWInfo -g ' create hardware json, + then use 'Check-VCGStatus -f ' load hardware json file to comapre when connect an available network") + Exit(1) + } +} + +# +# Get the web request. +# +Function Get-WebRequest($VCGurl) { + try { + $req = Invoke-WebRequest -Headers $Headers -Uri $VCGUrl -ErrorVariable $err -UseBasicParsing + } + catch { + if ($err[0].errorrecord.exception.response) { + error ("WebReponse code:" + $err[0].errorrecord.exception.response.statuscode.value__) + error ($exitScript) + Exit(1) + } + else { + error ("Failed to check " + $type + " data for " + $HostResource.hostname) + error ("Failed to access VMware Compatibility API, please check your Internet connection or contact VMware Compatibility API administrator") + error ("Exit the script") + Exit(1) + } + } + return $req +} + +Function Get-RemoteApiTitleString([object]$device,$EsxiVersion){ + if ($device.type -eq 'Server') { + $Title = $device.model + $device.vendor + $device.cpufeatureid + $device.biosversion +$EsxiVersion + } + else{ + $Title = $device.vid + $device.did + $device.Svid + $device.Ssid + $EsxiVersion + } + return $Title +} + +Function Get-ResponseFromApi([object]$device,$EsxiVersion){ + if ($device.type -eq 'Server') { + $VCGUrl = $Url + "model=" + $device.model + "&releaseversion=" + $EsxiVersion ` + + "&vendor=" + $device.vendor + "&cpuFeatureId=" + $device.cpufeatureid ` + + "&bios=" + $device.biosversion + debug ("Model:" + $device.model) + debug ("VCG Url:" + $VCGUrl) + $Headers.GetEnumerator() | ForEach-Object {debug ("Req Header:" + $_.key + ":" + $_.value)} + $request = Get-WebRequest $VCGUrl + $Response = ConvertFrom-Json -InputObject $request -Erroraction 'silentlycontinue' + } + elseif ($device.type -eq 'IO Device') { + $VCGUrl = $UrlPci + "vid=0X" + $device.vid + "&did=0X" + $device.did + "&svid=0X" + $device.Svid ` + + "&ssid=0X" + $device.Ssid + "&releaseversion=" + $EsxiVersion ` + + "&driver=" + $device.Driver + "&driverversion=" + $device.driverversion + "&firmware=N/A" + debug ("Model:" + $device.model) + debug ("VCG Url:" + $VCGUrl) + $Headers.GetEnumerator() | ForEach-Object {debug ("Req Header:" + $_.key + ":" + $_.value)} + $request = Get-WebRequest $VCGUrl + $Response = ConvertFrom-Json -InputObject $request -Erroraction 'silentlycontinue' + } + return $Response +} +# +# Get the data from api +# +Function Get-VCGData($HostResource) { + foreach ($device in $HostResource.ComponentResource) { + if ($HostResource.checkRelease) { + $EsxiVersion = $HostResource.checkRelease + } + else { + $EsxiVersion = $HostResource.version + } + $temp=0 + $title=Get-RemoteApiTitleString $device $EsxiVersion + if($apiQurryDict.Count -eq 0){ + $Response= Get-ResponseFromApi $device $EsxiVersion + $apiQurryDict.Add($title,$Response) + }else{ + foreach($onetitle in $apiQurryDict.keys){ + if($onetitle -eq $title){ + $Response= $apiQurryDict[$onetitle] + $temp=1 + break + } + } + if($temp -eq 0){ + $Response= Get-ResponseFromApi $device $EsxiVersion + $apiQurryDict.Add($title,$Response) + } + } + + if ($Response.matches) { + foreach ($match in $Response.matches) { + $device.vcgLink += [string]$match.vcgLink + } + } + else { + foreach ($potentialMatche in $Response.potentialMatches) { + $device.vcgLink += [string]$potentialMatche.vcgLink + } + } + $device.status = [string]$Response.searchResult.status + $device.matchResult = [string]$Response.searchResult.matchResult + $device.warnings = $Response.searchResult.warnings + $device.updateRelease = [string]$Response.searchOption.foundRelease + } +} + +# +# Send the hardware data to VCG API and handle returned result +# +Function Get-DataFromRemoteApi([object]$servers) { + info ("Checking hardware compatibility result with VMware Compatibility Guide API...") + info ("This may take a few minutes depending on your network.") + for ($idx = 0; $idx -lt $servers.Count; $idx++) { + $server = $servers[$idx] + $i = $idx + 1 + info ([string]$i + "/" + [string]$servers.Count + " - Checking hardware compatibility results for " + $server.hostname) + if (!$server -or $server.ComponentResource.Count -eq 0) { + error('Failed to get the hardware info.') + Exit(1) + } + Get-VCGData $server + } + return $servers +} + +Function Get-VCGStatus{ + Param( + [Parameter(Mandatory=$true)] $Data, + [Parameter(Mandatory=$false)] $Version + ) + $checkRelease = $Version + PingApiServer + + foreach ($vmHost in $Data) { + # $vmHost|add-member -Name "checkRelease" -value $checkRelease -MemberType NoteProperty -Force + $vmHost.checkRelease=$checkRelease + } + + $results = Get-DataFromRemoteApi($Data) + if ($results.Count -eq 0) { + error ("Failed to get compatibility results. No report will be generated") + error ("Exit the script") + Exit(1) + } + return $results +} \ No newline at end of file diff --git a/Modules/VMware.VCGChecker/README.md b/Modules/VMware.VCGChecker/README.md new file mode 100644 index 0000000..a38c064 --- /dev/null +++ b/Modules/VMware.VCGChecker/README.md @@ -0,0 +1,41 @@ +# About +This module is designed to ease the work of collecting hardware inventory data and compare it with VMware's official VCG data. Before deploying vSphere, it is required to validate your physical machines with VCG to make sure all the devices in your physical machines are compatible with the vSphere version you want to install. It is a time-consuming and painful experience to collect hardware/driver/firmware data from all of the machines, especially when you have a huge number of machines in your data center. + +# How It Works +By using this module, it will automate the data collection and comparison work. + +When running the module, it will connect to the target vCenter or ESXi to read the hardware data. It is a read-only operation and nothing on the target hosts will be changed. There is almost no impact on the machine's performance as the read operation takes just few seconds. + +The module will then send your hardware inventory data to VMware's offical website to conduct a compatibility check. The result will be 'Compatible', 'May not be compatible' or 'Not compatible'. +* Compatible: the hardware is compatible with the given vSphere release. Link to that VCG page will be provided. +* May not be compatible: manual check is required to confirm the compatibility status of this hardware. A few potential matching VCG records will be provided. +* Not compatible: the hardware is not compatible with the given vSphere release. + +After the checking is completed, the module will generate reports in different formats for your review and future use. A summary view in html will give you an overview of your machines compatibility status; an html file with device details to view each device/driver/firmware you have, their compatibility with vSphere version you specified and links to the corresponding VCG documents online; a csv file with device details to allow customization on report in Excel or by your own tool. + +# Usage +Considering many data center may have control on internet access, we create 3 cmdlets to meet various situations. +* Get-VCGHWInfo: cmdlet to collect hardware info +* Get-VCGStatus: cmdlet to check hardware compatibility by query VCG website +* Export-VCGReport: cmdlet to export the summary/html/csv reports + +1. You need to first import this module after you import PowerCLI module +PS> Import-Module + +2. Connect to the target vSphere hosts using Connect-VIServer and get VMHosts +PS> Connect-VIServer -Server -User -Password +PS> $vmhosts = Get-VMHost + +3. Collect the hardware data +PS> $hwdata = Get-VCGHWInfo -vmHosts $vmhosts +Note: if you don't have internet access, you need to connect your client to internet before proceeding to the next step. + +4. Specify the target vSphere release you want to check and submit the hardware data to VMware website +PS> $vcgdata= Get-VCGStatus -Data $hwdata -Version '' + +5. Save the compatibility reports +PS> Export-VCGReport -Data $vcgdata -Dir + +# Known Limitation +* The module is not able to get the firmware version for HBA devices. +* The module is not able to get the HDD/SSD data. \ No newline at end of file diff --git a/Modules/VMware.VCGChecker/Save-VCGJsonFile.ps1 b/Modules/VMware.VCGChecker/Save-VCGJsonFile.ps1 new file mode 100644 index 0000000..785fc00 --- /dev/null +++ b/Modules/VMware.VCGChecker/Save-VCGJsonFile.ps1 @@ -0,0 +1,17 @@ +Function Save-VCGJsonFile{ + Param( + [Parameter(Mandatory=$true)] $FileName, + [Parameter(Mandatory=$true)] $Data, + [Parameter(Mandatory=$true)] $Dir + ) + $json = @() + $Data | ForEach-Object { $json += $_.to_jsonobj()} + + if (!(Test-Path $Dir)) { + New-Item -Type directory -Confirm:$false -Path $Dir -Force |Out-Null + } + + $Path= $Dir + '\' + $FileName + '.json' + info ("Saving data to " + $Path) + ConvertTo-Json -Depth 10 -Compress $json | Out-File -encoding 'UTF8' -FilePath $Path +} \ No newline at end of file diff --git a/Modules/VMware.VCGChecker/VMware.VCGChecker.psd1 b/Modules/VMware.VCGChecker/VMware.VCGChecker.psd1 new file mode 100644 index 0000000..12493af --- /dev/null +++ b/Modules/VMware.VCGChecker/VMware.VCGChecker.psd1 @@ -0,0 +1,90 @@ +# +# Module manifest for module 'VMware.VCGChecker' +# +# Generated by: fdai@vmware.com, zhangta@vmware.com, linweij@vmware.com +# +# Generated on: 11/15/18 +# + +@{ + + # Script module or binary module file associated with this manifest. + # RootModule = 'VMware.VCGChecker.psm1' + + # Version number of this module. + ModuleVersion = '1.0.0' + + # Supported PSEditions + # CompatiblePSEditions = @() + + # ID used to uniquely identify this module + # GUID = '' + + # Author of this module + Author = 'Frank Dai, Tao Zhang, Linwei Jiang' + + # Company or vendor of this module + CompanyName = 'VMware' + + # Copyright statement for this module + Copyright = '(c) 2018 VMware. All rights reserved.' + + # Description of the functionality provided by this module + Description = 'PowerShell Module for Checking Hardware Compatibility Status' + + RequiredModules = @('VMware.VimAutomation.Core') + + # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess + NestedModules = 'Get-VCGHWInfo.ps1','Get-VCGStatus.ps1','Export-VCGReport.ps1', 'Save-VCGJsonFile.ps1', 'logger.ps1' + + # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. + FunctionsToExport = 'Get-VCGHWInfo', 'Get-VCGStatus', 'Export-VCGReport', 'Save-VCGJsonFile' + # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. + CmdletsToExport = @() + + # Variables to export from this module + VariablesToExport = '*' + + # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. + AliasesToExport = @() + + # DSC resources to export from this module + # DscResourcesToExport = @() + + # List of all modules packaged with this module + # ModuleList = @() + + # List of all files packaged with this module + # FileList = @() + + # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. + PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + + } # End of PrivateData hashtable + + # HelpInfo URI of this module + # HelpInfoURI = '' + + # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. + # DefaultCommandPrefix = '' + + } \ No newline at end of file diff --git a/Modules/VMware.VCGChecker/logger.ps1 b/Modules/VMware.VCGChecker/logger.ps1 new file mode 100644 index 0000000..686611a --- /dev/null +++ b/Modules/VMware.VCGChecker/logger.ps1 @@ -0,0 +1,112 @@ +<# +Copyright 2018 VMware, Inc. All rights reserved. + +#> + +# Messages +$HEADER_OK = "[OK] " +$HEADER_INFO = "[INFO] " +$HEADER_WARNING = "[WARNING] " +$HEADER_ERR = "[ERROR] " + +Class DebugLog +{ + # Static variables of the logger class + static [string] $CAFILE_PATH = "./.certs/" + + [boolean] $debug + [string] $logfile + + DebugLog() + { + $this.debug = $false + $this.logfile = $null + if (!(Test-Path $this::CAFILE_PATH)) + { + New-Item -Type directory -Confirm:$false -Path $this::CAFILE_PATH + } + } + + [void] SetDebug( + [boolean] $debug, + [string] $hostname + ){ + if (!$hostname) {$hostname = ''} + $this.debug = $debug + if ($this.debug) + { + $this.logfile = $this::CAFILE_PATH + $hostname + [DateTime]::Now.ToString("_yyyy-MM-dd_HH-mm") + ".log" + }else{ + $this.logfile = $null + } + } + + [void] log_vars( + [string] $message, + [object] $var + ){ + $this.log($message + $var) + } + + [void] log( + [string] $message + ){ + if (!$this.debug -or !$this.logfile) {return} + try + { + $message | Out-File $this.logfile -Append + }catch { + Out-Host -InputObject ("[Exception] Failed to write to a logfile: " + $this.logfile) + Out-Host -InputObject $_ + } + } +} + +Function debug_vars( + [string] $message, + [object] $var) +{ + $logger.log_vars($message, $var) +} + +Function debug( + [string] $message) +{ + $logger.log($message) +} + +Function vcglog( + [string] $message, + [string] $header="") +{ + $msg = $header + $message + $logger.log($msg) + Out-Host -InputObject $msg +} + +Function ok( + [string] $message) +{ + vcglog $message $HEADER_OK +} + +Function warning( + [string] $message) +{ + vcglog $message $HEADER_WARNING +} + +Function info( + [string] $message) +{ + vcglog $message $HEADER_INFO +} + +Function error( + [string] $message) +{ + vcglog $message $HEADER_ERR +} + +$logger = [DebugLog]::new() +$logger.SetDebug($true, "vcc-debug") \ No newline at end of file From 82b32df293620cc3c4cb41dfac018467ac21e143 Mon Sep 17 00:00:00 2001 From: Adrian Moseley Date: Wed, 21 Nov 2018 16:53:37 -0600 Subject: [PATCH 043/175] Verbage for DeleteFromDisk if False --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c58e1c0..06527a4 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -10171,7 +10171,7 @@ $deleteSpec.DeleteFromDisk = $DeleteFromDisk $deleteSpec.ArchivePersistentDisk = $false #Delete the machines -write-host "Attempting to Delete:" +if($DeleteFromDisk){write-host "Attempting to Delete:"}else{write-host "Attempting to remove from inventory:"} Write-Output ($deleteMachine.base.Name -join "`n") $bye = $machineService.Machine_DeleteMachines($services,$deleteMachine.id,$deleteSpec) From 1ce8b927ce6d890013df8036ed8167f42df6f424 Mon Sep 17 00:00:00 2001 From: dzl84 Date: Tue, 27 Nov 2018 17:17:46 +0800 Subject: [PATCH 044/175] Update README.md --- Modules/VMware.VCGChecker/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Modules/VMware.VCGChecker/README.md b/Modules/VMware.VCGChecker/README.md index a38c064..1aa9a58 100644 --- a/Modules/VMware.VCGChecker/README.md +++ b/Modules/VMware.VCGChecker/README.md @@ -19,23 +19,23 @@ Considering many data center may have control on internet access, we create 3 cm * Get-VCGStatus: cmdlet to check hardware compatibility by query VCG website * Export-VCGReport: cmdlet to export the summary/html/csv reports -1. You need to first import this module after you import PowerCLI module +1. You need to first import this module after you import PowerCLI module PS> Import-Module -2. Connect to the target vSphere hosts using Connect-VIServer and get VMHosts -PS> Connect-VIServer -Server -User -Password +2. Connect to the target vSphere hosts using Connect-VIServer and get VMHosts +PS> Connect-VIServer -Server <server> -User <username> -Password <password> PS> $vmhosts = Get-VMHost -3. Collect the hardware data -PS> $hwdata = Get-VCGHWInfo -vmHosts $vmhosts +3. Collect the hardware data +PS> $hwdata = Get-VCGHWInfo -vmHosts $vmhosts Note: if you don't have internet access, you need to connect your client to internet before proceeding to the next step. -4. Specify the target vSphere release you want to check and submit the hardware data to VMware website -PS> $vcgdata= Get-VCGStatus -Data $hwdata -Version '' +4. Specify the target vSphere release you want to check and submit the hardware data to VMware website +PS> $vcgdata= Get-VCGStatus -Data $hwdata -Version '<release>' -5. Save the compatibility reports -PS> Export-VCGReport -Data $vcgdata -Dir +5. Save the compatibility reports +PS> Export-VCGReport -Data $vcgdata -Dir <dir> # Known Limitation * The module is not able to get the firmware version for HBA devices. -* The module is not able to get the HDD/SSD data. \ No newline at end of file +* The module is not able to get the HDD/SSD data. From 3e28c516a7b88bd3964876a04c66743a9e09501a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maik=20St=C3=BCbner?= Date: Fri, 30 Nov 2018 09:12:16 +0100 Subject: [PATCH 045/175] removed brake for issue vmware#74 --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 1 - 1 file changed, 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c58e1c0..d407e2d 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -7173,7 +7173,6 @@ function Get-HVMachine { $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 From 560739222dae6638a0612f33cfa3607b62b8da72 Mon Sep 17 00:00:00 2001 From: Zhoulin Dai Date: Fri, 30 Nov 2018 17:15:13 +0800 Subject: [PATCH 046/175] Fix bugs --- .../VMware.VCGChecker/Export-VCGReport.ps1 | 14 ++++++------ Modules/VMware.VCGChecker/Get-VCGStatus.ps1 | 2 +- Modules/VMware.VCGChecker/README.md | 22 +++++++++---------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Modules/VMware.VCGChecker/Export-VCGReport.ps1 b/Modules/VMware.VCGChecker/Export-VCGReport.ps1 index 1b1253d..3774915 100644 --- a/Modules/VMware.VCGChecker/Export-VCGReport.ps1 +++ b/Modules/VMware.VCGChecker/Export-VCGReport.ps1 @@ -140,10 +140,10 @@ Function Generate_HtmlReport($Data, $Dir) { $dataTime = Get-Date -Format 'yyyy-M-d_h-m' $vcName = vcName($Data) $filename = 'compreport_' + $vcName + $dataTime + '.html' - $filePath = $Dir + $filename + $filePath = $Dir + '\' + $filename #save report $content |Out-File -FilePath $filePath -Encoding utf8| Out-Null - info ("Report " + "'" + $Dir + $filename + "'" + " has been created!") + info ("Report " + "'" + $filePath + "'" + " has been created!") } Function Generate_SummaryReport($Data, $Dir) { @@ -440,10 +440,10 @@ Function Generate_SummaryReport($Data, $Dir) { $dataTime = Get-Date -Format 'yyyy-M-d_h-m' $vcName = vcName($Data) $filename = 'sumreport_' + $vcName + $dataTime + '.html' - $filePath = $Dir + $filename + $filePath = $Dir + '\' + $filename # Out-put a html report $content |Out-File -FilePath $filePath -Encoding utf8| Out-Null - info ("Report " + "'" + $Dir + $filename + "'" + " has been created!") + info ("Report " + "'" + $filePath + "'" + " has been created!") } Function Generate_CsvReport($Data, $Dir) { @@ -542,9 +542,9 @@ Function Generate_CsvReport($Data, $Dir) { $dataTime = Get-Date -Format 'yyyy-M-d_h-m' $vcName = vcName($Data) $filename = 'compreport_' + $vcName + $dataTime + '.csv' - $filePath = $Dir + $filename + $filePath = $Dir + '\' + $filename #save csv report - info ("Report " + "'" + $Dir + $filename + "'" + " has been created!") + info ("Report " + "'" + $filePath + "'" + " has been created!") $content |Out-File -FilePath $filePath -Encoding utf8| Out-Null return $content } @@ -785,7 +785,7 @@ $summaryHead = @' height: 100%; background-size: cover; background-repeat: no-repeat; - background-image: url(https://myvmware.workspaceair.com:443/SAAS/jersey/manager/api/images/510495) + background-image: url(https://myvmware.workspaceair.com/SAAS/jersey/manager/api/images/520470) } #header{ margin: 0 auto; diff --git a/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 b/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 index 0f7a5de..426d6ce 100644 --- a/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 +++ b/Modules/VMware.VCGChecker/Get-VCGStatus.ps1 @@ -13,7 +13,7 @@ $apiQurryDict=@{} # Function PingApiServer(){ $apiServerIp='apigw.vmware.com' - $results =Test-NetConnection $apiServerIp -InformationLevel 'Quiet' + $results =Test-Connection $apiServerIp -Quiet if($results -ne $true){ error ("Failed to access VMware Compatibility API, Unable to use comparison function, only view basic hardware information; diff --git a/Modules/VMware.VCGChecker/README.md b/Modules/VMware.VCGChecker/README.md index a38c064..79007d4 100644 --- a/Modules/VMware.VCGChecker/README.md +++ b/Modules/VMware.VCGChecker/README.md @@ -19,23 +19,23 @@ Considering many data center may have control on internet access, we create 3 cm * Get-VCGStatus: cmdlet to check hardware compatibility by query VCG website * Export-VCGReport: cmdlet to export the summary/html/csv reports -1. You need to first import this module after you import PowerCLI module -PS> Import-Module +1. You need to first import this module after you import PowerCLI module +PS> Import-Module <path_to_VMware.VCGChecker.psd1> -2. Connect to the target vSphere hosts using Connect-VIServer and get VMHosts -PS> Connect-VIServer -Server -User -Password +2. Connect to the target vSphere hosts using Connect-VIServer and get VMHosts +PS> Connect-VIServer -Server <server> -User <username> -Password <password> PS> $vmhosts = Get-VMHost -3. Collect the hardware data -PS> $hwdata = Get-VCGHWInfo -vmHosts $vmhosts +3. Collect the hardware data +PS> $hwdata = Get-VCGHWInfo -vmHosts $vmhosts Note: if you don't have internet access, you need to connect your client to internet before proceeding to the next step. -4. Specify the target vSphere release you want to check and submit the hardware data to VMware website -PS> $vcgdata= Get-VCGStatus -Data $hwdata -Version '' +4. Specify the target vSphere release you want to check and submit the hardware data to VMware website +PS> $vcgdata= Get-VCGStatus -Data $hwdata -Version '<release>' -5. Save the compatibility reports -PS> Export-VCGReport -Data $vcgdata -Dir +5. Save the compatibility reports +PS> Export-VCGReport -Data $vcgdata -Dir <dir> # Known Limitation * The module is not able to get the firmware version for HBA devices. -* The module is not able to get the HDD/SSD data. \ No newline at end of file +* The module is not able to get the HDD/SSD data. From 971e4aeec76e83c7b43ae2694428cd2c1a68d9f9 Mon Sep 17 00:00:00 2001 From: jpgrall <33696799+jpgrall@users.noreply.github.com> Date: Fri, 30 Nov 2018 09:43:40 -0600 Subject: [PATCH 047/175] Adding file path to Get-ContentLibraryItemFiles Adding the support to display the actual path of the file on the datastore. This is useful when needing to mount an ISO that is hosted on the Content Library. Also, replaced references of "Libary" to "Library" throughout. --- Modules/ContentLibrary/ContentLibrary.psm1 | 113 +++++++++++---------- 1 file changed, 60 insertions(+), 53 deletions(-) diff --git a/Modules/ContentLibrary/ContentLibrary.psm1 b/Modules/ContentLibrary/ContentLibrary.psm1 index 318b999..d85bd54 100644 --- a/Modules/ContentLibrary/ContentLibrary.psm1 +++ b/Modules/ContentLibrary/ContentLibrary.psm1 @@ -20,12 +20,12 @@ [Parameter(Mandatory=$false)][String]$LibraryName ) - $contentLibaryService = Get-CisService com.vmware.content.library - $libaryIDs = $contentLibaryService.list() + $contentLibraryService = Get-CisService com.vmware.content.library + $LibraryIDs = $contentLibraryService.list() $results = @() - foreach($libraryID in $libaryIDs) { - $library = $contentLibaryService.get($libraryID) + foreach($libraryID in $LibraryIDs) { + $library = $contentLibraryService.get($libraryID) # Use vCenter REST API to retrieve name of Datastore that is backing the Content Library $datastoreService = Get-CisService com.vmware.vcenter.datastore @@ -108,18 +108,18 @@ Function Get-ContentLibraryItems { [Parameter(Mandatory=$false)][String]$LibraryItemName ) - $contentLibaryService = Get-CisService com.vmware.content.library - $libaryIDs = $contentLibaryService.list() + $contentLibraryService = Get-CisService com.vmware.content.library + $LibraryIDs = $contentLibraryService.list() $results = @() - foreach($libraryID in $libaryIDs) { - $library = $contentLibaryService.get($libraryId) + foreach($libraryID in $LibraryIDs) { + $library = $contentLibraryService.get($libraryId) if($library.name -eq $LibraryName) { - $contentLibaryItemService = Get-CisService com.vmware.content.library.item - $itemIds = $contentLibaryItemService.list($libraryID) + $contentLibraryItemService = Get-CisService com.vmware.content.library.item + $itemIds = $contentLibraryItemService.list($libraryID) foreach($itemId in $itemIds) { - $item = $contentLibaryItemService.get($itemId) + $item = $contentLibraryItemService.get($itemId) if(!$LibraryItemName) { $itemResult = [pscustomobject] @{ @@ -179,28 +179,34 @@ Function Get-ContentLibraryItemFiles { [Parameter(Mandatory=$false)][String]$LibraryItemName ) - $contentLibaryService = Get-CisService com.vmware.content.library - $libaryIDs = $contentLibaryService.list() + $contentLibraryService = Get-CisService com.vmware.content.library + $libraryIDs = $contentLibraryService.list() $results = @() - foreach($libraryID in $libaryIDs) { - $library = $contentLibaryService.get($libraryId) + foreach($libraryID in $libraryIDs) { + $library = $contentLibraryService.get($libraryId) if($library.name -eq $LibraryName) { - $contentLibaryItemService = Get-CisService com.vmware.content.library.item - $itemIds = $contentLibaryItemService.list($libraryID) - + $contentLibraryItemService = Get-CisService com.vmware.content.library.item + $itemIds = $contentLibraryItemService.list($libraryID) + $DatastoreID = $library.storage_backings.datastore_id.Value + $Datastore = get-datastore -id "Datastore-$DatastoreID" + foreach($itemId in $itemIds) { - $itemName = ($contentLibaryItemService.get($itemId)).name - $contenLibraryItemFileSerice = Get-CisService com.vmware.content.library.item.file - $files = $contenLibraryItemFileSerice.list($itemId) + $itemName = ($contentLibraryItemService.get($itemId)).name + $contentLibraryItemFileSerice = Get-CisService com.vmware.content.library.item.file + $files = $contentLibraryItemFileSerice.list($itemId) + $contentLibraryItemStorageService = Get-CisService com.vmware.content.library.item.storage foreach($file in $files) { + $filepath = $contentLibraryItemStorageService.get($itemId, $($file.name)).storage_uris.AbsolutePath.split("/")[5..7] -join "/" + $fullfilepath = "[$($datastore.name)] $filepath" if(!$LibraryItemName) { $fileResult = [pscustomobject] @{ Name = $file.name; Version = $file.version; Size = $file.size; Stored = $file.cached; + Path = $fullfilepath; } $results+=$fileResult } else { @@ -210,6 +216,7 @@ Function Get-ContentLibraryItemFiles { Version = $file.version; Size = $file.size; Stored = $file.cached; + Path = $fullfilepath; } $results+=$fileResult } @@ -245,12 +252,12 @@ Function Set-ContentLibrary { [Parameter(Mandatory=$false)][Switch]$JSONPersistenceDisabled ) - $contentLibaryService = Get-CisService com.vmware.content.library - $libaryIDs = $contentLibaryService.list() + $contentLibraryService = Get-CisService com.vmware.content.library + $LibraryIDs = $contentLibraryService.list() $found = $false - foreach($libraryID in $libaryIDs) { - $library = $contentLibaryService.get($libraryId) + foreach($libraryID in $LibraryIDs) { + $library = $contentLibraryService.get($libraryId) if($library.name -eq $LibraryName) { $found = $true break @@ -361,12 +368,12 @@ Function Remove-SubscribedContentLibrary { [Parameter(Mandatory=$true)][String]$LibraryName ) - $contentLibaryService = Get-CisService com.vmware.content.library - $libaryIDs = $contentLibaryService.list() + $contentLibraryService = Get-CisService com.vmware.content.library + $LibraryIDs = $contentLibraryService.list() $found = $false - foreach($libraryID in $libaryIDs) { - $library = $contentLibaryService.get($libraryId) + foreach($libraryID in $LibraryIDs) { + $library = $contentLibraryService.get($libraryId) if($library.name -eq $LibraryName) { $found = $true break @@ -460,12 +467,12 @@ Function Remove-LocalContentLibrary { [Parameter(Mandatory=$true)][String]$LibraryName ) - $contentLibaryService = Get-CisService com.vmware.content.library - $libaryIDs = $contentLibaryService.list() + $contentLibraryService = Get-CisService com.vmware.content.library + $LibraryIDs = $contentLibraryService.list() $found = $false - foreach($libraryID in $libaryIDs) { - $library = $contentLibaryService.get($libraryId) + foreach($libraryID in $LibraryIDs) { + $library = $contentLibraryService.get($libraryId) if($library.name -eq $LibraryName) { $found = $true break @@ -493,49 +500,49 @@ Function Copy-ContentLibrary { =========================================================================== .DESCRIPTION This function copies all library items from one Content Library to another - .PARAMETER SourceLibaryName + .PARAMETER SourceLibraryName The name of the source Content Library to copy from - .PARAMETER DestinationLibaryName + .PARAMETER DestinationLibraryName The name of the desintation Content Library to copy to .PARAMETER DeleteSourceFile Whther or not to delete library item from the source Content Library after copy .EXAMPLE - Copy-ContentLibrary -SourceLibaryName Foo -DestinationLibaryName Bar + Copy-ContentLibrary -SourceLibraryName Foo -DestinationLibraryName Bar .EXAMPLE - Copy-ContentLibrary -SourceLibaryName Foo -DestinationLibaryName Bar -DeleteSourceFile $true + Copy-ContentLibrary -SourceLibraryName Foo -DestinationLibraryName Bar -DeleteSourceFile $true #> param( - [Parameter(Mandatory=$true)][String]$SourceLibaryName, - [Parameter(Mandatory=$true)][String]$DestinationLibaryName, + [Parameter(Mandatory=$true)][String]$SourceLibraryName, + [Parameter(Mandatory=$true)][String]$DestinationLibraryName, [Parameter(Mandatory=$false)][Boolean]$DeleteSourceFile=$false ) - $sourceLibraryId = (Get-ContentLibrary -LibraryName $SourceLibaryName).Id + $sourceLibraryId = (Get-ContentLibrary -LibraryName $SourceLibraryName).Id if($sourceLibraryId -eq $null) { - Write-Host -ForegroundColor red "Unable to find Source Content Library named $SourceLibaryName" + Write-Host -ForegroundColor red "Unable to find Source Content Library named $SourceLibraryName" exit } - $destinationLibraryId = (Get-ContentLibrary -LibraryName $DestinationLibaryName).Id + $destinationLibraryId = (Get-ContentLibrary -LibraryName $DestinationLibraryName).Id if($destinationLibraryId -eq $null) { - Write-Host -ForegroundColor Red "Unable to find Destination Content Library named $DestinationLibaryName" + Write-Host -ForegroundColor Red "Unable to find Destination Content Library named $DestinationLibraryName" break } - $sourceItemFiles = Get-ContentLibraryItems -LibraryName $SourceLibaryName + $sourceItemFiles = Get-ContentLibraryItems -LibraryName $SourceLibraryName if($sourceItemFiles -eq $null) { - Write-Host -ForegroundColor red "Unable to retrieve Content Library Items from $SourceLibaryName" + Write-Host -ForegroundColor red "Unable to retrieve Content Library Items from $SourceLibraryName" break } - $contentLibaryItemService = Get-CisService com.vmware.content.library.item + $contentLibraryItemService = Get-CisService com.vmware.content.library.item foreach ($sourceItemFile in $sourceItemFiles) { # Check to see if file already exists in destination Content Library - $result = Get-ContentLibraryItems -LibraryName $DestinationLibaryName -LibraryItemName $sourceItemFile.Name + $result = Get-ContentLibraryItems -LibraryName $DestinationLibraryName -LibraryItemName $sourceItemFile.Name if($result -eq $null) { # Create CopySpec - $copySpec = $contentLibaryItemService.Help.copy.destination_create_spec.Create() + $copySpec = $contentLibraryItemService.Help.copy.destination_create_spec.Create() $copySpec.library_id = $destinationLibraryId $copySpec.name = $sourceItemFile.Name $copySpec.description = $sourceItemFile.Description @@ -545,7 +552,7 @@ Function Copy-ContentLibrary { # Perform Copy try { Write-Host -ForegroundColor Cyan "Copying" $sourceItemFile.Name "..." - $copyResult = $contentLibaryItemService.copy($UniqueChangeId, $sourceItemFile.Id, $copySpec) + $copyResult = $contentLibraryItemService.copy($UniqueChangeId, $sourceItemFile.Id, $copySpec) } catch { Write-Host -ForegroundColor Red "Failed to copy" $sourceItemFile.Name $Error[0] @@ -556,7 +563,7 @@ Function Copy-ContentLibrary { if($DeleteSourceFile) { try { Write-Host -ForegroundColor Magenta "Deleteing" $sourceItemFile.Name "..." - $deleteResult = $contentLibaryItemService.delete($sourceItemFile.Id) + $deleteResult = $contentLibraryItemService.delete($sourceItemFile.Id) } catch { Write-Host -ForegroundColor Red "Failed to delete" $sourceItemFile.Name $Error[0] @@ -570,7 +577,7 @@ Function Copy-ContentLibrary { if($DeleteSourceFile) { try { Write-Host -ForegroundColor Magenta "Deleteing" $sourceItemFile.Name "..." - $deleteResult = $contentLibaryItemService.delete($sourceItemFile.Id) + $deleteResult = $contentLibraryItemService.delete($sourceItemFile.Id) } catch { Write-Host -ForegroundColor Red "Failed to delete" $sourceItemFile.Name break @@ -597,7 +604,7 @@ Function New-VMTX { The name of the VM Template in Content Library .PARAMETER Description Description of the VM template - .PARAMETER LibaryName + .PARAMETER LibraryName The name of the Content Library to clone to .PARAMETER FolderName The name of vSphere Folder (Defaults to Workloads for VMC) @@ -696,4 +703,4 @@ Function New-VMFromVMTX { Write-Host "`nDeploying new VM $NewVMName from VMTX Template $VMTXName ..." $results = $vmtxService.deploy($vmtxId,$vmtxDeploySpec) -} \ No newline at end of file +} \ No newline at end of file From 7c7f8d3fbf49e04ed6e3e72dbac104067091af5c Mon Sep 17 00:00:00 2001 From: jpgrall <33696799+jpgrall@users.noreply.github.com> Date: Fri, 30 Nov 2018 09:55:46 -0600 Subject: [PATCH 048/175] Update ContentLibrary.psm1 Adding logic incase backing isn't a datastore. --- Modules/ContentLibrary/ContentLibrary.psm1 | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Modules/ContentLibrary/ContentLibrary.psm1 b/Modules/ContentLibrary/ContentLibrary.psm1 index d85bd54..9a8574b 100644 --- a/Modules/ContentLibrary/ContentLibrary.psm1 +++ b/Modules/ContentLibrary/ContentLibrary.psm1 @@ -198,8 +198,14 @@ Function Get-ContentLibraryItemFiles { $contentLibraryItemStorageService = Get-CisService com.vmware.content.library.item.storage foreach($file in $files) { - $filepath = $contentLibraryItemStorageService.get($itemId, $($file.name)).storage_uris.AbsolutePath.split("/")[5..7] -join "/" - $fullfilepath = "[$($datastore.name)] $filepath" + if($contentLibraryItemStorageService.get($itemId, $($file.name)).storage_backing.type -eq "DATASTORE"){ + $filepath = $contentLibraryItemStorageService.get($itemId, $($file.name)).storage_uris.AbsolutePath.split("/")[5..7] -join "/" + $fullfilepath = "[$($datastore.name)] $filepath" + } + else{ + $fullfilepath = "UNKNOWN" + } + if(!$LibraryItemName) { $fileResult = [pscustomobject] @{ Name = $file.name; @@ -703,4 +709,4 @@ Function New-VMFromVMTX { Write-Host "`nDeploying new VM $NewVMName from VMTX Template $VMTXName ..." $results = $vmtxService.deploy($vmtxId,$vmtxDeploySpec) -} \ No newline at end of file +} From 937f21345150233d6ce15d2ca0f5cc781f63e4ab Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Sat, 1 Dec 2018 17:15:38 -0700 Subject: [PATCH 049/175] Update VMware.HV.Helper.psm1 Added functions to starting and starting Instant Clone maintenance operations on a host for Horizon 7.x --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 115 +++++++++++++++++- 1 file changed, 114 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c58e1c0..9eb2254 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11478,4 +11478,117 @@ function Get-HVlicense { [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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase,Get-HVlicense,Set-HVlicense +function Start-HVMaintenance { + <# + .Synopsis + Puts a host in instant clone maintanence mode + + .DESCRIPTION + Puts a host in instant clone maintanence mode + + + .PARAMETER Host + ESXi Host name to modify the InstantClone.Maintenance attribute + + .EXAMPLE + Start-HvMaintenance -Host + + .NOTES + Author : Jack McMichael + Author email : @jackwmc4 / jackwmc4@gmail.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.6 + PowerCLI Version : PowerCLI 11 + PowerShell Version : 5.1 + #> + + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High')] + + param( + [Parameter(Mandatory=$true, Position=0)] + [string]$Server, + + [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 { + if ((Get-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance").Value -eq ""){ + Set-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance" -Value "1" | Out-Null + } + while ((Get-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance").Value -ne "2") { + shouldcontinue() + Start-Sleep -Seconds 10 + } + [System.gc]::collect() + } +} + +function Stop-HVMaintenance { + <# + .Synopsis + Takes a host out of instant clone maintanence mode + + .DESCRIPTION + Takes a host out of instant clone maintanence mode + + + .PARAMETER Host + ESXi Host name to clear the InstantClone.Maintenance attribute + + .EXAMPLE + Stop-HvMaintenance -Host + + .NOTES + Author : Jack McMichael + Author email : @jackwmc4 / jackwmc4@gmail.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.6 + PowerCLI Version : PowerCLI 11 + PowerShell Version : 5.1 + #> + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High')] + + param( + [Parameter(Mandatory=$true, Position=0)] + [string]$Server, + + [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 { + if (-not (Get-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance").Value -eq "") { + Set-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance" -Value "" | Out-Null + } + Set-VMhost $Host -State Connected | Out-Null + [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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase,Get-HVlicense,Set-HVlicense, Start-HVMaintenance, Stop-HVMaintenance \ No newline at end of file From f9953ec994ebfe26997656d5292b90c12d9c8e95 Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Sat, 1 Dec 2018 20:55:50 -0700 Subject: [PATCH 050/175] Update VMware.HV.Helper.psm1 Added Set-HVInstantCloneMaintenance function. --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 111 ++++++------------ 1 file changed, 38 insertions(+), 73 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 9eb2254..3f0fe30 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11478,20 +11478,26 @@ function Get-HVlicense { [System.gc]::collect() } -function Start-HVMaintenance { +function Set-HVInstantCloneMaintenance { <# .Synopsis - Puts a host in instant clone maintanence mode + Enable or disable instant clone maintanence mode .DESCRIPTION - Puts a host in instant clone maintanence mode + Toggles a host in instant clone maintanence mode. Specify the VMHost name and enable or disable to toggle. + .PARAMETER VMHost + ESXi Host name to modify the InstantClone.Maintenance attribute - .PARAMETER Host - ESXi Host name to modify the InstantClone.Maintenance attribute - + .PARAMETER Enable + Enable Instant Clone maintenance mode. + + .PARAMETER Disable + Disable Instant Clone maintenance mode + .EXAMPLE - Start-HvMaintenance -Host + Set-HvInstantCloneMaintenance -VMHost -Enable $true + Set-HvInstantCloneMaintenance -VMHost -Disable $true .NOTES Author : Jack McMichael @@ -11510,11 +11516,20 @@ function Start-HVMaintenance { param( [Parameter(Mandatory=$true, Position=0)] - [string]$Server, + [string] + $VMHost, + + [Parameter(Mandatory = $false)] + [boolean] + $Enable, + + [Parameter(Mandatory = $false)] + [boolean] + $Disable, [Parameter(Mandatory = $false)] $HvServer = $null - ) + ) begin { $services = Get-ViewAPIService -hvServer $hvServer @@ -11525,70 +11540,20 @@ function Start-HVMaintenance { } process { - if ((Get-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance").Value -eq ""){ - Set-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance" -Value "1" | Out-Null + if ($Enable) { + if ((Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -eq ""){ + Set-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance" -Value "1" | Out-Null + } + while ((Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -ne "2") { + Start-Sleep -Seconds 10 + } + } elseif ($Disable) { + if (-not (Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -eq "") { + Set-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance" -Value "" | Out-Null + } + Set-VMhost $VMHost -State Connected | Out-Null } - while ((Get-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance").Value -ne "2") { - shouldcontinue() - Start-Sleep -Seconds 10 - } - [System.gc]::collect() + [System.gc]::collect() } } - -function Stop-HVMaintenance { - <# - .Synopsis - Takes a host out of instant clone maintanence mode - - .DESCRIPTION - Takes a host out of instant clone maintanence mode - - - .PARAMETER Host - ESXi Host name to clear the InstantClone.Maintenance attribute - - .EXAMPLE - Stop-HvMaintenance -Host - - .NOTES - Author : Jack McMichael - Author email : @jackwmc4 / jackwmc4@gmail.com - Version : 1.0 - - ===Tested Against Environment==== - Horizon View Server Version : 7.6 - PowerCLI Version : PowerCLI 11 - PowerShell Version : 5.1 - #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High')] - - param( - [Parameter(Mandatory=$true, Position=0)] - [string]$Server, - - [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 { - if (-not (Get-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance").Value -eq "") { - Set-Annotation -Entity (Get-VMHost -Name $Server) -CustomAttribute "InstantClone.Maintenance" -Value "" | Out-Null - } - Set-VMhost $Host -State Connected | Out-Null - [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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase,Get-HVlicense,Set-HVlicense, Start-HVMaintenance, Stop-HVMaintenance \ No newline at end of file +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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase,Get-HVlicense,Set-HVlicense, Set-HVInstantCloneMaintenance \ No newline at end of file From 53b8377c5395c2b699881a09084679561bccd7a2 Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Sat, 1 Dec 2018 20:59:06 -0700 Subject: [PATCH 051/175] Update VMware.HV.Helper.psm1 --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 3f0fe30..32322e7 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11479,14 +11479,14 @@ function Get-HVlicense { } function Set-HVInstantCloneMaintenance { - <# - .Synopsis + <# + .Synopsis Enable or disable instant clone maintanence mode - - .DESCRIPTION + + .DESCRIPTION Toggles a host in instant clone maintanence mode. Specify the VMHost name and enable or disable to toggle. - .PARAMETER VMHost + .PARAMETER VMHost ESXi Host name to modify the InstantClone.Maintenance attribute .PARAMETER Enable From 4ef4cce5efcc2dce3260058b98e81a71f70f5484 Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Sat, 1 Dec 2018 21:01:25 -0700 Subject: [PATCH 052/175] Update VMware.HV.Helper.psm1 --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 32322e7..4379f31 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11495,19 +11495,19 @@ function Set-HVInstantCloneMaintenance { .PARAMETER Disable Disable Instant Clone maintenance mode - .EXAMPLE + .EXAMPLE Set-HvInstantCloneMaintenance -VMHost -Enable $true Set-HvInstantCloneMaintenance -VMHost -Disable $true - - .NOTES - Author : Jack McMichael - Author email : @jackwmc4 / jackwmc4@gmail.com - Version : 1.0 + + .NOTES + Author : Jack McMichael + Author email : @jackwmc4 / jackwmc4@gmail.com + Version : 1.0 - ===Tested Against Environment==== - Horizon View Server Version : 7.6 - PowerCLI Version : PowerCLI 11 - PowerShell Version : 5.1 + ===Tested Against Environment==== + Horizon View Server Version : 7.6 + PowerCLI Version : PowerCLI 11 + PowerShell Version : 5.1 #> [CmdletBinding( From e5920d40f5069537042f1be5e538f0e8fcb30d2f Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Sat, 1 Dec 2018 21:15:51 -0700 Subject: [PATCH 053/175] Update VMware.HV.Helper.psm1 Updating exports to be more organized --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 4379f31..e42b8e2 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11556,4 +11556,22 @@ function Set-HVInstantCloneMaintenance { [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, Set-HVApplicationIcon, Remove-HVApplicationIcon, Get-HVGlobalSettings, Set-HVGlobalSettings, Set-HVGlobalEntitlement, Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession, Reset-HVMachine, Remove-HVMachine, Get-HVHealth, New-HVPodfederation, Remove-HVPodFederation, Get-HVPodFederation, Register-HVPod, Unregister-HVPod, Set-HVPodFederation,Get-HVSite,New-HVSite,Set-HVSite,Remove-HVSite,New-HVHomeSite,Get-HVHomeSite,Set-HVEventDatabase,Get-HVEventDatabase,Clear-HVEventDatabase,Get-HVlicense,Set-HVlicense, Set-HVInstantCloneMaintenance \ No newline at end of file +# Object related +Export-ModuleMember -Function Get-HVMachine, Get-HVMachineSummary, Get-HVQueryResult, Get-HVQueryFilter, Get-HVInternalName +# RDS Farm related +Export-ModuleMember -Function Get-HVFarmSummary, Start-HVFarm, Start-HVPool, New-HVFarm, Remove-HVFarm, Get-HVFarm, Set-HVFarm, Add-HVRDSServer +# Desktop Pool related +Export-ModuleMember -Function Get-HVPoolSummary, New-HVPool, Remove-HVPool, Get-HVPool, Set-HVPool, Get-HVPoolSpec, Add-HVDesktop +# Entitlement related +Export-ModuleMember -Function New-HVEntitlement,Get-HVEntitlement,Remove-HVEntitlement +Export-ModuleMember -Function Set-HVMachine, Reset-HVMachine, Remove-HVMachine +# Cloud Pod Architecture related +Export-ModuleMember -Function New-HVGlobalEntitlement, Remove-HVGlobalEntitlement, Get-HVGlobalEntitlement, Set-HVGlobalEntitlement, New-HVPodFederation, Remove-HVPodFederation, Get-HVPodFederation, Set-HVPodFederation +Export-ModuleMember -Function Get-HVSite, New-HVSite, New-HVHomeSite, Remove-HVSite, Get-HVHomeSite, Set-HVSite, Register-HVPod, Unregister-HVPod +# Published App related +Export-ModuleMember -Function Get-HVGlobalSettings, Set-HVApplicationIcon, Remove-HVApplicationIcon, Set-HVGlobalSettings +Export-ModuleMember -Function Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession +# Event Database related +Export-ModuleMember -Function Get-HVEventDatabase, Set-HVEventDatabase, Clear-HVEventDatabase, Get-HVEvent, Connect-HVEvent, Disconnect-HVEvent +# Misc/other related +Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance \ No newline at end of file From c7a19c795e2af4bcb578b1710423c14bca62aab0 Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Sun, 2 Dec 2018 17:01:26 -0700 Subject: [PATCH 054/175] Update VMware.HV.Helper.psm1 Changed booleans to switches after looking at other uses in the code. --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index e42b8e2..30336f5 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11520,11 +11520,11 @@ function Set-HVInstantCloneMaintenance { $VMHost, [Parameter(Mandatory = $false)] - [boolean] + [switch] $Enable, [Parameter(Mandatory = $false)] - [boolean] + [switch] $Disable, [Parameter(Mandatory = $false)] From cea57f11d5f72becdb63f4f29c60b04fae720808 Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Tue, 4 Dec 2018 14:05:08 -0700 Subject: [PATCH 055/175] Update VMware.HV.Helper.psm1 Added per feedback --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 30336f5..0a4efe9 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11545,11 +11545,13 @@ function Set-HVInstantCloneMaintenance { Set-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance" -Value "1" | Out-Null } while ((Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -ne "2") { + Write-Host "Instant Clone Maintenance Mode: Enabling for $VMHost...(This could take some time)" Start-Sleep -Seconds 10 } } elseif ($Disable) { if (-not (Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -eq "") { Set-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance" -Value "" | Out-Null + Write-Host "Instant Clone Maintenance Mode: Disabling for $VMHost" } Set-VMhost $VMHost -State Connected | Out-Null } From bd983dcd7fc5a7436de6c6243601d38d62f5ecb4 Mon Sep 17 00:00:00 2001 From: Jack McMichael Date: Wed, 5 Dec 2018 13:00:12 -0700 Subject: [PATCH 056/175] Update VMware.HV.Helper.psm1 Moving messaging so it doesn't repeat over and over. --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 0a4efe9..eee2b67 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11543,9 +11543,9 @@ function Set-HVInstantCloneMaintenance { if ($Enable) { if ((Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -eq ""){ Set-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance" -Value "1" | Out-Null + Write-Host "Instant Clone Maintenance Mode: Enabling for $VMHost...(This could take some time)" } while ((Get-Annotation -Entity (Get-VMHost -Name $VMHost) -CustomAttribute "InstantClone.Maintenance").Value -ne "2") { - Write-Host "Instant Clone Maintenance Mode: Enabling for $VMHost...(This could take some time)" Start-Sleep -Seconds 10 } } elseif ($Disable) { From 76eadeba8a2afcafd9dc96b83e2d5bf3921b968e Mon Sep 17 00:00:00 2001 From: Jase McCarty Date: Fri, 7 Dec 2018 16:11:18 -0700 Subject: [PATCH 057/175] Initial vSAN Encryption Module vSAN Encryption Module --- Modules/VMware.VsanEncryption/README.md | 7 + .../VMware.VsanEncryption.psd1 | Bin 0 -> 5098 bytes .../VMware.VsanEncryption.psm1 | 340 ++++++++++++++++++ 3 files changed, 347 insertions(+) create mode 100644 Modules/VMware.VsanEncryption/README.md create mode 100644 Modules/VMware.VsanEncryption/VMware.VsanEncryption.psd1 create mode 100644 Modules/VMware.VsanEncryption/VMware.VsanEncryption.psm1 diff --git a/Modules/VMware.VsanEncryption/README.md b/Modules/VMware.VsanEncryption/README.md new file mode 100644 index 0000000..8037171 --- /dev/null +++ b/Modules/VMware.VsanEncryption/README.md @@ -0,0 +1,7 @@ +Prerequisites/Steps to use this module: + +1. This module only works for vSphere products that support vSAN Encryption. E.g. vSAN 6.6 and later with a vSAN Enterprise license +2. All the functions in this module only work for KMIP Servers. +3. Install the latest version of Powershell and PowerCLI(11). +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.VsanEncryption/VMware.VsanEncryption.psd1 b/Modules/VMware.VsanEncryption/VMware.VsanEncryption.psd1 new file mode 100644 index 0000000000000000000000000000000000000000..47b0ca30d0fd967f4a1e9ee3b4b69b6b61d2b73d GIT binary patch literal 5098 zcmcgwSx-|@5T57$ikt8N7}*p7O-v;02_PwmzP7iEH+Hj&)foS}`h7D!oO60xX`4z& zxyv~-^UXfz{`tKk1zC|quB0s$8AwB_cxp;XT9Qc(Pd(}5O%3Z^T?zNC$~`ED*xkj> zO+59K@&wc=-u;jcs58*EWK|`Zv@`5(;n&6PKCTsTE@Sr_TtklBJ)MGFNwFg@WJ~t( zdm-C+Iv7bR$UFIod*g7ch%!Y)4MROlw=$5nRF@w)O>0;)+mxVV57a5%c=SU&_2o0@ z_&>vrycIV`NQ$6tV_$6Zx1d;6D;eHbKJ?tc?$>y?4X>6*ekJWrfcX%(DBb+`FPju3-fM`$ zSYv#e<&VIxi8x^nP-El%O|`DfBrE1{4Ngr^Cz6-?9B(fmCxtg+1Rcok!p3#z#|&g1 zTD*}L?eDX4ng@tuoR49cw6X>i>)`6LD9*(YX##6D@RtM#8S$(FjGwO1T9rtrV_joa zupD%8?Y%||)imN#XlLssNMUBt4;|39!Pz3v)r>gf!uVSO%`~ZI1#j^yaAl-7A-@Sa z;_pJ2$tXYSZpOk8dlI?PJ5t=jTg(*NhF+@cPHINmFpo05n+^RWzLT@rYvQ9Vw(M+} znM+pjmxcFy#L?q=3fuobJsz|Fe37&%*K#6vh>ugmh1H26EY_7T3&zYbsQchr#s56d z<)Tj^tBF7BPz~T`#1C+-Lq21k{e!t|^>0m%8^~pUW-Vf;=G?*w zCDqQ%d4u(3fH%ar23rw-RaoIZq2ui7-61enaKF1S+B}ZKsVMR};VT&{3@bdVKc@=z zXx?!aU_WNBqLyxwVkNWgO)BoGqaL-fpVidr600b!)Kbq_H(`Bcy`#O1KIBcVbzSlE zjmK!6vj}NnjSHs`YC$dE!Q$%=z4lOjR0WDMuw|hCx3<)yq!S1$=<*Ry#*@b#Pm^vs zB=$9Qy$-b4(YWz`vl-dt1pUUT&Uq+R-*Ce0Vh$i5c8_Iy$xWak`W~uJ8yzgnnMt0y zLl5o%6??SJ!m+mB;lsvAXHJe5ow2`$8jsX_-pF#&XGMFeam;g!%}Gy>I7Bcj>hXNZ zXCW&Y?aq3|DqyoZE3iAgaW(Gz;VS1ydXc9W`qAhu7K@-8KbLGpCy9Kd6tvSgB;)v9 z-pq4OwCri>obT(zsdf@S7g9^JPF21`BddRmO~x@NIA)eRhk5H1&=c8{LQd4`B;sP# z_*pcOvl}o!`)dEiWFG;U=Q4}jd-$7Gxuo^cRY&I6yn5$3%_5(3KBaT2U)<&~ms#Xq zs_&S)7R&5h>|J3j6Aw>mDP|>`IM@>=pTvCxxEdJ7s+Z;>)<>RSi;;v?aDEilFHfN* zW6I0O%V%ZI&r1TTBcIQIIW``m%(#h4G8!Ji&4YLfNwJ7wLd4jd6jc&MQs*lk=4S- zD##}Iy&s(q=^1_vv1-FBpQhvBInvoke-VsanEncryptionRekey -Cluster "ClusterName" -DeepRekey $true/$false -ReducedRedundancy $true/$false + + #> + + # Set our Parameters + [CmdletBinding()]Param( + [Parameter(Mandatory = $True)][String]$Cluster, + [Parameter(Mandatory = $False)][Boolean]$DeepRekey, + [Parameter(Mandatory = $False)][Boolean]$ReducedRedundancy + ) + + # Get the Cluster + $VsanCluster = Get-Cluster -Name $Cluster + + # Get the vSAN Cluster Configuration View + $VsanVcClusterConfig = Get-VsanView -Id "VsanVcClusterConfigSystem-vsan-cluster-config-system" + + # Get Encryption State + $EncryptedVsan = $VsanVcClusterConfig.VsanClusterGetConfig($VsanCluster.ExtensionData.MoRef).DataEncryptionConfig + + # If vSAN is enabled and it is Encrypted + If($VsanCluster.vSanEnabled -And $EncryptedVsan.EncryptionEnabled){ + + # Get a count of hosts to guarantee reduced redundancy for 2 and 3 node clusters + $HostCount = $VsanCluster | Select @{n="count";e={($_ | Get-VMHost).Count}} + + # If reduced redundancy is specified, or there are less than 4 hosts, force reduced redundancy + If (($ReducedRedundancy -eq $true) -or ($HostCount.Value -lt 4)) { + + } + # Determine Rekey Type for messaging + Switch ($DeepRekey) { + $true { $ReKeyType = "deep"} + default { $ReKeyType = "shallow"} + } + + # Determine Reduced Redundancy for messaging + Switch ($ReducedRedundancy) { + $true { $RRMessage = "with reduced redundancy"} + default { $RRMessage = ""} + } + + # Echo task being performed + Write-Host "Executing $ReKeyType rekey of vSAN Cluster $VsanCluster $RRMessage" + + # Execute the rekeying task + $ReKeyTask = $VsanVcClusterConfig.VsanEncryptedClusterRekey_Task($VsanCluster.ExtensionData.MoRef,$DeepRekey,$ReducedRedundancy) + } +} + +Function Set-VsanEncryptionKms { + <# + .SYNOPSIS + This function will set the KMS to be used with vSAN Encryption + + .DESCRIPTION + This function will set the KMS to be used with vSAN Encryption + + .PARAMETER Cluster + Specifies the Cluster to set the KMS server for + + .PARAMETER KmsCluster + Use to set the KMS Cluster to be used with vSAN Encryption + + .EXAMPLE + C:\PS>Set-VsanEncryptionKms -Cluster "ClusterName" -KmsCluster "vCenter KMS Cluster Entry" + + #> + + # Set our Parameters + [CmdletBinding()]Param( + [Parameter(Mandatory = $True)][String]$Cluster, + [Parameter(Mandatory = $False)][String]$KmsCluster + ) + + # Get the Cluster + $VsanCluster = Get-Cluster -Name $Cluster + + # Get the list of KMS Servers that are included + $KmsClusterList = Get-KmsCluster + + # Was a KMS Cluster Specified? + # Specified: Is it in the list? + # Is it not in the list? + # Not Specified: Present a list + If ($KmsCluster) { + If ($KmsClusterList.Name.Contains($KmsCluster)) { + Write-Host "$KmsCluster In the list, proceeding" -ForegroundColor Green + $KmsClusterProfile = $KmsClusterList | Where-Object {$_.Name -eq $KmsCluster} + } else { + + $Count = 0 + Foreach ($KmsClusterItem in $KmsClusterList) { + Write-Host "$Count) $KmsClusterItem " + $Count = $Count + 1 + } + $KmsClusterEntry = Read-Host -Prompt "$KmsCluster is not valid, please select one of the existing KMS Clusters to use" + Write-Host $KmsClusterList[$KmsClusterEntry] + $KmsClusterProfile = $KmsClusterList[$KmsClusterEntry] + } + } else { + + $Count = 0 + Foreach ($KmsClusterItem in $KmsClusterList) { + Write-Host "$Count) $KmsClusterItem " + $Count = $Count + 1 + } + $KmsClusterEntry = Read-Host -Prompt "No KMS provided, please select one of the existing KMS Clusters to use" + Write-Host $KmsClusterList[$KmsClusterEntry] + $KmsClusterProfile = $KmsClusterList[$KmsClusterEntry] + } + + # Get the vSAN Cluster Configuration View + $VsanVcClusterConfig = Get-VsanView -Id "VsanVcClusterConfigSystem-vsan-cluster-config-system" + + # Get Encryption State + $EncryptedVsan = $VsanVcClusterConfig.VsanClusterGetConfig($VsanCluster.ExtensionData.MoRef).DataEncryptionConfig + + # If vSAN is enabled and it is Encrypted + If($VsanCluster.vSanEnabled -And $EncryptedVsan.EncryptionEnabled){ + + If ($EncryptedVsan.KmsProviderId.Id -eq $KmsClusterProfile.Name) { + # If the Specified KMS Profile is the KMS Profile being used, then don't do anything + Write-Host $EncryptedVsan.KmsProviderId.Id "is already the assigned KMS Cluster Profile, exiting" + } else { + Write-Host "Changing the KMS Profile to $KmsClusterProfile on Cluster $VsanCluster" + + # Setup the KMS Provider Id Specification + $KmsProviderIdSpec = New-Object VMware.Vim.KeyProviderId + $KmsProviderIdSpec.Id = $KmsClusterProfile.Name + + # Setup the Data Encryption Configuration Specification + $DataEncryptionConfigSpec = New-Object VMware.Vsan.Views.VsanDataEncryptionConfig + $DataEncryptionConfigSpec.KmsProviderId = $KmsProviderIdSpec + $DataEncryptionConfigSpec.EncryptionEnabled = $true + + # Set the Reconfigure Specification to use the Data Encryption Configuration Spec + $vsanReconfigSpec = New-Object VMware.Vsan.Views.VimVsanReconfigSpec + $vsanReconfigSpec.DataEncryptionConfig = $DataEncryptionConfigSpec + + # Execute the task of changing the KMS Cluster Profile Being Used + $ChangeKmsTask = $VsanVcClusterConfig.VsanClusterReconfig($VsanCluster.ExtensionData.MoRef,$vsanReconfigSpec) + } + + } + } + + Function Get-VsanEncryptionKms { + <# + .SYNOPSIS + This function will set the KMS to be used with vSAN Encryption + + .DESCRIPTION + This function will set the KMS to be used with vSAN Encryption + + .PARAMETER Cluster + Specifies the Cluster to set the KMS server for + + .EXAMPLE + C:\PS>Get-VsanEncryptionKms -Cluster "ClusterName" + #> + + # Set our Parameters + [CmdletBinding()]Param([Parameter(Mandatory = $True)][String]$Cluster) + + # Get the Cluster + $VsanCluster = Get-Cluster -Name $Cluster + + # Get the vSAN Cluster Configuration View + $VsanVcClusterConfig = Get-VsanView -Id "VsanVcClusterConfigSystem-vsan-cluster-config-system" + + # Get Encryption State + $EncryptedVsan = $VsanVcClusterConfig.VsanClusterGetConfig($VsanCluster.ExtensionData.MoRef).DataEncryptionConfig + + # If vSAN is enabled and it is Encrypted + If($VsanCluster.vSanEnabled -And $EncryptedVsan.EncryptionEnabled){ + + $EncryptedVsan.KmsProviderId.Id + } +} + +Function Set-VsanEncryptionDiskWiping { + <# + .SYNOPSIS + This function will update the Disk Wiping option in vSAN Encryption + + .DESCRIPTION + This function will update the Disk Wiping option in vSAN Encryption + + .PARAMETER Cluster + Specifies the Cluster set the Disk Wiping Setting on + + .PARAMETER DiskWiping + Use to set the Disk Wiping setting for vSAN Encryption + + .EXAMPLE + C:\PS>Set-VsanEncryptionDiskWiping -Cluster "ClusterName" -DiskWiping $true + + .EXAMPLE + C:\PS>Set-VsanEncryptionDiskWiping -Cluster "ClusterName" -DiskWiping $false + + #> + + # Set our Parameters + [CmdletBinding()]Param( + [Parameter(Mandatory = $True)][String]$Cluster, + [Parameter(Mandatory = $True)][Boolean]$DiskWiping + ) + + # Get the Cluster + $VsanCluster = Get-Cluster -Name $Cluster + + # Get the vSAN Cluster Configuration View + $VsanVcClusterConfig = Get-VsanView -Id "VsanVcClusterConfigSystem-vsan-cluster-config-system" + + # Get Encryption State + $EncryptedVsan = $VsanVcClusterConfig.VsanClusterGetConfig($VsanCluster.ExtensionData.MoRef).DataEncryptionConfig + + # If vSAN is enabled and it is Encrypted + If($VsanCluster.vSanEnabled -And $EncryptedVsan.EncryptionEnabled){ + + # Determine Rekey Type for messaging + Switch ($DiskWiping) { + $true { $DiskWipingSetting = "enabled" } + default { $DiskWipingSetting = "disabled" } + } + + # Check to see the current Disk Wiping value + If ($DiskWiping -eq $EncryptedVsan.EraseDisksBeforeUse) { + Write-Host "Disk Wiping is already $DiskWipingSetting" -ForegroundColor "Green" + Write-Host "No action necessary" -ForegroundColor "Green" + + } else { + + Write-Host "Disk Wiping is not set to $DiskWipingSetting" -ForegroundColor "Yellow" + Write-Host "Changing Disk Wiping setting on Cluster $VsanCluster" -ForegroundColor "Blue" + + # Setup the Data Encryption Configuration Specification + $DataEncryptionConfigSpec = New-Object VMware.Vsan.Views.VsanDataEncryptionConfig + $DataEncryptionConfigSpec.EncryptionEnabled = $true + $DataEncryptionConfigSpec.EraseDisksBeforeUse = $DiskWiping + + # Set the Reconfigure Specification to use the Data Encryption Configuration Spec + $vsanReconfigSpec = New-Object VMware.Vsan.Views.VimVsanReconfigSpec + $vsanReconfigSpec.DataEncryptionConfig = $DataEncryptionConfigSpec + + # Execute the task of changing the KMS Cluster Profile Being Used + $VsanVcClusterConfig.VsanClusterReconfig($VsanCluster.ExtensionData.MoRef,$vsanReconfigSpec) + + } + } +} + +Function Get-VsanEncryptionDiskWiping { + <# + .SYNOPSIS + This function will retrieve the Disk Wiping option setting in vSAN Encryption + + .DESCRIPTION + This function will retrieve the Disk Wiping option setting in vSAN Encryption + + .PARAMETER Cluster + Specifies the Cluster set the Disk Wiping Setting on + + .EXAMPLE + C:\PS>Get-VsanEncryptionDiskWiping -Cluster "ClusterName" + + #> + + # Set our Parameters + [CmdletBinding()]Param([Parameter(Mandatory = $True)][String]$Cluster) + + # Get the Cluster + $VsanCluster = Get-Cluster -Name $Cluster + + # Get the vSAN Cluster Configuration View + $VsanVcClusterConfig = Get-VsanView -Id "VsanVcClusterConfigSystem-vsan-cluster-config-system" + + # Get Encryption State + $EncryptedVsan = $VsanVcClusterConfig.VsanClusterGetConfig($VsanCluster.ExtensionData.MoRef).DataEncryptionConfig + + # If vSAN is enabled and it is Encrypted + If($VsanCluster.vSanEnabled -And $EncryptedVsan.EncryptionEnabled){ + + $EncryptedVsan.EraseDisksBeforeUse + } +} + + + +# Export Function for vSAN Rekeying +Export-ModuleMember -Function Invoke-VsanEncryptionRekey +Export-ModuleMember -Function Set-VsanEncryptionKms +Export-ModuleMember -Function Get-VsanEncryptionKms +Export-ModuleMember -Function Set-VsanEncryptionDiskWiping +Export-ModuleMember -Function Get-VsanEncryptionDiskWiping \ No newline at end of file From 82c7889cec7c140eae66d9f0f16cbf8776286680 Mon Sep 17 00:00:00 2001 From: Jase McCarty Date: Mon, 10 Dec 2018 13:36:22 -0700 Subject: [PATCH 058/175] Initial Push This is an initial push to PowerCLI-Example-Tools --- Modules/VMware.VsanEncryption/VMware.VsanEncryption.psm1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Modules/VMware.VsanEncryption/VMware.VsanEncryption.psm1 b/Modules/VMware.VsanEncryption/VMware.VsanEncryption.psm1 index e45ab91..870bd44 100644 --- a/Modules/VMware.VsanEncryption/VMware.VsanEncryption.psm1 +++ b/Modules/VMware.VsanEncryption/VMware.VsanEncryption.psm1 @@ -326,6 +326,7 @@ Function Get-VsanEncryptionDiskWiping { # If vSAN is enabled and it is Encrypted If($VsanCluster.vSanEnabled -And $EncryptedVsan.EncryptionEnabled){ + # Change the setting $EncryptedVsan.EraseDisksBeforeUse } } From faa125fd83db28e453ecb57748ccc17df52e9f65 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 14 Dec 2018 05:54:25 -0800 Subject: [PATCH 059/175] Updated URLs to new NSX-T Policy API endpoints --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 3bfdfe3..dff421a 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -83,7 +83,7 @@ Function Get-NSXTSegment { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { $method = "GET" - $segmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments" + $segmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/segments" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$segmentsURL`n" @@ -178,7 +178,7 @@ Function New-NSXTSegment { $body = $payload | ConvertTo-Json -depth 4 $method = "PUT" - $newSegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments/$Name" + $newSegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/segments/$Name" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newSegmentsURL`n" @@ -231,7 +231,7 @@ Function Remove-NSXTSegment { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { $method = "DELETE" - $deleteSegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/networks/cgw/segments/$Id" + $deleteSegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/segments/$Id" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteSegmentsURL`n" @@ -285,7 +285,7 @@ Function Get-NSXTFirewall { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { $method = "GET" - $edgeFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/edge-communication-maps/default" + $edgeFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/gateway-policies/default" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$edgeFirewallURL`n" @@ -303,7 +303,7 @@ Function Get-NSXTFirewall { } if($requests.StatusCode -eq 200) { - $rules = ($requests.Content | ConvertFrom-Json).communication_entries + $rules = ($requests.Content | ConvertFrom-Json).rules if ($PSBoundParameters.ContainsKey("Name")){ $rules = $rules | where {$_.display_name -eq $Name} @@ -467,7 +467,7 @@ Function New-NSXTFirewall { $body = $payload | ConvertTo-Json -depth 5 $method = "PUT" - $newFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/edge-communication-maps/default/communication-entries/$Id" + $newFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/gateway-policies/default/rules/$Id" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newFirewallURL`n" @@ -520,7 +520,7 @@ Function Remove-NSXTFirewall { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { $method = "DELETE" - $deleteGgroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/edge-communication-maps/default/communication-entries/$Id" + $deleteGgroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/gateway-policies/default/rules/$Id" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteGgroupURL`n" From 3372f3faf39dda82d7082dbf30e4ae79288c3a14 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Tue, 18 Dec 2018 11:16:26 -0500 Subject: [PATCH 060/175] Introduction of a new Tagging module Introduction of a new module which uses the REST based CIS API to perform tagging operations. More info: http://blogs.vmware.com/PowerCLI/2018/12/new-module-for-tag-management.html --- .../VMware.Community.CISTag.psd1 | 123 ++++ .../VMware.Community.CISTag.psm1 | 693 ++++++++++++++++++ 2 files changed, 816 insertions(+) create mode 100644 Modules/VMware.Community.CISTag/VMware.Community.CISTag.psd1 create mode 100644 Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 diff --git a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psd1 b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psd1 new file mode 100644 index 0000000..b20f2de --- /dev/null +++ b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psd1 @@ -0,0 +1,123 @@ +# +# Module manifest for module 'VMware.Community.CISTag' +# +# Generated by: Kyle Ruddy +# +# Generated on: 12/14/18 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'VMware.Community.CISTag.psm1' + +# Version number of this module. +ModuleVersion = '1.0.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = 'a0803efd-6017-4049-bfc9-5983a5a0c348' + +# Author of this module +Author = 'Kyle Ruddy' + +# Company or vendor of this module +CompanyName = 'VMware' + +# Copyright statement for this module +Copyright = '(c) VMware. All rights reserved.' + +# Description of the functionality provided by this module +Description = 'Community sourced PowerShell Module for managing vSphere Tags via the CIS Endpoint' + +# Minimum version of the PowerShell engine required by this module +PowerShellVersion = '4.0' + +# Name of the PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' + +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# CLRVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +# RequiredModules = @() + +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +# NestedModules = @() + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Get-CISTag', 'Get-CISTagCategory', 'Get-CISTagAssignment', 'New-CISTag', 'New-CISTagCategory', 'New-CISTagAssignment', 'Remove-CISTag', 'Remove-CISTagCategory', 'Remove-CISTagAssignment' + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +# CmdletsToExport = '*' + +# Variables to export from this module +# VariablesToExport = '*' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +# AliasesToExport = '*' + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} + diff --git a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 new file mode 100644 index 0000000..4dd9c0f --- /dev/null +++ b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 @@ -0,0 +1,693 @@ +function Get-CISTag { +<# +.SYNOPSIS + Gathers tag information from the CIS REST API endpoint +.DESCRIPTION + Will provide a list of tags +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Name + Tag name which should be retreived +.PARAMETER Category + Tag category name which should be retreived +.PARAMETER Id + Tag ID which should be retreived +.EXAMPLE + Get-CISTag + Retreives all tag information +.EXAMPLE + Get-CISTag -Name tagName + Retreives the tag information based on the specified name +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')] + param( + [Parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName=$true)] + [String]$Name, + [Parameter(Mandatory=$false,Position=1,ValueFromPipelineByPropertyName=$true)] + [String]$Category, + [Parameter(Mandatory=$false,Position=2,ValueFromPipelineByPropertyName=$true)] + [String]$Id + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagSvc = Get-CisService -Name com.vmware.cis.tagging.tag + if ($PSBoundParameters.ContainsKey("Id")) { + $tagOutput = $tagSvc.get($Id) + } else { + $tagArray = @() + $tagIdList = $tagSvc.list() | Select-Object -ExpandProperty Value + foreach ($t in $tagIdList) { + $tagArray += $tagSvc.get($t) + } + if ($PSBoundParameters.ContainsKey("Name")) { + $tagOutput = $tagArray | Where {$_.Name -eq $Name} + } elseif ($PSBoundParameters.ContainsKey("Category")) { + $tagCatid = Get-CISTagCategory -Name $Category | Select-Object -ExpandProperty Id + $tagIdList = $tagSvc.list_tags_for_category($tagCatid) + $tagArray2 = @() + foreach ($t in $tagIdList) { + $tagArray2 += $tagSvc.get($t) + } + $tagOutput = $tagArray2 + } else { + $tagOutput = $tagArray + } + } + $tagOutput | Select-Object Id, Name, Description + } + +} + +function New-CISTag { +<# +.SYNOPSIS + Creates a new tag from the CIS REST API endpoint +.DESCRIPTION + Will create a new tag +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Name + Tag name which should be created +.PARAMETER Category + Category name where the new tag should be associated +.PARAMETER Description + Description for the new tag +.PARAMETER CategoryID + Category ID where the new tag should be associated +.EXAMPLE + New-CISTag -Name tagName -Category categoryName -Description "Tag Descrition" + Creates a new tag based on the specified name +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')] + param( + [Parameter(Mandatory=$true,Position=0)] + [String]$Name, + [Parameter(Mandatory=$false,Position=1)] + [String]$Category, + [Parameter(Mandatory=$false,Position=2)] + [String]$Description, + [Parameter(Mandatory=$false,Position=3)] + [String]$CategoryID + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagSvc = Get-CisService -Name com.vmware.cis.tagging.tag + $tagCreateHelper = $tagSvc.Help.create.create_spec.Create() + $tagCreateHelper.name = $Name + if ($PSBoundParameters.ContainsKey("Category")) { + $tagCreateHelper.category_id = Get-CISTagCategory -Name $Category | Select-Object -ExpandProperty Id + } elseif ($PSBoundParameters.ContainsKey("CategoryId")) { + $tagCreateHelper.category_id = $CategoryID + } else {Write-Warning "No Category input found. Add a Category name or ID."; break} + if ($PSBoundParameters.ContainsKey("Description")) { + $tagCreateHelper.description = $Description + } else { + $tagCreateHelper.description = "" + } + $tagNewId = $tagSvc.create($tagCreateHelper) + Get-CISTag -Id $tagNewId + } + +} + +function Remove-CISTag { +<# +.SYNOPSIS + Removes a tag from the CIS REST API endpoint +.DESCRIPTION + Will delete a new tag +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Name + Tag name which should be removed +.PARAMETER ID + Tag ID which should be removed +.EXAMPLE + Remove-CISTag -Name tagName + Removes a new tag based on the specified name +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] + param( + [Parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName=$true)] + [String]$Name, + [Parameter(Mandatory=$false,Position=1,ValueFromPipelineByPropertyName=$true)] + [String]$ID + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagSvc = Get-CisService -Name com.vmware.cis.tagging.tag + if ($ID) { + $tagSvc.delete($ID) + } else { + $tagId = Get-CISTag -Name $Name | select -ExpandProperty Id + if ($tagId) {$tagSvc.delete($tagId)} + else {Write-Warning "No valid tag found."} + } + } +} + +function Get-CISTagCategory { +<# +.SYNOPSIS + Gathers tag category information from the CIS REST API endpoint +.DESCRIPTION + Will provide a list of tag categories +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Name + Tag category name which should be retreived +.PARAMETER Id + Tag category ID which should be retreived +.EXAMPLE + Get-CISTagCategory + Retreives all tag category information +.EXAMPLE + Get-CISTagCategory -Name tagCategoryName + Retreives the tag category information based on the specified name +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')] + param( + [Parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName=$true)] + [String]$Name, + [Parameter(Mandatory=$false,Position=2,ValueFromPipelineByPropertyName=$true)] + [String]$Id + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagCatSvc = Get-CisService -Name com.vmware.cis.tagging.category + if ($PSBoundParameters.ContainsKey("Id")) { + $tagCatOutput = $tagCatSvc.get($Id) + } else { + $tagCatArray = @() + $tagCatIdList = $tagCatSvc.list() | Select-Object -ExpandProperty Value + foreach ($tc in $tagCatIdList) { + $tagCatArray += $tagCatSvc.get($tc) + } + if ($PSBoundParameters.ContainsKey("Name")) { + $tagCatOutput = $tagCatArray | Where {$_.Name -eq $Name} + } else { + $tagCatOutput = $tagCatArray + } + } + $tagCatOutput | Select-Object Id, Name, Description, Cardinality + } + +} + +function New-CISTagCategory { +<# +.SYNOPSIS + Creates a new tag category from the CIS REST API endpoint +.DESCRIPTION + Will create a new tag category +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Name + Tag category name which should be created +.PARAMETER Description + Tag category ID which should be retreived +.PARAMETER Cardinality + Tag category ID which should be retreived +.PARAMETER AssociableTypes + Tag category ID which should be retreived +.EXAMPLE + New-CISTagCategory -Name NewTagCategoryName -Description "New Tag Category Description" -Cardinality "Single" -AssociableTypes + Creates a new tag category with the specified information +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')] + param( + [Parameter(Mandatory=$true,Position=0)] + [String]$Name, + [Parameter(Mandatory=$false,Position=1)] + [String]$Description, + [Parameter(Mandatory=$false,Position=2)] + [ValidateSet("SINGLE","MULTIPLE")] + [String]$Cardinality = "SINGLE", + [Parameter(Mandatory=$false,Position=3)] + [ValidateSet("All", "Cluster", "Datacenter", "Datastore", "DatastoreCluster", "DistributedPortGroup", "DistributedSwitch", "Folder", "ResourcePool", "VApp", "VirtualPortGroup", "VirtualMachine", "VMHost")] + [String]$AssociableTypes = "All" + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagCatSvc = Get-CisService -Name com.vmware.cis.tagging.category + $tagCatCreateHelper = $tagCatSvc.Help.create.create_spec.Create() + $tagCatCreateHelper.name = $Name + if ($PSBoundParameters.ContainsKey("Description")) { + $tagCatCreateHelper.description = $Description + } else {$tagCatCreateHelper.description = ""} + $tagCatCreateHelper.cardinality = $Cardinality + $tagCatCreateAssocTypeHelper = $tagCatSvc.help.create.create_spec.associable_types.create() + $tagCatCreateAssocTypeHelper.Add($AssociableTypes) + $tagCatCreateHelper.associable_types = $tagCatCreateAssocTypeHelper + $tagCatNewId = $tagCatSvc.create($tagCatCreateHelper) + Get-CISTagCategory -Id $tagCatNewId + } + +} + +function Remove-CISTagCategory { +<# +.SYNOPSIS + Gathers tag category information from the CIS REST API endpoint +.DESCRIPTION + Will provide a list of tag categories +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Name + Tag category name which should be removed +.PARAMETER Id + Tag category ID which should be removed +.EXAMPLE + Get-CISTagCategory + Retreives all tag category information +.EXAMPLE + Get-CISTagCategory -Name tagCategoryName + Retreives the tag category information based on the specified name + +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] + param( + [Parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName=$true)] + [String]$Name, + [Parameter(Mandatory=$false,Position=2,ValueFromPipelineByPropertyName=$true)] + [String]$Id + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagCatSvc = Get-CisService -Name com.vmware.cis.tagging.category + if ($PSBoundParameters.ContainsKey("Id")) { + $tagCatSvc.delete($Id) + } elseif ($PSBoundParameters.ContainsKey("Name")) { + $tagCatId = Get-CISTagCategory -Name $Name | Select-Object -ExpandProperty Id + $tagCatSvc.delete($tagCatId) + } else {Write-Warning "No tag category found."} + } +} + +function Get-CISTagAssignment { +<# +.SYNOPSIS + Displays a list of the tag assignments from the CIS REST API endpoint +.DESCRIPTION + Will provide a list of the tag assignments +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Category + Tag category name which should be referenced +.PARAMETER Entity + Object name which should be retreived +.PARAMETER ObjectId + Object ID which should be retreived +.EXAMPLE + Get-CISTagAssignment + Retreives all tag assignment information +.EXAMPLE + Get-CISTagAssignment -Entity VMName + Retreives all tag assignments for the VM name +.EXAMPLE + Get-CISTagAssignment -ObjectId 'vm-11' + Retreives all tag assignments for the VM object +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')] + param( + [Parameter(Mandatory=$false,Position=0)] + [String]$Category, + [Parameter(Mandatory=$false,Position=1)] + [String]$Entity, + [Parameter(Mandatory=$false,Position=2,ValueFromPipelineByPropertyName=$true)] + [String]$ObjectId + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagOutput = @() + [Boolean]$vCenterConn = $false + $tagAssocSvc = Get-CisService -Name com.vmware.cis.tagging.tag_association + if ($PSBoundParameters.ContainsKey("ObjectId")) { + if ($ObjectId.split('-')[0] -eq 'vm') { + $objType = 'VirtualMachine' + } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $ObjectId + $objObject.type = $objType + $tagIdOutput = $tagAssocSvc.list_attached_tags($objObject) + } elseif ($PSBoundParameters.ContainsKey("Entity")) { + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + [Boolean]$vCenterConn = $true + $viObject = (Get-Inventory -Name $Entity).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $objId + $objObject.type = $objType + } + $tagIdOutput = $tagAssocSvc.list_attached_tags($objObject) + } else { + $tagSvc = Get-CisService -Name com.vmware.cis.tagging.tag + $tagIdOutput = @() + $tagCategories = Get-CISTagCategory | Sort-Object -Property Name + if ($Category) { + $tagCatId = $tagCategories | where {$_.Name -eq $Category} | Select-Object -ExpandProperty Id + $tagIdOutput += $tagSvc.list_tags_for_category($tagCatId) + } else { + foreach ($tagCat in $tagCategories) { + $tagIdOutput += $tagSvc.list_tags_for_category($tagCat.id) + } + } + } + $tagReference = Get-CISTag + + if ($Entity -or $ObjectId) { + foreach ($tagId in $tagIdOutput) { + $tagAttObj = @() + if ($Entity) { + $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) | where {$_.type -eq $viObject.type -and $_.id -eq $viObject.Value} + } else { + $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) | where {$_.id -eq $ObjectId} + } + foreach ($obj in $tagAttObj) { + if ($obj.type -eq "VirtualMachine") { + if (-Not $vmSvc) {$vmSvc = Get-CisService -Name com.vmware.vcenter.vm} + $filterVmObj = $vmsvc.help.list.filter.create() + $filterVmObj.vms.add($obj.Id) | Out-Null + $objName = $vmSvc.list($filterVmObj) | Select-Object -ExpandProperty Name + } + else {$objName = 'Object Not Found'} + $tempObject = "" | Select-Object Tag, Entity + $tempObject.Tag = $tagReference | where {$_.id -eq $tagId} | Select-Object -ExpandProperty Name + $tempObject.Entity = $objName + $tagOutput += $tempObject + } + } + } else { + foreach ($tagId in $tagIdOutput) { + $tagAttObj = @() + $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + [Boolean]$vCenterConn = $true + } elseif ($tagAttObj.Type -contains 'VirtualMachine') { + if (-Not $vmSvc) {$vmSvc = Get-CisService -Name com.vmware.vcenter.vm} + } + foreach ($obj in $tagAttObj) { + if ($vCenterConn) { + $newViObj = New-Object -TypeName VMware.Vim.ManagedObjectReference + $newViObj.Type = $obj.type + $newViObj.Value = $obj.id + $objName = Get-View -Id $newViObj -Property Name | Select-Object -ExpandProperty Name + } elseif ($obj.type -eq "VirtualMachine") { + $filterVmObj = $vmsvc.help.list.filter.create() + $filterVmObj.vms.add($obj.Id) | Out-Null + $objName = $vmSvc.list($filterVmObj) | Select-Object -ExpandProperty Name + } else {$objName = 'Object Not Found'} + $tempObject = "" | Select-Object Tag, Entity + $tempObject.Tag = $tagReference | where {$_.id -eq $tagId} | Select-Object -ExpandProperty Name + $tempObject.Entity = $objName + $tagOutput += $tempObject + } + } + } + return $tagOutput + } +} + +function New-CISTagAssignment { +<# +.SYNOPSIS + Creates new tag assignments from the CIS REST API endpoint +.DESCRIPTION + Will create new tag assignments +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Tag + Tag name which should be referenced +.PARAMETER Entity + Object name which should be retreived +.PARAMETER TagId + Tag ID/s which should be referenced +.PARAMETER ObjectId + Object ID which/s should be retreived +.EXAMPLE + New-CISTagAssignment -Tag TagName -Entity VMName + Creates a tag assignment between the Tag name and the VM name +.EXAMPLE + New-CISTagAssignment -TagId $tagId -ObjectId 'vm-11' + Creates a tag assignment between the Tag ID and the Object ID +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')] + param( + [Parameter(Mandatory=$false,Position=0)] + $Tag, + [Parameter(Mandatory=$false,Position=1)] + $Entity, + [Parameter(Mandatory=$false,Position=2)] + $TagId, + [Parameter(Mandatory=$false,Position=3)] + $ObjectId + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagAssocSvc = Get-CisService -Name com.vmware.cis.tagging.tag_association + if ($PSBoundParameters.ContainsKey("Tag") -and $PSBoundParameters.ContainsKey("Entity")) { + if ($Tag -is [array] -and $Entity -isnot [array]) { + $tagIdList = $tagAssocSvc.help.attach_multiple_tags_to_object.tag_ids.create() + foreach ($t in $Tag) { + $tempId = Get-CISTag -Name $t | Select-Object -ExpandProperty Id + $tagIdList.add($tempId) | Out-Null + } + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + $viObject = (Get-Inventory -Name $Entity).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $objId + $objObject.type = $objType + } + $tagAssocSvc.attach_multiple_tags_to_object($objObject,$tagIdList) | Out-Null + } elseif ($Tag -isnot [array] -and $Entity -is [array]) { + $tagId = Get-CISTag -Name $Tag | Select-Object -ExpandProperty Id + $objList = $tagAssocSvc.help.attach_tag_to_multiple_objects.object_ids.create() + foreach ($e in $Entity) { + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + $viObject = (Get-Inventory -Name $e).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $objId + $objObject.type = $objType + } + $objList.add($objObject) | Out-Null + } + $tagAssocSvc.attach_tag_to_multiple_objects($TagId,$objList) | Out-Null + } elseif ($Tag -isnot [array] -and $Entity -isnot [array]) { + $tagId = Get-CISTag -Name $Tag | Select-Object -ExpandProperty Id + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + $viObject = (Get-Inventory -Name $Entity).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() + $objObject.id = $objId + $objObject.type = $objType + } + $tagAssocSvc.attach($TagId,$objObject) | Out-Null + } + } elseif ($PSBoundParameters.ContainsKey("TagId") -and $PSBoundParameters.ContainsKey("ObjectId")) { + if ($ObjectId.split('-')[0] -eq 'vm') { + $objType = 'VirtualMachine' + } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} + if ($TagId -is [array] -and $ObjectId -isnot [array]) { + $objObject = $tagAssocSvc.help.attach_multiple_tags_to_object.object_id.create() + $objObject.id = $ObjectId + $objObject.type = $objType + $tagIdList = $tagAssocSvc.help.attach_multiple_tags_to_object.tag_ids.create() + foreach ($tId in $TagId) { + $tagIdList.add($tId) | Out-Null + } + $tagAssocSvc.attach_multiple_tags_to_object($objObject,$tagIdList) | Out-Null + } elseif ($TagId -isnot [array] -and $ObjectId -is [array]) { + $objList = $tagAssocSvc.help.attach_tag_to_multiple_objects.object_ids.create() + foreach ($obj in $ObjectId) { + $objObject = $tagAssocSvc.help.attach_tag_to_multiple_objects.object_ids.element.create() + $objObject.id = $obj + $objObject.type = $objType + $objList.add($objObject) | Out-Null + } + $tagAssocSvc.attach_tag_to_multiple_objects($TagId,$objList) | Out-Null + } elseif ($TagId -isnot [array] -and $ObjectId -isnot [array]) { + $objObject = $tagAssocSvc.help.attach.object_id.create() + $objObject.id = $ObjectId + $objObject.type = $objType + $tagAssocSvc.attach($TagId,$objObject) | Out-Null + } + + } else {Write-Output "Multiple tags with multiple objects are not a supported call."} + + } +} + +function Remove-CISTagAssignment { +<# +.SYNOPSIS + Displays a list of the tag assignments from the CIS REST API endpoint +.DESCRIPTION + Will provide a list of the tag assignments +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER Tag + Tag name which should be removed +.PARAMETER Entity + Object name which should be removed +.PARAMETER TagId + Tag ID/s which should be removed +.PARAMETER ObjectId + Object ID which/s should be removed +.EXAMPLE + Remove-CISTagAssignment -TagId $tagId -ObjectId 'vm-11' + Removes the tag assignment between the Tag ID and the Object ID +.EXAMPLE + Remove-CISTagAssignment -Tag TagName -Entity VMName + Removes the tag assignment between the Tag name and the Entity name +#> +[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] + param( + [Parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName=$true)] + $Tag, + [Parameter(Mandatory=$false,Position=1,ValueFromPipelineByPropertyName=$true)] + $Entity, + [Parameter(Mandatory=$false,Position=2)] + $TagId, + [Parameter(Mandatory=$false,Position=3)] + $ObjectId + ) + + If (-Not $global:DefaultCisServers) { Write-error "No CIS Connection found, please use the Connect-CisServer to connect" } Else { + $tagAssocSvc = Get-CisService -Name com.vmware.cis.tagging.tag_association + if ($PSBoundParameters.ContainsKey("Tag") -and $PSBoundParameters.ContainsKey("Entity")) { + if ($Tag -is [array] -and $Entity -isnot [array]) { + $tagIdList = $tagAssocSvc.help.detach_multiple_tags_from_object.tag_ids.create() + foreach ($t in $Tag) { + $tempId = Get-CISTag -Name $t | Select-Object -ExpandProperty Id + $tagIdList.add($tempId) | Out-Null + } + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + $viObject = (Get-Inventory -Name $Entity).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.detach_multiple_tags_from_object.object_id.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.detach_multiple_tags_from_object.object_id.create() + $objObject.id = $objId + $objObject.type = $objType + } + $tagAssocSvc.detach_multiple_tags_from_object($objObject,$tagIdList) | Out-Null + } elseif ($Tag -isnot [array] -and $Entity -is [array]) { + $tagId = Get-CISTag -Name $Tag | Select-Object -ExpandProperty Id + $objList = $tagAssocSvc.help.detach_tag_from_multiple_objects.object_ids.create() + foreach ($e in $Entity) { + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + $viObject = (Get-Inventory -Name $e).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.detach_tag_from_multiple_objects.object_ids.element.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.detach_tag_from_multiple_objects.object_ids.element.create() + $objObject.id = $objId + $objObject.type = $objType + } + $objList.add($objObject) | Out-Null + } + $tagAssocSvc.detach_tag_from_multiple_objects($TagId,$objList) | Out-Null + } elseif ($Tag -isnot [array] -and $Entity -isnot [array]) { + $tagId = Get-CISTag -Name $Tag | Select-Object -ExpandProperty Id + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + $viObject = (Get-Inventory -Name $Entity).ExtensionData.MoRef + $objObject = $tagAssocSvc.help.detach.object_id.create() + $objObject.id = $viObject.Value + $objObject.type = $viObject.type + } else { + $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + $filterVmNameObj = $vmsvc.help.list.filter.create() + $filterVmNameObj.names.add($Entity) | Out-Null + $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm + if ($objId) {$objType = 'VirtualMachine'} + else {Write-Warning "No entities found."; break} + $objObject = $tagAssocSvc.help.detach.object_id.create() + $objObject.id = $objId + $objObject.type = $objType + } + $tagAssocSvc.detach($TagId,$objObject) | Out-Null + } + } elseif ($PSBoundParameters.ContainsKey("TagId") -and $PSBoundParameters.ContainsKey("ObjectId")) { + if ($ObjectId.split('-')[0] -eq 'vm') { + $objType = 'VirtualMachine' + } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} + if ($TagId -is [array] -and $ObjectId -isnot [array]) { + $objObject = $tagAssocSvc.help.detach_multiple_tags_from_object.object_id.create() + $objObject.id = $ObjectId + $objObject.type = $objType + $tagIdList = $tagAssocSvc.help.detach_multiple_tags_from_object.tag_ids.create() + foreach ($tId in $TagId) { + $tagIdList.add($tId) | Out-Null + } + $tagAssocSvc.detach_multiple_tags_from_object($objObject,$tagIdList) | Out-Null + } elseif ($TagId -isnot [array] -and $ObjectId -is [array]) { + $objList = $tagAssocSvc.help.detach_tag_from_multiple_objects.object_ids.create() + foreach ($obj in $ObjectId) { + $objObject = $tagAssocSvc.help.detach_tag_from_multiple_objects.object_ids.element.create() + $objObject.id = $obj + $objObject.type = $objType + $objList.add($objObject) | Out-Null + } + $tagAssocSvc.detach_tag_from_multiple_objects($TagId,$objList) | Out-Null + } elseif ($TagId -isnot [array] -and $ObjectId -isnot [array]) { + $objObject = $tagAssocSvc.help.detach.object_id.create() + $objObject.id = $ObjectId + $objObject.type = $objType + $tagAssocSvc.detach($TagId,$objObject) | Out-Null + } + } else {Write-Output "Multiple tags with multiple objects are not a supported call."} + + } +} \ No newline at end of file From 44879d8c25df1e3b0165d9441be6b236aaaab099 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Tue, 18 Dec 2018 15:00:39 -0500 Subject: [PATCH 061/175] Update VMware.Community.CISTag.psm1 Updated Synopsis and Examples --- .../VMware.Community.CISTag.psm1 | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 index 4dd9c0f..837a595 100644 --- a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 +++ b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 @@ -248,9 +248,9 @@ function New-CISTagCategory { function Remove-CISTagCategory { <# .SYNOPSIS - Gathers tag category information from the CIS REST API endpoint + Removes tag category information from the CIS REST API endpoint .DESCRIPTION - Will provide a list of tag categories + Will remove a tag categorie .NOTES Author: Kyle Ruddy, @kmruddy .PARAMETER Name @@ -258,11 +258,8 @@ function Remove-CISTagCategory { .PARAMETER Id Tag category ID which should be removed .EXAMPLE - Get-CISTagCategory - Retreives all tag category information -.EXAMPLE - Get-CISTagCategory -Name tagCategoryName - Retreives the tag category information based on the specified name + Remove-CISTagCategory -Name tagCategoryName + Removes the tag category information based on the specified name #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] @@ -558,9 +555,9 @@ function New-CISTagAssignment { function Remove-CISTagAssignment { <# .SYNOPSIS - Displays a list of the tag assignments from the CIS REST API endpoint + Removes a tag assignment from the CIS REST API endpoint .DESCRIPTION - Will provide a list of the tag assignments + Will remove provided tag assignments .NOTES Author: Kyle Ruddy, @kmruddy .PARAMETER Tag From bfbcbc8faa185709cfa7a527cdc3083da99c9d7a Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Tue, 18 Dec 2018 19:37:42 -0500 Subject: [PATCH 062/175] Update VMware.Community.CISTag.psm1 Add VIServer capabilities to Get-CISTag --- .../VMware.Community.CISTag.psm1 | 41 +++++++++++++------ 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 index 837a595..05594e4 100644 --- a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 +++ b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 @@ -34,23 +34,38 @@ function Get-CISTag { if ($PSBoundParameters.ContainsKey("Id")) { $tagOutput = $tagSvc.get($Id) } else { - $tagArray = @() - $tagIdList = $tagSvc.list() | Select-Object -ExpandProperty Value - foreach ($t in $tagIdList) { - $tagArray += $tagSvc.get($t) + if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { + [Boolean]$vCenterConn = $true + $vCTagList = Get-Tag + } else { + $tagArray = @() + $tagIdList = $tagSvc.list() | Select-Object -ExpandProperty Value + [integer]$counter = 1 + foreach ($t in $tagIdList) { + $tagArray += $tagSvc.get($t) + $counter++ + if ($counter -gt 200) {Start-Sleep -Milliseconds 1; $counter = 1} + } } if ($PSBoundParameters.ContainsKey("Name")) { - $tagOutput = $tagArray | Where {$_.Name -eq $Name} + if ($vCenterConn){ + $tagOutput = $vCTagList | where {$_.Name -eq $Name} + } else {$tagOutput = $tagArray | Where {$_.Name -eq $Name}} } elseif ($PSBoundParameters.ContainsKey("Category")) { - $tagCatid = Get-CISTagCategory -Name $Category | Select-Object -ExpandProperty Id - $tagIdList = $tagSvc.list_tags_for_category($tagCatid) - $tagArray2 = @() - foreach ($t in $tagIdList) { - $tagArray2 += $tagSvc.get($t) + if ($vCenterConn){ + $tagOutput = $vCTagList | where {$_.Category -eq $Category} + } else { + $tagCatid = Get-CISTagCategory -Name $Category | Select-Object -ExpandProperty Id + $tagIdList = $tagSvc.list_tags_for_category($tagCatid) + $tagArray2 = @() + foreach ($t in $tagIdList) { + $tagArray2 += $tagSvc.get($t) + } + $tagOutput = $tagArray2 } - $tagOutput = $tagArray2 } else { - $tagOutput = $tagArray + if ($vCenterConn){$tagOutput = $vCTagList} + else {$tagOutput = $tagArray} } } $tagOutput | Select-Object Id, Name, Description @@ -250,7 +265,7 @@ function Remove-CISTagCategory { .SYNOPSIS Removes tag category information from the CIS REST API endpoint .DESCRIPTION - Will remove a tag categorie + Will remove a tag category .NOTES Author: Kyle Ruddy, @kmruddy .PARAMETER Name From 8953a512fe58fd69f54e963364e49b3b89d5f602 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 20 Dec 2018 10:28:31 +0000 Subject: [PATCH 063/175] Create Get-Migrations.ps1 Quick function for listing the currently running and recently finished VM migrations --- Scripts/Get-Migrations.ps1 | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Scripts/Get-Migrations.ps1 diff --git a/Scripts/Get-Migrations.ps1 b/Scripts/Get-Migrations.ps1 new file mode 100644 index 0000000..8336de7 --- /dev/null +++ b/Scripts/Get-Migrations.ps1 @@ -0,0 +1,12 @@ +<# +Script name: get-migrations.ps1 +Created on: 20/12/2018 +Author: Chris Bradshaw @aldershotchris +Description: The purpose of the script is to list the currently running + recently finished VM migrations. +Dependencies: None known +#> +Function Get-Migrations{ + Get-Task | + Where-Object{$_.Name -eq "RelocateVM_Task"} | + Select-Object @{Name="VM";Expression={Get-VM -Id $_.ObjectID}}, State, @{Name="% Complete";Expression={$_.PercentComplete}},StartTime +} From 4652495ece548970cb8b43c6b03f53bb2b27d94a Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 20 Dec 2018 06:35:45 -0800 Subject: [PATCH 064/175] Fixing Get/New-NSXTSegment due to NSX-T Policy API change --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index dff421a..6a4204f 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -112,7 +112,7 @@ Function Get-NSXTSegment { $subnets = $segment.subnets $network = $subnets.network - $gateway = $subnets.gateway_addresses + $gateway = $subnets.gateway_address $dhcpRange = $subnets.dhcp_ranges $tmp = [pscustomobject] @{ @@ -147,12 +147,12 @@ Function New-NSXTSegment { .DESCRIPTION This cmdlet creates a new NSX-T Segment (Logical Networks) .EXAMPLE - New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1" -Prefix "24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" + New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -Network "192.168.0/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" #> Param ( [Parameter(Mandatory=$True)]$Name, [Parameter(Mandatory=$True)]$Gateway, - [Parameter(Mandatory=$True)]$Prefix, + [Parameter(Mandatory=$True)]$Network, [Parameter(Mandatory=$False)]$DHCPRange, [Switch]$DHCP, [Switch]$Troubleshoot @@ -166,9 +166,9 @@ Function New-NSXTSegment { } $subnets = @{ - gateway_addresses = @($gateway); - prefix_len = $Prefix; - dhcp_ranges = $dhcpConf + gateway_address = $gateway; + network = $Network; + dhcp_ranges = $dhcpConf; } $payload = @{ From 81e60245d03e981a57ca944b9e20d754fd7d770b Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 21 Dec 2018 09:58:37 -0800 Subject: [PATCH 065/175] Fixing New-NSXTSegment (Network property not required) --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 6a4204f..5a30156 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -147,12 +147,11 @@ Function New-NSXTSegment { .DESCRIPTION This cmdlet creates a new NSX-T Segment (Logical Networks) .EXAMPLE - New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -Network "192.168.0/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" + New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" #> Param ( [Parameter(Mandatory=$True)]$Name, [Parameter(Mandatory=$True)]$Gateway, - [Parameter(Mandatory=$True)]$Network, [Parameter(Mandatory=$False)]$DHCPRange, [Switch]$DHCP, [Switch]$Troubleshoot @@ -167,7 +166,6 @@ Function New-NSXTSegment { $subnets = @{ gateway_address = $gateway; - network = $Network; dhcp_ranges = $dhcpConf; } From 06d018c7a6abd4657f0b057a31358e008de3dcb1 Mon Sep 17 00:00:00 2001 From: PARAMESHO Date: Wed, 2 Jan 2019 21:55:26 +0530 Subject: [PATCH 066/175] Set-HVApplicationIcon not behaving correctly with .ico and .bmp files When bmp/ico image files are used as customized application icons, short cuts feature on Horizon Client is facing the issues in rendering. Bug 2168320 has been reported for this issue. We have decided to block all the non-png image files for the customization of application icons. Testing: Tested with the changes. Working as expected. Refer review https://reviewboard.eng.vmware.com/r/1446121 for more details. --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 5b68b9f..7717e40 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -8819,6 +8819,16 @@ function Set-HVApplicationIcon { } process { + if (!(Test-Path $IconPath)) { + Write-Error "File:[$IconPath] does not exist." + break + } + + if ([IO.Path]::GetExtension($IconPath) -ne '.png') { + Write-Error "Unsupported file format:[$IconPath]. Only PNG image files are supported." + break + } + try { $appInfo = Get-HVQueryResult -EntityType ApplicationInfo -Filter (Get-HVQueryFilter data.name -Eq $ApplicationName) -HvServer $HvServer } catch { @@ -8832,11 +8842,6 @@ function Set-HVApplicationIcon { 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 From 25cfffa14f343f799fc236d6e1108297aaea0c49 Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 2 Jan 2019 10:07:40 -0800 Subject: [PATCH 067/175] Adding "Get" functions for Distribugted FW rules --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 282 +++++++++++++++++-- 1 file changed, 266 insertions(+), 16 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 5a30156..426a357 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -126,7 +126,8 @@ Function Get-NSXTSegment { } $results } else { - Write-Error "Failed to retrieve NSX-T Segments" + Write-Error "Error in retrieving NSX-T Segments" + Write-Error "Return code: " $requests.StatusCode } } } @@ -198,8 +199,8 @@ Function New-NSXTSegment { Write-Host "Succesfully created new NSX-T Segment $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } else { - Write-Error "Failed to create new NSX-T Segment" - + Write-Error "Error in creating new NSX-T Segment" + Write-Error "Return code: " $requests.StatusCode } } } @@ -249,8 +250,8 @@ Function Remove-NSXTSegment { if($requests.StatusCode -eq 200) { Write-Host "Succesfully removed NSX-T Segment $Name" } else { - Write-Error "Failed to remove NSX-T Segments" - + Write-Error "Error in removing NSX-T Segments" + Write-Error "Return code: " $requests.StatusCode } } } @@ -321,7 +322,11 @@ Function Get-NSXTFirewall { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$sourceGroupURL`n" } try { - $requests = Invoke-WebRequest -Uri $sourceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $sourceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $sourceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } } catch { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break @@ -343,7 +348,11 @@ Function Get-NSXTFirewall { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$destionationGroupURL`n" } try { - $requests = Invoke-WebRequest -Uri $destionationGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $destionationGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $destionationGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } } catch { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break @@ -365,7 +374,11 @@ Function Get-NSXTFirewall { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$serviceGroupURL`n" } try { - $requests = Invoke-WebRequest -Uri $serviceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $serviceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $serviceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } } catch { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break @@ -389,7 +402,8 @@ Function Get-NSXTFirewall { $results } else { - Write-Error "Failed to retrieve NSX-T Firewall Rules" + Write-Error "Error in retrieving NSX-T Firewall Rules" + Write-Error "Return code: " $requests.StatusCode } } } @@ -487,7 +501,8 @@ Function New-NSXTFirewall { Write-Host "Succesfully created new NSX-T Firewall Rule $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } else { - Write-Error "Failed to create new NSX-T Firewall Rule" + Write-Error "Error in creating new NSX-T Firewall Rule" + Write-Error "Return code: " $requests.StatusCode } } } @@ -538,7 +553,8 @@ Function Remove-NSXTFirewall { if($requests.StatusCode -eq 200) { Write-Host "Succesfully removed NSX-T Firewall Rule $Name" } else { - Write-Error "Failed to create new NSX-T Firewall Rule" + Write-Error "Error in creating new NSX-T Firewall Rule" + Write-Error "Return code: " $requests.StatusCode } } } @@ -622,7 +638,8 @@ Function Get-NSXTGroup { } $results } else { - Write-Error "Failed to retrieve NSX-T Groups" + Write-Error "Error in retrieving NSX-T Groups" + Write-Error "Return code: " $requests.StatusCode } } } @@ -687,7 +704,8 @@ Function New-NSXTGroup { Write-Host "Succesfully created new NSX-T Group $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } else { - Write-Error "Failed to create new NSX-T Group" + Write-Error "Error in creating new NSX-T Group" + Write-Error "Return code: " $requests.StatusCode } } } @@ -738,7 +756,8 @@ Function Remove-NSXTGroup { if($requests.StatusCode -eq 200) { Write-Host "Succesfully removed NSX-T Group $Name" } else { - Write-Error "Failed to create new NSX-T Group" + Write-Error "Error in creating new NSX-T Group" + Write-Error "Return code: " $requests.StatusCode } } } @@ -812,7 +831,8 @@ Function Get-NSXTService { } $results } else { - Write-Error "Failed to retrieve NSX-T Services" + Write-Error "Error in retrieving NSX-T Services" + Write-Error "Return code: " $requests.StatusCode } } } @@ -881,7 +901,237 @@ Function New-NSXTService { Write-Host "Succesfully created new NSX-T Service $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } else { - Write-Error "Failed to create new NSX-T Service" + Write-Error "Error in creating new NSX-T Service" + Write-Error "Return code: " $requests.StatusCode + } + } +} + +Function Get-NSXTDistFirewallSection { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 12/31/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Distributed Firewall Groups + .DESCRIPTION + This cmdlet retrieves all NSX-T Distributed Firewall Sections + .EXAMPLE + Get-NSXTDistFirewallSection + .EXAMPLE + Get-NSXTDistFirewallSection -Name "App Section 1" + .EXAMPLE + et-NSXTDistFirewallSection -Category Emergency +#> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Parameter(Mandatory=$false)][ValidateSet("Emergency","Infrastructure","Environment","Application")][String]$Category, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $distFirewallGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$distFirewallGroupURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $distFirewallGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $distFirewallGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + + if($requests.StatusCode -eq 200) { + $groups = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $groups = $groups | where {$_.display_name -eq $Name} + } + + if ($PSBoundParameters.ContainsKey("Category")){ + $groups = $groups | where {$_.category -eq $Category} + } + + $results = @() + foreach ($group in $groups | Sort-Object -Property category) { + $tmp = [pscustomobject] @{ + Id = $group.id; + Section = $group.display_name; + Category = $group.category; + Precedence = $group.precedence; + } + $results+=$tmp + } + $results + + } else { + Write-Error "Error in retrieving NSX-T Distributed Firewall Sections" + Write-Error "Return code: " $requests.StatusCode + } + } +} + +Function Get-NSXTDistFirewall { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/11/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Distributed Firewall Rules for a given Section + .DESCRIPTION + This cmdlet retrieves all NSX-T Distributed Firewall Rules for a given Section + .EXAMPLE + Get-NSXTDistFirewall -Name "App Section 1" +#> + param( + [Parameter(Mandatory=$true)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + try { + $distGroupId = (Get-NSXTDistFirewallSection -Name $Name).Id + } + catch { + Write-Host -ForegroundColor Red "`nUnable to find NSX-T Distributed Firewall Group named $Name`n" + break + } + + $method = "GET" + $distFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$distGroupId" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$distFirewallURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $distFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $distFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nFailed to retrieve Distributed Firewall Rules`n" + break + } + + if($requests.StatusCode -eq 200) { + $rules = ($requests.Content | ConvertFrom-Json).communication_entries + + $results = @() + foreach ($rule in $rules | Sort-Object -Property sequence_number) { + $sourceGroups = $rule.source_groups + $source = @() + foreach ($sourceGroup in $sourceGroups) { + if($sourceGroup -eq "ANY") { + $source += $sourceGroup + break + } else { + $sourceGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $sourceGroup + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$sourceGroupURL`n" + } + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $sourceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $sourceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nFailed to retrieve Source Group Rule mappings`n" + break + } + $group = ($requests.Content | ConvertFrom-Json) + $source += $group.display_name + } + } + + $destinationGroups = $rule.destination_groups + $destination = @() + foreach ($destinationGroup in $destinationGroups) { + if($destinationGroup -eq "ANY") { + $destination += $destinationGroup + break + } else { + $destionationGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $destinationGroup + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$destionationGroupURL`n" + } + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $destionationGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $destionationGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nFailed to retireve Destination Group Rule mappings`n" + break + } + $group = ($requests.Content | ConvertFrom-Json) + $destination += $group.display_name + } + } + + $serviceGroups = $rule.services + $service = @() + foreach ($serviceGroup in $serviceGroups) { + if($serviceGroup -eq "ANY") { + $service += $serviceGroup + break + } else { + $serviceGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $serviceGroup + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$serviceGroupURL`n" + } + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $serviceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $serviceGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nFailed to retrieve Services Rule mappings`n" + break + } + $group = ($requests.Content | ConvertFrom-Json) + $service += $group.display_name + } + } + + $tmp = [pscustomobject] @{ + SequenceNumber = $rule.sequence_number; + Name = $rule.display_name; + ID = $rule.id; + Source = $source; + Destination = $destination; + Services = $service; + Action = $rule.action; + } + $results+=$tmp + } + $results + } else { + Write-Error "Error in retrieving NSX-T Distributed Firewall Rules" + Write-Error "Return code: " $requests.StatusCode } } } \ No newline at end of file From 5571a8900a4d39c5a8739e6f3a13276a05fe0734 Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 3 Jan 2019 12:21:50 -0800 Subject: [PATCH 068/175] Added {New,Remove}-NSXTDisFirewall functions --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 411 ++++++++++++++----- 1 file changed, 319 insertions(+), 92 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 426a357..ef83777 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -96,8 +96,14 @@ Function Get-NSXTSegment { $requests = Invoke-WebRequest -Uri $segmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Segments" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { @@ -125,9 +131,6 @@ Function Get-NSXTSegment { $results+=$tmp } $results - } else { - Write-Error "Error in retrieving NSX-T Segments" - Write-Error "Return code: " $requests.StatusCode } } } @@ -191,16 +194,19 @@ Function New-NSXTSegment { $requests = Invoke-WebRequest -Uri $newSegmentsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Segment" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { Write-Host "Succesfully created new NSX-T Segment $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id - } else { - Write-Error "Error in creating new NSX-T Segment" - Write-Error "Return code: " $requests.StatusCode } } } @@ -243,15 +249,18 @@ Function Remove-NSXTSegment { $requests = Invoke-WebRequest -Uri $deleteSegmentsURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in removing NSX-T Segments" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { Write-Host "Succesfully removed NSX-T Segment $Name" - } else { - Write-Error "Error in removing NSX-T Segments" - Write-Error "Return code: " $requests.StatusCode } } } @@ -297,8 +306,14 @@ Function Get-NSXTFirewall { $requests = Invoke-WebRequest -Uri $edgeFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Firewall Rules" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { @@ -401,9 +416,6 @@ Function Get-NSXTFirewall { } $results - } else { - Write-Error "Error in retrieving NSX-T Firewall Rules" - Write-Error "Return code: " $requests.StatusCode } } } @@ -424,15 +436,14 @@ Function New-NSXTFirewall { .DESCRIPTION This cmdlet creates a new NSX-T Firewall Rule on MGW or CGW .EXAMPLE - New-NSXTFirewall -GatewayType MGW -Name TEST -Id TEST -SourceGroupId ESXI -DestinationGroupId ANY -Service ANY -Logged $true -SequenceNumber 7 -Action ALLOW + New-NSXTFirewall -GatewayType MGW -Name TEST -SourceGroup @("ANY") -DestinationGroup @("ESXI") -Service ANY -Logged $true -SequenceNumber 0 -Action ALLOW #> Param ( [Parameter(Mandatory=$True)]$Name, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, - [Parameter(Mandatory=$True)]$Id, [Parameter(Mandatory=$True)]$SequenceNumber, - [Parameter(Mandatory=$True)]$SourceGroupId, - [Parameter(Mandatory=$True)]$DestinationGroupId, + [Parameter(Mandatory=$True)]$SourceGroup, + [Parameter(Mandatory=$True)]$DestinationGroup, [Parameter(Mandatory=$True)]$Service, [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, [Parameter(Mandatory=$false)][Boolean]$Logged=$false, @@ -441,34 +452,43 @@ Function New-NSXTFirewall { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { - if($DestinationGroupId -eq "ANY") { - $destinationGroups = $DestinationGroupId - } else { - $destinationGroups = "/infra/domains/$($GatewayType.toLower())/groups/$DestinationGroupId" + $generatedId = (New-Guid).Guid + + $destinationGroups = @() + foreach ($group in $DestinationGroup) { + if($group -eq "ANY") { + $destinationGroups = @("ANY") + } else { + $tmp = (Get-NSXTGroup -GatewayType $GatewayType -Name $group).Path + $destinationGroups+= $tmp + } } $sourceGroups = @() - foreach ($group in $SourceGroupId) { - $tmp = "/infra/domains/$($GatewayType.toLower())/groups/$group" - $sourceGroups+= $tmp + foreach ($group in $SourceGroup) { + if($group -eq "ANY") { + $sourceGroups = @("ANY") + } else { + $tmp = (Get-NSXTGroup -GatewayType $GatewayType -Name $group).Path + $sourceGroups+= $tmp + } } $services = @() foreach ($serviceName in $Service) { - if($serviceName -eq "ANY") { - $tmp = "ANY" + if($group -eq "ANY") { + $services = @("ANY") } else { $tmp = "/infra/services/$serviceName" + $services+=$tmp } - $services+=$tmp } $payload = @{ display_name = $Name; resource_type = "CommunicationEntry"; - id = $Id; sequence_number = $SequenceNumber; - destination_groups = @($destinationGroups); + destination_groups = $destinationGroups; source_groups = $sourceGroups; logged = $Logged; scope = @("/infra/labels/$($GatewayType.toLower())"); @@ -479,7 +499,7 @@ Function New-NSXTFirewall { $body = $payload | ConvertTo-Json -depth 5 $method = "PUT" - $newFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/gateway-policies/default/rules/$Id" + $newFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/gateway-policies/default/rules/$generatedId" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newFirewallURL`n" @@ -493,16 +513,19 @@ Function New-NSXTFirewall { $requests = Invoke-WebRequest -Uri $newFirewallURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Firewall Rule" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { Write-Host "Succesfully created new NSX-T Firewall Rule $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id - } else { - Write-Error "Error in creating new NSX-T Firewall Rule" - Write-Error "Return code: " $requests.StatusCode } } } @@ -546,15 +569,18 @@ Function Remove-NSXTFirewall { $requests = Invoke-WebRequest -Uri $deleteGgroupURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Firewall Rule" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T Firewall Rule $Name" - } else { - Write-Error "Error in creating new NSX-T Firewall Rule" - Write-Error "Return code: " $requests.StatusCode + Write-Host "Succesfully removed NSX-T Firewall Rule" } } } @@ -600,8 +626,14 @@ Function Get-NSXTGroup { $requests = Invoke-WebRequest -Uri $edgeFirewallGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Groups" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { @@ -633,13 +665,11 @@ Function Get-NSXTGroup { ID = $group.id; Type = $groupType; Members = $members; + Path = $group.path; } $results+=$tmp } $results - } else { - Write-Error "Error in retrieving NSX-T Groups" - Write-Error "Return code: " $requests.StatusCode } } } @@ -682,7 +712,8 @@ Function New-NSXTGroup { $body = $payload | ConvertTo-Json -depth 5 $method = "PUT" - $newGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/groups/$Name" + $generatedId = (New-Guid).Guid + $newGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/$($GatewayType.toLower())/groups/$generatedId" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newGroupURL`n" @@ -696,16 +727,19 @@ Function New-NSXTGroup { $requests = Invoke-WebRequest -Uri $newGroupURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Group" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { Write-Host "Succesfully created new NSX-T Group $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id - } else { - Write-Error "Error in creating new NSX-T Group" - Write-Error "Return code: " $requests.StatusCode } } } @@ -749,15 +783,18 @@ Function Remove-NSXTGroup { $requests = Invoke-WebRequest -Uri $deleteGgroupURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Group" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { Write-Host "Succesfully removed NSX-T Group $Name" - } else { - Write-Error "Error in creating new NSX-T Group" - Write-Error "Return code: " $requests.StatusCode } } } @@ -802,8 +839,14 @@ Function Get-NSXTService { $requests = Invoke-WebRequest -Uri $serviceGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Services" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { @@ -830,9 +873,6 @@ Function Get-NSXTService { $results += $tmp } $results - } else { - Write-Error "Error in retrieving NSX-T Services" - Write-Error "Return code: " $requests.StatusCode } } } @@ -893,16 +933,19 @@ Function New-NSXTService { $requests = Invoke-WebRequest -Uri $newServiceURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Service" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { Write-Host "Succesfully created new NSX-T Service $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id - } else { - Write-Error "Error in creating new NSX-T Service" - Write-Error "Return code: " $requests.StatusCode } } } @@ -912,7 +955,7 @@ Function Get-NSXTDistFirewallSection { .NOTES =========================================================================== Created by: William Lam - Date: 12/31/2018 + Date: 01/01/2019 Organization: VMware Blog: http://www.virtuallyghetto.com Twitter: @lamw @@ -950,8 +993,14 @@ Function Get-NSXTDistFirewallSection { $requests = Invoke-WebRequest -Uri $distFirewallGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Distributed Firewall Sections" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { @@ -976,10 +1025,6 @@ Function Get-NSXTDistFirewallSection { $results+=$tmp } $results - - } else { - Write-Error "Error in retrieving NSX-T Distributed Firewall Sections" - Write-Error "Return code: " $requests.StatusCode } } } @@ -989,7 +1034,7 @@ Function Get-NSXTDistFirewall { .NOTES =========================================================================== Created by: William Lam - Date: 09/11/2018 + Date: 01/01/2019 Organization: VMware Blog: http://www.virtuallyghetto.com Twitter: @lamw @@ -1000,20 +1045,26 @@ Function Get-NSXTDistFirewall { .DESCRIPTION This cmdlet retrieves all NSX-T Distributed Firewall Rules for a given Section .EXAMPLE - Get-NSXTDistFirewall -Name "App Section 1" + Get-NSXTDistFirewall -SectionName "App Section 1" #> param( - [Parameter(Mandatory=$true)][String]$Name, + [Parameter(Mandatory=$true)][String]$SectionName, [Switch]$Troubleshoot ) If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { try { - $distGroupId = (Get-NSXTDistFirewallSection -Name $Name).Id + $distGroupId = (Get-NSXTDistFirewallSection -Name $SectionName).Id } catch { - Write-Host -ForegroundColor Red "`nUnable to find NSX-T Distributed Firewall Group named $Name`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Host -ForegroundColor Red "`nUnable to find NSX-T Distributed Firewall Section named $SectionName`n" + Write-Error "`n($_.Exception.Message)`n" + break + } } $method = "GET" @@ -1030,8 +1081,14 @@ Function Get-NSXTDistFirewall { $requests = Invoke-WebRequest -Uri $distFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { - Write-Host -ForegroundColor Red "`nFailed to retrieve Distributed Firewall Rules`n" - break + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Distributed Firewall Rules" + Write-Error "`n($_.Exception.Message)`n" + break + } } if($requests.StatusCode -eq 200) { @@ -1129,9 +1186,179 @@ Function Get-NSXTDistFirewall { $results+=$tmp } $results - } else { - Write-Error "Error in retrieving NSX-T Distributed Firewall Rules" - Write-Error "Return code: " $requests.StatusCode + } + } +} + +Function New-NSXTDistFirewall { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/03/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a new NSX-T Distribuged Firewall Rule + .DESCRIPTION + This cmdlet creates a new NSX-T Distribuged Firewall Rule + .EXAMPLE + New-NSXTDistFirewall -Name "App1 to Web1" -Section "App Section 1" ` + -SourceGroup "App Server 1" ` + -DestinationGroup "Web Server 1" ` + -Service HTTPS -Logged $true ` + -SequenceNumber 10 ` + -Action ALLOW +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Parameter(Mandatory=$True)]$Section, + [Parameter(Mandatory=$True)]$SequenceNumber, + [Parameter(Mandatory=$True)]$SourceGroup, + [Parameter(Mandatory=$True)]$DestinationGroup, + [Parameter(Mandatory=$True)]$Service, + [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, + [Parameter(Mandatory=$false)][Boolean]$Logged=$false, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + + $sectionId = (Get-NSXTDistFirewallSection -Name $Section).Id + + $destinationGroups = @() + foreach ($group in $DestinationGroup) { + if($group -eq "ANY") { + $destinationGroups = @("ANY") + } else { + $tmp = (Get-NSXTGroup -GatewayType CGW -Name $group).Path + $destinationGroups+= $tmp + } + } + + $sourceGroups = @() + foreach ($group in $SourceGroup) { + if($group -eq "ANY") { + $sourceGroups = @("ANY") + } else { + $tmp = (Get-NSXTGroup -GatewayType CGW -Name $group).Path + $sourceGroups+= $tmp + } + } + + $services = @() + foreach ($serviceName in $Service) { + if($serviceName -eq "ANY") { + $services = @("ANY") + } else { + $tmp = "/infra/services/$serviceName" + $services+=$tmp + } + } + + $payload = @{ + display_name = $Name; + sequence_number = $SequenceNumber; + destination_groups = $destinationGroups; + source_groups = $sourceGroups; + logged = $Logged; + scope = @("ANY"); + services = $services; + action = $Action; + } + + $body = $payload | ConvertTo-Json -depth 5 + + $method = "PUT" + $generatedId = (New-Guid).Guid + $newDistFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$sectionId/communication-entries/$generatedId" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newDistFirewallURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $newDistFirewallURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $newDistFirewallURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Distribugted Firewall Rule" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully created new NSX-T Distributed Firewall Rule $Name" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } + } +} + +Function Remove-NSXTDistFirewall { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/03/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes an NSX-T Distribugted Firewall Rule + .DESCRIPTION + This cmdlet removes an NSX-T Distribugted Firewall Rule + .EXAMPLE + Remove-NSXTFirewall -Id TEST -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Id, + [Parameter(Mandatory=$True)]$Section, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $sectionId = (Get-NSXTDistFirewallSection -Name $Section).Id + $dfwId = (Get-NSXTDistFirewall -SectionName $Section).Id + + $method = "DELETE" + $deleteDistFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$sectionId/communication-entries/$dfwId" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteDistFirewallURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteDistFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteDistFirewallURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new NSX-T Firewall Rule" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully removed NSX-T Distribugted Firewall Rule" } } } \ No newline at end of file From a2c896b81b1cd7728b3009b8894be39312893ea7 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 4 Jan 2019 06:52:09 -0800 Subject: [PATCH 069/175] Fixing typo + Remove-NSXTDistFirewall function --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index ef83777..f15379f 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1292,7 +1292,7 @@ Function New-NSXTDistFirewall { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break } else { - Write-Error "Error in creating new NSX-T Distribugted Firewall Rule" + Write-Error "Error in creating new NSX-T Distributed Firewall Rule" Write-Error "`n($_.Exception.Message)`n" break } @@ -1331,7 +1331,7 @@ Function Remove-NSXTDistFirewall { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { $sectionId = (Get-NSXTDistFirewallSection -Name $Section).Id - $dfwId = (Get-NSXTDistFirewall -SectionName $Section).Id + $dfwId = (Get-NSXTDistFirewall -SectionName $Section | where { $_.id -eq $Id}).Id $method = "DELETE" $deleteDistFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$sectionId/communication-entries/$dfwId" @@ -1351,14 +1351,14 @@ Function Remove-NSXTDistFirewall { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break } else { - Write-Error "Error in creating new NSX-T Firewall Rule" + Write-Error "Error in removing NSX-T Distributed Firewall Rule" Write-Error "`n($_.Exception.Message)`n" break } } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T Distribugted Firewall Rule" + Write-Host "Succesfully removed NSX-T Distributed Firewall Rule" } } } \ No newline at end of file From 0d75606d99faa3104ea76e0c17de2ce5a31d6791 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 4 Jan 2019 06:54:17 -0800 Subject: [PATCH 070/175] Updating psd1 --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index 9eca367..ef45018 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index f15379f..72bc1e3 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1317,9 +1317,9 @@ Function Remove-NSXTDistFirewall { =========================================================================== .SYNOPSIS - Removes an NSX-T Distribugted Firewall Rule + Removes an NSX-T Distributed Firewall Rule .DESCRIPTION - This cmdlet removes an NSX-T Distribugted Firewall Rule + This cmdlet removes an NSX-T Distributed Firewall Rule .EXAMPLE Remove-NSXTFirewall -Id TEST -Troubleshoot #> From 9073d8f3b23fa1763f68d812f5564ed0a4e7fe32 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Thu, 10 Jan 2019 09:42:14 -0500 Subject: [PATCH 071/175] Create Save-PowerCLI.ps1 Adding function to download specific versions of PowerCLI from an online repository --- Scripts/Save-PowerCLI.ps1 | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Scripts/Save-PowerCLI.ps1 diff --git a/Scripts/Save-PowerCLI.ps1 b/Scripts/Save-PowerCLI.ps1 new file mode 100644 index 0000000..8aa3230 --- /dev/null +++ b/Scripts/Save-PowerCLI.ps1 @@ -0,0 +1,57 @@ +function Save-PowerCLI { +<# +.SYNOPSIS + Function which can be used to easily download specific versions of PowerCLI from an online gallery +.DESCRIPTION + Downloads a specific version of PowerCLI and all the dependencies at the appropriate version +.NOTES + Author: 1.0 - Dimitar Milov +.PARAMETER RequiredVersion + Specify the PowerCLI version +.PARAMETER Path + Directory path where the modules should be downloaded +.PARAMETER Repository + Repository to access the PowerCLI modules +.EXAMPLE + Save-PowerCLI -RequiredVersion '10.0.0.7895300' -Path .\Downloads\ + Downloads PowerCLI 10.0.0 to the Downloads folder +#> + param( + [Parameter(Mandatory = $true)] + [version]$RequiredVersion, + + [Parameter(Mandatory = $true)] + [ValidateScript( { Test-Path $_} )] + [string] + $Path, + + [Parameter()] + [string]$Repository = 'PSGallery' + ) + $powercliModuleName = 'VMware.PowerCLI' + $desiredPowerCLIModule = Find-Module -Name $powercliModuleName -RequiredVersion $RequiredVersion + if (-not $desiredPowerCLIModule) { + throw "'VMware.PowerCLI' with version $RequiredVersion' was not found." + } + + $depsOrder = 'VMware.VimAutomation.Sdk', 'VMware.VimAutomation.Common', 'VMware.Vim', 'VMware.VimAutomation.Cis.Core', 'VMware.VimAutomation.Core', 'VMware.VimAutomation.Nsxt', 'VMware.VimAutomation.Vmc', 'VMware.VimAutomation.Vds', 'VMware.VimAutomation.Srm', 'VMware.ImageBuilder', 'VMware.VimAutomation.Storage', 'VMware.VimAutomation.StorageUtility', 'VMware.VimAutomation.License', 'VMware.VumAutomation', 'VMware.VimAutomation.HorizonView', 'VMware.DeployAutomation', 'VMware.VimAutomation.vROps', 'VMware.VimAutomation.PCloud' + $orderedDependncies = @() + foreach ($depModuleName in $depsOrder) { + $orderedDependncies += $desiredPowerCLIModule.Dependencies | ? {$_.Name -eq $depModuleName} + } + + # Save PowerCLI Module Version + Find-Module -Name $powercliModuleName -RequiredVersion $RequiredVersion | Save-Module -Path $Path + + # Save dependencies with minimum version + foreach ($dependency in $orderedDependncies) { + Find-Module $dependency.Name -RequiredVersion $dependency.MinimumVersion | Save-Module -Path $Path + } + + # Remove newer dependencies versoin + foreach ($dependency in $orderedDependncies) { + Get-ChildItem -Path (Join-Path $path $dependency.Name) | ` + Where-Object {$_.Name -ne $dependency.MinimumVersion} | ` + Remove-Item -Confirm:$false -Force -Recurse + } +} \ No newline at end of file From e35e17a04dea99a56123908cda4f29444d2aaaf3 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Thu, 10 Jan 2019 09:44:58 -0500 Subject: [PATCH 072/175] Update Save-PowerCLI.ps1 Updating function with v2 additions: - Dynamic RequiredVersion parameter - Simple parameter to handle the nested version folders - Address the potential of downloading multiple module folders twice --- Scripts/Save-PowerCLI.ps1 | 202 +++++++++++++++++++++++++++----------- 1 file changed, 146 insertions(+), 56 deletions(-) diff --git a/Scripts/Save-PowerCLI.ps1 b/Scripts/Save-PowerCLI.ps1 index 8aa3230..e9127bc 100644 --- a/Scripts/Save-PowerCLI.ps1 +++ b/Scripts/Save-PowerCLI.ps1 @@ -1,57 +1,147 @@ function Save-PowerCLI { -<# -.SYNOPSIS - Function which can be used to easily download specific versions of PowerCLI from an online gallery -.DESCRIPTION - Downloads a specific version of PowerCLI and all the dependencies at the appropriate version -.NOTES - Author: 1.0 - Dimitar Milov -.PARAMETER RequiredVersion - Specify the PowerCLI version -.PARAMETER Path - Directory path where the modules should be downloaded -.PARAMETER Repository - Repository to access the PowerCLI modules -.EXAMPLE - Save-PowerCLI -RequiredVersion '10.0.0.7895300' -Path .\Downloads\ - Downloads PowerCLI 10.0.0 to the Downloads folder -#> - param( - [Parameter(Mandatory = $true)] - [version]$RequiredVersion, - - [Parameter(Mandatory = $true)] - [ValidateScript( { Test-Path $_} )] - [string] - $Path, - - [Parameter()] - [string]$Repository = 'PSGallery' - ) - $powercliModuleName = 'VMware.PowerCLI' - $desiredPowerCLIModule = Find-Module -Name $powercliModuleName -RequiredVersion $RequiredVersion - if (-not $desiredPowerCLIModule) { - throw "'VMware.PowerCLI' with version $RequiredVersion' was not found." - } - - $depsOrder = 'VMware.VimAutomation.Sdk', 'VMware.VimAutomation.Common', 'VMware.Vim', 'VMware.VimAutomation.Cis.Core', 'VMware.VimAutomation.Core', 'VMware.VimAutomation.Nsxt', 'VMware.VimAutomation.Vmc', 'VMware.VimAutomation.Vds', 'VMware.VimAutomation.Srm', 'VMware.ImageBuilder', 'VMware.VimAutomation.Storage', 'VMware.VimAutomation.StorageUtility', 'VMware.VimAutomation.License', 'VMware.VumAutomation', 'VMware.VimAutomation.HorizonView', 'VMware.DeployAutomation', 'VMware.VimAutomation.vROps', 'VMware.VimAutomation.PCloud' - $orderedDependncies = @() - foreach ($depModuleName in $depsOrder) { - $orderedDependncies += $desiredPowerCLIModule.Dependencies | ? {$_.Name -eq $depModuleName} - } - - # Save PowerCLI Module Version - Find-Module -Name $powercliModuleName -RequiredVersion $RequiredVersion | Save-Module -Path $Path - - # Save dependencies with minimum version - foreach ($dependency in $orderedDependncies) { - Find-Module $dependency.Name -RequiredVersion $dependency.MinimumVersion | Save-Module -Path $Path - } - - # Remove newer dependencies versoin - foreach ($dependency in $orderedDependncies) { - Get-ChildItem -Path (Join-Path $path $dependency.Name) | ` - Where-Object {$_.Name -ne $dependency.MinimumVersion} | ` - Remove-Item -Confirm:$false -Force -Recurse - } -} \ No newline at end of file + <# + .SYNOPSIS + Advanced function which can be used to easily download specific versions of PowerCLI from an online gallery + .DESCRIPTION + Downloads a specific version of PowerCLI and all the dependencies at the appropriate version + .NOTES + Author: 1.0 - Dimitar Milov + Author: 2.0 - Kyle Ruddy, @kmruddy + .PARAMETER RequiredVersion + Dynamic parameter used to specify the PowerCLI version + .PARAMETER Path + Directory path where the modules should be downloaded + .PARAMETER Repository + Repository to access the PowerCLI modules + .PARAMETER Simple + Switch used to specify the nested version folders should be removed (therefore adding PowerShell 3/4 compatibility) + .EXAMPLE + Save-PowerCLI -RequiredVersion '10.0.0.7895300' -Path .\Downloads\ + Downloads PowerCLI 10.0.0 to the Downloads folder + .EXAMPLE + Save-PowerCLI -RequiredVersion '6.5.2.6268016' -Path .\Downloads\ -Simple + Downloads PowerCLI 6.5.2 to the Downloads folder and removes the nested version folders + #> + [CmdletBinding(SupportsShouldProcess = $True)] + param( + [Parameter(Mandatory = $true, Position = 1)] + [ValidateScript( { Test-Path $_} )] + $Path, + [Parameter(Mandatory = $false, Position = 2)] + [string]$Repository = 'PSGallery', + [Parameter(Mandatory = $false, Position = 3)] + [Switch]$Simple + ) + DynamicParam + { + # Set the dynamic parameters name + $ParameterName = 'RequiredVersion' + + # Create the dictionary + $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary + + # Create the collection of attributes + $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + + # Create and set the parameters' attributes + $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute + $ParameterAttribute.ValueFromPipeline = $true + $ParameterAttribute.ValueFromPipelineByPropertyName = $true + $ParameterAttribute.Mandatory = $true + $ParameterAttribute.Position = 0 + + # Add the attributes to the attributes collection + $AttributeCollection.Add($ParameterAttribute) + + # Generate and set the ValidateSet + $pcliVersions = Find-Module -Name 'VMware.PowerCLI' -AllVersions + $arrSet = $pcliVersions | select-Object -ExpandProperty Version + $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) + + # Add the ValidateSet to the attributes collection + $AttributeCollection.Add($ValidateSetAttribute) + + # Create and return the dynamic parameter + $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) + $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) + return $RuntimeParameterDictionary + } + + begin { + $powercliModuleName = 'VMware.PowerCLI' + $desiredPowerCLIModule = Find-Module -Name $powercliModuleName -RequiredVersion $RequiredVersion -Repository $Repository + + $depsOrder = 'VMware.VimAutomation.Sdk', 'VMware.VimAutomation.Common', 'VMware.Vim', 'VMware.VimAutomation.Cis.Core', 'VMware.VimAutomation.Core', 'VMware.VimAutomation.Nsxt', 'VMware.VimAutomation.Vmc', 'VMware.VimAutomation.Vds', 'VMware.VimAutomation.Srm', 'VMware.ImageBuilder', 'VMware.VimAutomation.Storage', 'VMware.VimAutomation.StorageUtility', 'VMware.VimAutomation.License', 'VMware.VumAutomation', 'VMware.VimAutomation.HorizonView', 'VMware.DeployAutomation', 'VMware.VimAutomation.vROps', 'VMware.VimAutomation.PCloud' + $orderedDependencies = @() + foreach ($depModuleName in $depsOrder) { + $orderedDependencies += $desiredPowerCLIModule.Dependencies | Where-Object {$_.Name -eq $depModuleName} + } + + foreach ($remainingDep in $desiredPowerCLIModule.Dependencies) { + if ($orderedDependencies.Name -notcontains $remainingDep.Name) { + $orderedDependencies += $remainingDep + } + + } + } + + process { + # Save PowerCLI Module Version + $desiredPowerCLIModule | Save-Module -Path $Path + + # Working with the depenent modules + foreach ($dependency in $orderedDependencies) { + if (Get-ChildItem -Path (Join-Path $path $dependency.Name) | Where-Object {$_.Name -ne $dependency.MinimumVersion}) { + # Save dependencies with minimum version + Find-Module $dependency.Name -RequiredVersion $dependency.MinimumVersion | Save-Module -Path $Path + + # Remove newer dependencies version + Get-ChildItem -Path (Join-Path $path $dependency.Name) | Where-Object {$_.Name -ne $dependency.MinimumVersion} | Remove-Item -Confirm:$false -Force -Recurse + } + } + } + + end { + if ($Simple) { + + function FolderCleanup { + param( + [Parameter(Mandatory = $true, Position = 0)] + [ValidateScript( { Test-Path $_} )] + $ParentFolder, + [Parameter(Mandatory = $true, Position = 1)] + [String]$ModuleName, + [Parameter(Mandatory = $true, Position = 2)] + $Version + ) + + + $topFolder = Get-Item -Path (Join-Path $ParentFolder $ModuleName) + $versionFolder = $topFolder | Get-ChildItem -Directory | Where-Object {$_.Name -eq $Version} + $versionFolder | Get-ChildItem | Copy-Item -Destination $topFolder + + # Checking for any nested folders within the PowerCLI module version folder + if ($versionFolder| Get-ChildItem -Directory) { + + # Obtaining and storing the child items to a variable, then copying the items to the parent folder's nested folder + $nestFolder = $versionFolder| Get-ChildItem -Directory + foreach ($nestDir in $nestFolder) { + $nestDir | Get-ChildItem | Copy-Item -Destination (Join-Path $topFolder $nestDir.Name) + } + + } + + # Removing any of the former, no longer needed, directory structure + $versionFolder| Remove-Item -Recurse -Force + } + + FolderCleanup -ParentFolder $Path -ModuleName $desiredPowerCLIModule.Name -Version $desiredPowerCLIModule.Version + foreach ($cleanUp in $orderedDependencies) { + + FolderCleanup -ParentFolder $Path -ModuleName $cleanUp.Name -Version $cleanUp.MinimumVersion + } + + } + + } + } \ No newline at end of file From 24556bbe195a7fec85b124b3387d5cd67fbbaf9a Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 10 Jan 2019 15:48:43 -0800 Subject: [PATCH 073/175] Fixed CSP Auth due to API change + Refresh Token expiry info --- Modules/VMware.CSP/VMware.CSP.psm1 | 44 ++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.CSP/VMware.CSP.psm1 b/Modules/VMware.CSP/VMware.CSP.psm1 index b4b4515..0562950 100644 --- a/Modules/VMware.CSP/VMware.CSP.psm1 +++ b/Modules/VMware.CSP/VMware.CSP.psm1 @@ -21,7 +21,8 @@ [Parameter(Mandatory=$true)][String]$RefreshToken ) - $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + $body = "refresh_token=$RefreshToken" + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -Method POST -ContentType "application/x-www-form-urlencoded" -UseBasicParsing -Body $body if($results.StatusCode -ne 200) { Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" break @@ -51,4 +52,43 @@ Function Get-CSPServices { $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/slc/api/definitions?expand=1" -Method GET -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$env:cspAuthToken"} ((($results.Content) | ConvertFrom-Json).results | where {$_.visible -eq $true}).displayName } -} \ No newline at end of file +} + +Function Get-CSPRefreshTokenExpiry { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/10/2019 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .DESCRIPTION + Retrieve the expiry for a given CSP Refresh Token + .PARAMETER RefreshToken + Retrieve the expiry for a given CSP Refresh Token + .EXAMPLE + Get-CSPRefreshTokenExpiry -RefreshToken $RefreshToken + #> + Param ( + [Parameter(Mandatory=$true)][String]$RefreshToken + ) + + $body = @{"tokenValue"="$RefreshToken"} + $json = $body | ConvertTo-Json + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/details" -Method POST -ContentType "application/json" -UseBasicParsing -Body $json + $tokenDetails = (($results.Content) | ConvertFrom-Json) + + $createDate = (Get-Date -Date "01/01/1970").AddMilliseconds($tokenDetails.createdAt).ToLocalTime() + $usedDate = (Get-Date -Date "01/01/1970").AddMilliseconds($tokenDetails.lastUsedAt).ToLocalTime() + $expiryDate = (Get-Date -Date "01/01/1970").AddMilliseconds($tokenDetails.expiresAt).ToLocalTime() + + $tmp = [pscustomobject] @{ + LastUsedDate = $usedDate; + CreatedDate = $createDate; + ExpiryDate = $expiryDate; + } + $tmp | Format-List +} From 59ab2785e3b2d466672d48f7ae41c53df18d4886 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 12 Jan 2019 15:56:50 -0800 Subject: [PATCH 074/175] Added Set-VMCSDDC function to rename SDDC --- Modules/VMware.VMC/VMware.VMC.psm1 | 117 +++++++++++++++++++---------- 1 file changed, 77 insertions(+), 40 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 6605a14..b6c8541 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -918,23 +918,23 @@ Function Get-VMCPublicIP { .EXAMPLE Get-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName - ) + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName + ) - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - $publicIPs = $publicIPService.list($orgId,$sddcId) + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + $publicIPs = $publicIPService.list($orgId,$sddcId) - $publicIPs | select public_ip, name, allocation_id - } + $publicIPs | select public_ip, name, allocation_id } +} - Function New-VMCPublicIP { +Function New-VMCPublicIP { <# .NOTES =========================================================================== @@ -952,28 +952,28 @@ Function Get-VMCPublicIP { .EXAMPLE New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$False)]$Description - ) + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$False)]$Description + ) - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - $publicIPSpec = $publicIPService.Help.create.spec.Create() - $publicIPSpec.count = 1 - $publicIPSpec.names = @($Description) + $publicIPSpec = $publicIPService.Help.create.spec.Create() + $publicIPSpec.count = 1 + $publicIPSpec.names = @($Description) - Write-Host "Requesting a new public IP Address for your SDDC ..." - $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) - } + Write-Host "Requesting a new public IP Address for your SDDC ..." + $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) } +} - Function Remove-VMCPublicIP { +Function Remove-VMCPublicIP { <# .NOTES =========================================================================== @@ -991,21 +991,58 @@ Function Get-VMCPublicIP { .EXAMPLE Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$True)]$AllocationId - ) + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$AllocationId + ) - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - Write-Host "Deleting public IP Address with ID $AllocationId ..." - $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + Write-Host "Deleting public IP Address with ID $AllocationId ..." + $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + } +} + +Function Set-VMCSDDC { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/12/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Rename an SDDC + .DESCRIPTION + This cmdlet renames an SDDC + .EXAMPLE + Set-VMCSDDC -SDDC $SDDCName -OrgName $OrgName -Name $NewSDDCName + #> + Param ( + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$Name + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $sddc = Get-VMCSDDC -Org $OrgName -Name $SDDCName + if($sddc) { + $sddcService = Get-VmcService com.vmware.vmc.orgs.sddcs + $renameSpec = $sddcService.help.patch.sddc_patch_request.Create() + $renameSpec.name = $Name + + Write-Host "`nRenaming SDDC `'$SDDCName`' to `'$Name`' ...`n" + $results = $sddcService.patch($sddc.org_id,$sddc.id,$renameSpec) } } +} -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP' +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', 'Set-VMCSDDC' From ff3d297e697e943611b7fe4845c47f810b5dbcee Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 17 Jan 2019 08:07:15 -0800 Subject: [PATCH 075/175] Fixing typo for creating NSX-T GW Firewall --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 72bc1e3..5466e41 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -476,7 +476,7 @@ Function New-NSXTFirewall { $services = @() foreach ($serviceName in $Service) { - if($group -eq "ANY") { + if($serviceName -eq "ANY") { $services = @("ANY") } else { $tmp = "/infra/services/$serviceName" From 216ee7386fecda5cfa1589c599739cdf7f75a7ba Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 23 Jan 2019 05:25:14 -0800 Subject: [PATCH 076/175] Module for managing vCenter CEIP Settings --- Modules/vCenterCEIP/vCenterCEIP.psm1 | 74 ++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100755 Modules/vCenterCEIP/vCenterCEIP.psm1 diff --git a/Modules/vCenterCEIP/vCenterCEIP.psm1 b/Modules/vCenterCEIP/vCenterCEIP.psm1 new file mode 100755 index 0000000..3d5e903 --- /dev/null +++ b/Modules/vCenterCEIP/vCenterCEIP.psm1 @@ -0,0 +1,74 @@ +Function Get-VCenterCEIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/23/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves the the Customer Experience Improvement Program (CEIP) setting for vCenter Server + .DESCRIPTION + This cmdlet retrieves the the CEIP setting for vCenter Server + .EXAMPLE + Get-VCenterCEIP + #> + If (-Not $global:DefaultVIServer.IsConnected) { Write-error "No valid VC Connection found, please use the Connect-VIServer to connect"; break } Else { + $ceipSettings = (Get-AdvancedSetting -Entity $global:DefaultVIServer -Name VirtualCenter.DataCollector.ConsentData).Value.toString() | ConvertFrom-Json + $ceipEnabled = $ceipSettings.consentConfigurations[0].consentAccepted + + $tmp = [pscustomobject] @{ + VCENTER = $global:DefaultVIServer.Name; + CEIP = $ceipEnabled; + } + $tmp + } +} +Function Set-VCenterCEIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/23/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Enables or Disables the Customer Experience Improvement Program (CEIP) setting for vCenter Server + .DESCRIPTION + This cmdlet enables or disables the CEIP setting for vCenter Server + .EXAMPLE + Set-VCenterCEIP -Enabled + .EXAMPLE + Set-VCenterCEIP -Disabled + #> + Param ( + [Switch]$Enabled, + [Switch]$Disabled + ) + If (-Not $global:DefaultVIServer.IsConnected) { Write-error "No valid VC Connection found, please use the Connect-VIServer to connect"; break } Else { + $ceipSettings = (Get-AdvancedSetting -Entity $global:DefaultVIServer -Name VirtualCenter.DataCollector.ConsentData).Value.toString() | ConvertFrom-Json + If($Enabled) { + $originalVersion = $ceipSettings.version + $ceipSettings.version = [int]$originalVersion + 1 + $ceipSettings.consentConfigurations[0].consentAccepted = $True + $ceipSettings.consentConfigurations[1].consentAccepted = $True + $updatedceipSettings = $ceipSettings | ConvertTo-Json + Write-Host "Enabling Customer Experience Improvement Program (CEIP) ..." + Get-AdvancedSetting -Entity $global:DefaultVIServer -Name VirtualCenter.DataCollector.ConsentData | Set-AdvancedSetting -Value $updatedceipSettings -Confirm:$false + } else { + $originalVersion = $ceipSettings.version + $ceipSettings.version = [int]$originalVersion + 1 + $ceipSettings.consentConfigurations[0].consentAccepted = $False + $ceipSettings.consentConfigurations[1].consentAccepted = $False + $updatedceipSettings = $ceipSettings | ConvertTo-Json + Write-Host "Disablng Customer Experience Improvement Program (CEIP) ..." + Get-AdvancedSetting -Entity $global:DefaultVIServer -Name VirtualCenter.DataCollector.ConsentData | Set-AdvancedSetting -Value $updatedceipSettings -Confirm:$false + } + } +} From 6cc6634628e5e5c53c7e0c36eea46d410d584910 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Fri, 1 Feb 2019 14:19:32 -0500 Subject: [PATCH 077/175] Create Set-NetworkAdapterOpaqueNetwork.ps1 Code sample provided as part of KB 65149: https://kb.vmware.com/s/article/65149 --- Scripts/Set-NetworkAdapterOpaqueNetwork.ps1 | 50 +++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Scripts/Set-NetworkAdapterOpaqueNetwork.ps1 diff --git a/Scripts/Set-NetworkAdapterOpaqueNetwork.ps1 b/Scripts/Set-NetworkAdapterOpaqueNetwork.ps1 new file mode 100644 index 0000000..1310734 --- /dev/null +++ b/Scripts/Set-NetworkAdapterOpaqueNetwork.ps1 @@ -0,0 +1,50 @@ +function Set-NetworkAdapterOpaqueNetwork { +param( + [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [VMware.VimAutomation.Types.NetworkAdapter] + $NetworkAdapter, + + [Parameter(Mandatory = $true, Position = 2)] + [string] + $OpaqueNetworkName, + + [Parameter()] + [switch] + $Connected, + + [Parameter()] + [switch] + $StartConnected +) +process { + $opaqueNetwork = Get-View -ViewType OpaqueNetwork | ? {$_.Name -eq $OpaqueNetworkName} + if (-not $opaqueNetwork) { + throw "'$OpaqueNetworkName' network not found." + } + + $opaqueNetworkBacking = New-Object VMware.Vim.VirtualEthernetCardOpaqueNetworkBackingInfo + $opaqueNetworkBacking.OpaqueNetworkId = $opaqueNetwork.Summary.OpaqueNetworkId + $opaqueNetworkBacking.OpaqueNetworkType = $opaqueNetwork.Summary.OpaqueNetworkType + + $device = $NetworkAdapter.ExtensionData + $device.Backing = $opaqueNetworkBacking + + if ($StartConnected) { + $device.Connectable.StartConnected = $true + } + + if ($Connected) { + $device.Connectable.Connected = $true + } + + $spec = New-Object VMware.Vim.VirtualDeviceConfigSpec + $spec.Operation = [VMware.Vim.VirtualDeviceConfigSpecOperation]::edit + $spec.Device = $device + $configSpec = New-Object VMware.Vim.VirtualMachineConfigSpec + $configSpec.DeviceChange = @($spec) + $NetworkAdapter.Parent.ExtensionData.ReconfigVM($configSpec) + + # Output + Get-NetworkAdapter -Id $NetworkAdapter.Id + } +} From 407be173e404bf388e93698a8695206bc7b8e06c Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 2 Feb 2019 07:34:16 -0800 Subject: [PATCH 078/175] Adding NSX-T Routing Table --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 79 ++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 5466e41..bc2cebd 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1361,4 +1361,83 @@ Function Remove-NSXTDistFirewall { Write-Host "Succesfully removed NSX-T Distributed Firewall Rule" } } +} + +Function Get-NSXTRouteTable { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/02/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves NSX-T Routing Table + .DESCRIPTION + This cmdlet retrieves NSX-T Routing Table. By default, it shows all routes but you can filter by BGP, CONNECTED or STATIC routes + .EXAMPLE + Get-NSXTRouteTable + .EXAMPLE + Get-NSXTRouteTable -RouteSource BGP + .EXAMPLE + Get-NSXTRouteTable -RouteSource CONNECTED + .EXAMPLE + Get-NSXTRouteTable -RouteSource STATIC + .EXAMPLE + Get-NSXTRouteTable -RouteSource BGP -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$False)][ValidateSet("BGP","CONNECTED","STATIC")]$RouteSource, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $routeTableURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/routing-table?enforcement_point_path=/infra/deployment-zones/default/enforcement-points/vmc-enforcementpoint" + + if($RouteSource) { + $routeTableURL = $routeTableURL + "&route_source=$RouteSource" + } + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$routeTableURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $routeTableURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $routeTableURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Routing Table" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully retrieved NSX-T Routing Table`n" + $routeTables = ($requests.Content | ConvertFrom-Json).results + + foreach ($routeTable in $routeTables) { + Write-Host "EdgeNode: $($routeTable.edge_node)" + Write-Host "Entries: $($routeTable.count)" + + $routeEntries = $routeTable.route_entries + $routeEntryResults = @() + foreach ($routeEntry in $routeEntries) { + $routeEntryResults += $routeEntry + } + $routeEntryResults | select network,next_hop,admin_distance,route_type | ft + } + } + } } \ No newline at end of file From 2212477dff9ca34a0e16d34dcd792ad6978993d8 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 8 Feb 2019 05:28:10 -0800 Subject: [PATCH 079/175] Added NSX-T Overview Info --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 55 ++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index ef45018..b74bad7 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index bc2cebd..d120086 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1440,4 +1440,59 @@ Function Get-NSXTRouteTable { } } } +} + +Function Get-NSXTOverviewInfo { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/02/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves NSX-T Overview including the VPN internet IP Address and SDDC Infra/Mgmt Subnets, etc. + .DESCRIPTION + This cmdlet retrieves NSX-T Overview details including the VPN internet IP Address and SDDC Infra/Mgmt Subnets, etc. + .EXAMPLE + Get-NSXTOverviewInfo +#> +Param ( + [Parameter(Mandatory=$False)][ValidateSet("BGP","CONNECTED","STATIC")]$RouteSource, + [Switch]$Troubleshoot +) + +If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $overviewURL = $global:nsxtProxyConnection.Server + "/cloud-service/api/v1/infra/sddc-user-config" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$overviewURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $overviewURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $overviewURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Overview Information" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully retrieved NSX-T Overview Information" + ($requests.Content | ConvertFrom-Json) + } +} } \ No newline at end of file From 0e318d3e07debd3a6275ad3a0a6ca9fabaa05b3d Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Wed, 13 Feb 2019 15:57:51 -0800 Subject: [PATCH 080/175] Create Move-DatastoreCluster.ps1 Moves a datastore cluster to a new location --- Scripts/Move-DatastoreCluster.ps1 | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Scripts/Move-DatastoreCluster.ps1 diff --git a/Scripts/Move-DatastoreCluster.ps1 b/Scripts/Move-DatastoreCluster.ps1 new file mode 100644 index 0000000..a01d3bb --- /dev/null +++ b/Scripts/Move-DatastoreCluster.ps1 @@ -0,0 +1,34 @@ +function Move-DatastoreCluster { +<# +.SYNOPSIS + Moves a datastore cluster to a new location +.DESCRIPTION + Will move a datastore cluster to a new location +.NOTES + Author: Kyle Ruddy, @kmruddy +.PARAMETER DatastoreCluster + Specifies the datastore cluster you want to move. +.PARAMETER Destination + Specifies a destination where you want to place the datastore cluster +.EXAMPLE + Move-DatastoreCluster -DatastoreCluster $DSCluster -Destination $DSClusterFolder + Moves the $DSCluster datastore cluster to the specified $DSClusterFolder folder. +#> +[CmdletBinding(SupportsShouldProcess = $True)] + param( + [Parameter(Mandatory=$false,Position=0,ValueFromPipelineByPropertyName=$true)] + [VMware.VimAutomation.ViCore.Types.V1.DatastoreManagement.DatastoreCluster]$DatastoreCluster, + [Parameter(Mandatory=$false,Position=1,ValueFromPipelineByPropertyName=$true)] + [VMware.VimAutomation.ViCore.Types.V1.Inventory.Folder]$Destination + ) + + if ($Global:DefaultVIServer.IsConnected -eq $false) { + Write-Warning -Message "No vCenter Server connection found." + break + } + + If ($Pscmdlet.ShouldProcess($DatastoreCluster,"Move Datastore Cluster")) { + $Destination.ExtensionData.MoveIntoFolder($DatastoreCluster.ExtensionData.MoRef) + } + +} \ No newline at end of file From ecc12a18847ae884c7ef41018d2bb3bfeeb7b9e6 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Wed, 13 Mar 2019 14:43:33 -0500 Subject: [PATCH 081/175] Address Issue #269 Both flash parameters for `New-HVPool` were limited to the validate set of `LINKED_CLONE`. This updates them to be valid for all desktop types, since it is applicable to all desktop types. See https://vdc-download.vmware.com/vmwb-repository/dcr-public/3721109b-48a5-4ffb-a0ad-6d6a44f2f288/ff45dfca-1050-4265-93ef-4e7d702322e4/vdi.resources.Desktop.AdobeFlashSettings.html for details. --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c150c5f..14972ca 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -3667,13 +3667,19 @@ function New-HVPool { # flashSettings #desktopSpec.desktopSettings.flashSettings.quality [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [ValidateSet('NO_CONTROL', 'LOW', 'MEDIUM', 'HIGH')] - [string]$quality = 'NO_CONTROL', + [string]$Quality = 'NO_CONTROL', #desktopSpec.desktopSettings.flashSettings.throttling [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'FULL_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [ValidateSet('DISABLED', 'CONSERVATIVE', 'MODERATE', 'AGGRESSIVE')] - [string]$throttling = 'DISABLED', + [string]$Throttling = 'DISABLED', #mirageConfigurationOverrides #desktopSpec.desktopSettings.mirageConfigurationOverrides.overrideGlobalSetting @@ -11580,4 +11586,4 @@ Export-ModuleMember -Function Get-HVResourceStructure, Get-HVLocalSession, Get-H # Event Database related Export-ModuleMember -Function Get-HVEventDatabase, Set-HVEventDatabase, Clear-HVEventDatabase, Get-HVEvent, Connect-HVEvent, Disconnect-HVEvent # Misc/other related -Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance \ No newline at end of file +Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance From b8b48e40f806d7753c167e34375189d0dd3d69b7 Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 14 Mar 2019 12:00:27 -0700 Subject: [PATCH 082/175] Add support for both Infra Group/Scopes related to CGW Edge Fireweall --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 195 ++++++++++++++++++- 2 files changed, 194 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index b74bad7..45e549d 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index d120086..70e8ba1 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -403,6 +403,27 @@ Function Get-NSXTFirewall { } } + $scopeEntries = $rule.scope + $scopes = @() + foreach ($scopeEntry in $scopeEntries) { + $scopeLabelURL = $global:nsxtProxyConnection.Server + "/policy/api/v1" + $scopeEntry + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$scopeLabelURL`n" + } + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $scopeLabelURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $scopeLabelURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } + $scope = ($requests.Content | ConvertFrom-Json) + $scopes += $scope.display_name + } + $tmp = [pscustomobject] @{ SequenceNumber = $rule.sequence_number; Name = $rule.display_name; @@ -410,6 +431,7 @@ Function Get-NSXTFirewall { Source = $source; Destination = $destination; Services = $service; + Scope = $scopes; Action = $rule.action; } $results+=$tmp @@ -446,6 +468,9 @@ Function New-NSXTFirewall { [Parameter(Mandatory=$True)]$DestinationGroup, [Parameter(Mandatory=$True)]$Service, [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, + [Parameter(Mandatory=$false)]$InfraScope, + [Parameter(Mandatory=$false)]$SourceInfraGroup, + [Parameter(Mandatory=$false)]$DestinationInfraGroup, [Parameter(Mandatory=$false)][Boolean]$Logged=$false, [Switch]$Troubleshoot ) @@ -464,6 +489,13 @@ Function New-NSXTFirewall { } } + if(! $DestinationInfraGroup) { + foreach ($group in $SourceInfraGroup) { + $tmp = (Get-NSXTInfraGroup -Name $group).Path + $destinationGroups+= $tmp + } + } + $sourceGroups = @() foreach ($group in $SourceGroup) { if($group -eq "ANY") { @@ -474,6 +506,13 @@ Function New-NSXTFirewall { } } + if(! $SourceInfraGroup) { + foreach ($group in $SourceInfraGroup) { + $tmp = (Get-NSXTInfraGroup -Name $group).Path + $sourceGroups+= $tmp + } + } + $services = @() foreach ($serviceName in $Service) { if($serviceName -eq "ANY") { @@ -484,6 +523,16 @@ Function New-NSXTFirewall { } } + $scopeLabels = @() + if(! $InfraScope ) { + $scopeLabels = @("/infra/labels/$($GatewayType.toLower())") + } else { + foreach ($infraScopeName in $InfraScope) { + $scope = Get-NSXTInfraScope -Name $infraScopeName + $scopeLabels += $scope.Path + } + } + $payload = @{ display_name = $Name; resource_type = "CommunicationEntry"; @@ -491,7 +540,7 @@ Function New-NSXTFirewall { destination_groups = $destinationGroups; source_groups = $sourceGroups; logged = $Logged; - scope = @("/infra/labels/$($GatewayType.toLower())"); + scope = $scopeLabels; services = $services; action = $Action; } @@ -1495,4 +1544,146 @@ If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection f ($requests.Content | ConvertFrom-Json) } } -} \ No newline at end of file +} + +Function Get-NSXTInfraScope { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 03/14/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Infrastructure Scopes + .DESCRIPTION + This cmdlet retrieves all NSX-T Infrastructure Scopes + .EXAMPLE + Get-NSXTInfraScope + .EXAMPLE + Get-NSXTInfraGroup -Name "VPN Tunnel Interface" + #> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $infraLabelURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/labels" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$infraLabelURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $infraLabelURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $infraLabelURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Infrastructure Scopes" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $infraLables = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $infraLables = $infraLables | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($infraLabel in $infraLables) { + $tmp = [pscustomobject] @{ + Name = $infraLabel.display_name; + Id = $infraLabel.Id; + Path = $infraLabel.Path; + } + $results+=$tmp + } + $results + } + } +} + +Function Get-NSXTInfraGroup { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 03/14/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Infrastructure Groups for CGW + .DESCRIPTION + This cmdlet retrieves all NSX-T Infrastructure Groups for CGW + .EXAMPLE + Get-NSXTInfraGroup + .EXAMPLE + Get-NSXTInfraGroup -Name "S3 Prefixes" + #> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $infraGroupsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/groups" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$infraGroupsURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $infraGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $infraGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Infrastructure Groups" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $groups = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $groups = $groups | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($group in $groups) { + $tmp = [pscustomobject] @{ + Name = $group.display_name; + ID = $group.id; + Path = $group.path; + } + $results+=$tmp + } + $results + } + } + } \ No newline at end of file From 360e190300465c476e5fe316deb5d5b9ea326414 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Thu, 14 Mar 2019 19:08:01 -0500 Subject: [PATCH 083/175] New HV Functions for vCenter and BaseImage --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 398 +++++++++++++++++- 1 file changed, 389 insertions(+), 9 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c150c5f..17508d7 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -94,6 +94,159 @@ function Get-VcenterID { return $virtualCenterId } +function Get-HVvCenterServer { + <# + .Synopsis + Gets a list of all configured vCenter Servers + + .DESCRIPTION + Queries and returns the vCenter Servers configured for the pod of the specified HVServer. + + .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 + + .PARAMETER Name + A string value to query a vCenter Server by Name, if it is known. + + .EXAMPLE + Get-HVvCenterServer + + .EXAMPLE + Get-HVvCenterServer -Name 'vCenter1' + + .OUTPUTS + Returns array of object type VMware.Hv.VirtualCenterInfo + + .NOTES + Author : Matt Frey. + Author email : mfrey@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.7 + PowerCLI Version : PowerCLI 11.2.0 + PowerShell Version : 5.1 + #> + + param( + [Parameter(Mandatory = $false)] + $HvServer = $null, + + [Parameter(Mandatory = $false)] + [string]$Name = $null + ) + + begin { + $services = Get-ViewAPIService -hvServer $hvServer + + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + + process { + + if ($null -ne $PSBoundParameters.Name) { + $vCenterList = $services.VirtualCenter.VirtualCenter_List() | Where-Object {$_.ServerSpec.ServerName -eq $Name} + } else { + $vCenterList = $services.VirtualCenter.VirtualCenter_List() + } + + } + + end { + + return $vCenterList + + } +} + +function Get-HVvCenterServerHealth { + <# + .Synopsis + Gets a the health info for a given vCenter Server. + + .DESCRIPTION + Queries and returns the VirtualCenterHealthInfo specified HVServer. + + .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 + + .PARAMETER VirtualCenter + A parameter to specify which vCenter Server to check health for. If not specified, this function will return the + health info for all vCenter Servers. + + .EXAMPLE + Get-HVvCenterServerHealth -VirtualCenter 'vCenter1' + + .EXAMPLE + Get-HVvCenterServerHealth -VirtualCenter $vCenter1 + + .EXAMPLE + Get-HVvCenterServerHealth + + .OUTPUTS + Returns array of object type VMware.Hv.VirtualCenterInfo + + .NOTES + Author : Matt Frey. + Author email : mfrey@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.7 + PowerCLI Version : PowerCLI 11.2.0 + PowerShell Version : 5.1 + #> + + param( + [Parameter(Mandatory = $false)] + $HvServer = $null, + + [Parameter(Mandatory = $false)] + $VirtualCenter = $null + ) + + begin { + $services = Get-ViewAPIService -hvServer $hvServer + + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + } + + process { + + if ($null -eq $PSBoundParameters.VirtualCenter) { + $VirtualCenterHealth = $services.VirtualCenterHealth.VirtualCenterHealth_List() + } else { + $objType = $VirtualCenter.getType() | Select-Object -ExpandProperty Name + Switch ($objType) { + 'String' { + $VirtualCenterHealth = $services.VirtualCenterHealth.VirtualCenterHealth_Get($(Get-HVvCenterServer -Name $VirtualCenter | Select-Object -ExpandProperty Id)) + } + 'VirtualCenterInfo' { + $VirtualCenterHealth = $services.VirtualCenterHealth.VirtualCenterHealth_Get($($VirtualCenter | Select-Object -ExpandProperty Id)) + } + 'VirtualCenterId' { + $VirtualCenterHealth = $services.VirtualCenterHealth.VirtualCenterHealth_Get($VirtualCenter) + } + } + } + + } + + end { + + return $VirtualCenterHealth + + } +} + function Get-JsonObject { param( [Parameter(Mandatory = $true)] @@ -462,8 +615,6 @@ function Add-HVRDSServer { } } - - function Connect-HVEvent { <# .SYNOPSIS @@ -2790,7 +2941,6 @@ function Test-HVFarmSpec { } } - function Get-HVFarmProvisioningData { param( [Parameter(Mandatory = $false)] @@ -2865,7 +3015,6 @@ function Get-HVFarmProvisioningData { return $vmObject } - function Get-HVFarmStorageObject { param( @@ -2933,7 +3082,6 @@ function Get-HVFarmStorageObject { return $storageObject } - function Get-HVFarmNetworkSetting { param( [Parameter(Mandatory = $false)] @@ -2945,7 +3093,6 @@ function Get-HVFarmNetworkSetting { return $networkObject } - function Get-HVFarmCustomizationSetting { param( [Parameter(Mandatory = $false)] @@ -3078,7 +3225,6 @@ function Get-FarmSpec { return $farm_spec_helper.getDataObject() } - function New-HVPool { <# .Synopsis @@ -4922,7 +5068,6 @@ function Get-HVPoolProvisioningData { return $vmObject } - function Get-HVHostOrClusterID { <# .Synopsis @@ -6902,6 +7047,239 @@ function Get-Machine ($Pool,$MachineList) { return $machines } +function Get-HVBaseImageVM { + <# + .Synopsis + Gets a list of compatible base image virtual machines. + + .DESCRIPTION + Queries and returns BaseImageVmInfo for the specified vCenter Server. + + .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. + + .PARAMETER VirtualCenter + A parameter to specify which vCenter Server to check base image VMs for. It can be specified as a String, + containing the name of the vCenter, or as a vCenter object as returned by Get-HVvCenterServer. If the value is + not passed or null then first element returned from Get-HVvCenterServer would be considered in place of VirtualCenter. + + .PARAMETER ImageType + A parameter to define the type of compatability to check the base image VM list against. Valid options are 'VDI', 'RDS', or 'ALL' + 'VDI' will return all desktop compatible Base Image VMs. + 'RDS' will return all RDSH compatible Base Image VMs. + 'ALL' will return all Base Image VMs, regardless of compatibility. + The default value is 'ALL'. + + .PARAMETER Name + The name of a virtual machine (if known), to filter Base Image VMs on. Wildcards are accepted. If Name is specified, then ImageType + is not considered for filtering. + + .EXAMPLE + Get-HVBaseImageVM -VirtualCenter 'vCenter1' -ImageType VDI + + .EXAMPLE + Get-HVBaseImageVM -VirtualCenter $vCenter1 -ImageType ALL + + .EXAMPLE + Get-HVBaseImageVM -Name '*WIN10*' + + .OUTPUTS + Returns array of object type VMware.Hv.BaseImageVmInfo + + .NOTES + Author : Matt Frey. + Author email : mfrey@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.7 + PowerCLI Version : PowerCLI 11.2.0 + PowerShell Version : 5.1 + #> + + [cmdletbinding( + DefaultParameterSetName='ImageType' + )] + + param( + [Parameter(Mandatory = $false)] + $HvServer = $null, + + [Parameter(Mandatory = $false)] + $VirtualCenter = $null, + + [Parameter(Mandatory = $false,ParameterSetName = 'ImageType')] + [ValidateSet('VDI','RDS','ALL')] + $ImageType = 'VDI', + + [Parameter(Mandatory = $false,ParameterSetName = 'Name')] + [string]$Name = $null + ) + + begin { + $services = Get-ViewAPIService -hvServer $hvServer + + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + + if ($null -eq $PSBoundParameters.VirtualCenter) { + $VirtualCenterId = Get-HVvCenterServer | Select-Object -First 1 -ExpandProperty Id + } else { + $objType = $VirtualCenter.getType() | Select-Object -ExpandProperty Name + Switch ($objType) { + 'String' { + $VirtualCenterId = Get-HVvCenterServer -Name $VirtualCenter | Select-Object -ExpandProperty Id + } + 'VirtualCenterInfo' { + $VirtualCenterId = $VirtualCenter | Select-Object -ExpandProperty Id + } + 'VirtualCenterId' { + $VirtualCenterId = $VirtualCenter + } + } + } + + } + + process { + + $BaseImageVMList = $services.BaseImageVM.BaseImageVM_List($VirtualCenterId) + + #For all conditions, see https://vdc-download.vmware.com/vmwb-repository/dcr-public/3721109b-48a5-4ffb-a0ad-6d6a44f2f288/ff45dfca-1050-4265-93ef-4e7d702322e4/vdi.utils.virtualcenter.BaseImageVm.BaseImageVmIncompatibleReasons.html + + If ($null -ne $PSBoundParameters.Name) { + $CompatibleBaseImageVMs = $BaseImageVMList | Where-Object {$_.Name -like $Name} + } Else { + Switch ($ImageType) { + + 'VDI' { + $CompatibleBaseImageVMs = $BaseImageVMList | Where-Object { + ($_.IncompatibleReasons.InUseByDesktop -eq $false) -and + ($_.IncompatibleReasons.InUseByLinkedCloneDesktop -eq $false) -and + ($_.IncompatibleReasons.ViewComposerReplica -eq $false) -and + ($_.IncompatibleReasons.UnsupportedOS -eq $false) -and + ($_.IncompatibleReasons.NoSnapshots -eq $false) -and + (($null -eq $_.IncompatibleReasons.InstantInternal) -or ($_.IncompatibleReasons.InstantInternal -eq $false)) + } + } + 'RDS' { + $CompatibleBaseImageVMs = $BaseImageVMList | Where-Object { + ($_.IncompatibleReasons.InUseByDesktop -eq $false) -and + ($_.IncompatibleReasons.InUseByLinkedCloneDesktop -eq $false) -and + ($_.IncompatibleReasons.ViewComposerReplica -eq $false) -and + ($_.IncompatibleReasons.UnsupportedOSForLinkedCloneFarm -eq $false) -and + ($_.IncompatibleReasons.NoSnapshots -eq $false) -and + (($null -eq $_.IncompatibleReasons.InstantInternal) -or ($_.IncompatibleReasons.InstantInternal -eq $false)) + } + } + 'ALL' { + $CompatibleBaseImageVMs = $BaseImageVMList + } + + } + } + + } + + end { + + return $CompatibleBaseImageVMs + + } +} + +function Get-HVBaseImageSnapshot { + <# + .Synopsis + Gets a list of compatible base image virtual machines. + + .DESCRIPTION + Queries and returns BaseImageVmInfo for the specified vCenter Server. + + .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. + + .PARAMETER BaseImageVM + The BaseImageVM to query snapshots for. This parameter is required. Wildcards are accepted. This parameter also supports + pipeline operations with Get-HVBaseImageVM + + .EXAMPLE + Get-HVBaseImageSnapshots -BaseImageVM 'WIN10-BaseImage' + + .EXAMPLE + Get-HVBaseImageSnapshots -BaseImageVM '*WIN10*' + + .EXAMPLE + Get-HVBaseImageVM -Name 'WIN10-BaseImage' | Get-HVBaseImageSnapshots + + .OUTPUTS + Array of object type VMware.Hv.BaseImageSnapshotInfo + + .NOTES + Author : Matt Frey. + Author email : mfrey@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.7 + PowerCLI Version : PowerCLI 11.2.0 + PowerShell Version : 5.1 + #> + + [cmdletbinding( + DefaultParameterSetName='ImageType' + )] + + param( + [Parameter(Mandatory = $false)] + $HvServer = $null, + + [Parameter(Mandatory = $true,ValueFromPipeLine=$true)] + $BaseImageVM = $null + ) + + begin { + $services = Get-ViewAPIService -hvServer $hvServer + + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + + } + + process { + + if ($null -ne $PSBoundParameters.BaseImageVM) { + $objType = $BaseImageVM.getType() | Select-Object -ExpandProperty Name + Switch ($objType) { + 'String' { + $BaseImageVMObj = Get-HVBaseImageVM -Name $BaseImageVM + } + 'BaseImageVMInfo' { + $BaseImageVMObj = $BaseImageVM + } + 'Object[]' { + Write-Error 'This function cannot accept an array of Base Image VMs. You must specify only a single Base Image VM.' + Break + } + } + $BaseImageSnapshotList = $services.BaseImageSnapshot.BaseImageSnapshot_List($BaseImageVMObj.Id) + } + + } + + end { + + return $BaseImageSnapshotList + + } +} + function Set-HVPoolSpec { param( [Parameter(Mandatory = $true)] @@ -11579,5 +11957,7 @@ Export-ModuleMember -Function Get-HVGlobalSettings, Set-HVApplicationIcon, Remov Export-ModuleMember -Function Get-HVResourceStructure, Get-HVLocalSession, Get-HVGlobalSession # Event Database related Export-ModuleMember -Function Get-HVEventDatabase, Set-HVEventDatabase, Clear-HVEventDatabase, Get-HVEvent, Connect-HVEvent, Disconnect-HVEvent +# vCenter Server related +Export-ModuleMember -Function Get-HVvCenterServer, Get-HVvCenterServerHealth # Misc/other related -Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance \ No newline at end of file +Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot \ No newline at end of file From 29fbb5bc59d447981b71b9e5a116fdf0bd8ae10c Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 15 Mar 2019 05:13:37 -0700 Subject: [PATCH 084/175] Fixing optional for Source/Destination Groups + typo --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 70e8ba1..de52816 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -464,8 +464,8 @@ Function New-NSXTFirewall { [Parameter(Mandatory=$True)]$Name, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$True)]$SequenceNumber, - [Parameter(Mandatory=$True)]$SourceGroup, - [Parameter(Mandatory=$True)]$DestinationGroup, + [Parameter(Mandatory=$False)]$SourceGroup, + [Parameter(Mandatory=$False)]$DestinationGroup, [Parameter(Mandatory=$True)]$Service, [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, [Parameter(Mandatory=$false)]$InfraScope, @@ -490,7 +490,7 @@ Function New-NSXTFirewall { } if(! $DestinationInfraGroup) { - foreach ($group in $SourceInfraGroup) { + foreach ($group in $DestinationInfraGroup) { $tmp = (Get-NSXTInfraGroup -Name $group).Path $destinationGroups+= $tmp } From 72a55558609fb85f23befafc87d7a9648504af5d Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 15 Mar 2019 10:46:43 -0700 Subject: [PATCH 085/175] Fixing logic for SRC/DST Infra Group --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index de52816..eb54158 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -489,7 +489,7 @@ Function New-NSXTFirewall { } } - if(! $DestinationInfraGroup) { + if($DestinationInfraGroup) { foreach ($group in $DestinationInfraGroup) { $tmp = (Get-NSXTInfraGroup -Name $group).Path $destinationGroups+= $tmp @@ -506,7 +506,7 @@ Function New-NSXTFirewall { } } - if(! $SourceInfraGroup) { + if($SourceInfraGroup) { foreach ($group in $SourceInfraGroup) { $tmp = (Get-NSXTInfraGroup -Name $group).Path $sourceGroups+= $tmp From bda5a5a276ca016a4861ca53489203f5b14722f5 Mon Sep 17 00:00:00 2001 From: William Lam Date: Mon, 18 Mar 2019 13:39:52 -0700 Subject: [PATCH 086/175] Fixing the default Scope label for CGW FW Rules --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index eb54158..fcfbe3c 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -524,8 +524,8 @@ Function New-NSXTFirewall { } $scopeLabels = @() - if(! $InfraScope ) { - $scopeLabels = @("/infra/labels/$($GatewayType.toLower())") + if(!$InfraScope) { + $scopeLabels = @("/infra/labels/$($GatewayType.toLower())-all") } else { foreach ($infraScopeName in $InfraScope) { $scope = Get-NSXTInfraScope -Name $infraScopeName From d95806ea2f2f91546c815ffaeb8ae3171a9d7fe4 Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 19 Mar 2019 10:31:20 -0700 Subject: [PATCH 087/175] Fix CGW/MGW scope --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index fcfbe3c..d29abbc 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -525,7 +525,11 @@ Function New-NSXTFirewall { $scopeLabels = @() if(!$InfraScope) { - $scopeLabels = @("/infra/labels/$($GatewayType.toLower())-all") + if($GatewayType.toLower() -eq "cgw") { + $scopeLabels = @("/infra/labels/$($GatewayType.toLower())-all") + } else { + $scopeLabels = @("/infra/labels/$($GatewayType.toLower())") + } } else { foreach ($infraScopeName in $InfraScope) { $scope = Get-NSXTInfraScope -Name $infraScopeName From 1c54a37fbdeb56ac33146d1ff27f084448f9b8bd Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Tue, 19 Mar 2019 15:06:54 -0700 Subject: [PATCH 088/175] Shortened ImageType to Type --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 17508d7..d47d6b5 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -7064,7 +7064,7 @@ function Get-HVBaseImageVM { containing the name of the vCenter, or as a vCenter object as returned by Get-HVvCenterServer. If the value is not passed or null then first element returned from Get-HVvCenterServer would be considered in place of VirtualCenter. - .PARAMETER ImageType + .PARAMETER Type A parameter to define the type of compatability to check the base image VM list against. Valid options are 'VDI', 'RDS', or 'ALL' 'VDI' will return all desktop compatible Base Image VMs. 'RDS' will return all RDSH compatible Base Image VMs. @@ -7072,14 +7072,14 @@ function Get-HVBaseImageVM { The default value is 'ALL'. .PARAMETER Name - The name of a virtual machine (if known), to filter Base Image VMs on. Wildcards are accepted. If Name is specified, then ImageType + The name of a virtual machine (if known), to filter Base Image VMs on. Wildcards are accepted. If Name is specified, then Type is not considered for filtering. .EXAMPLE - Get-HVBaseImageVM -VirtualCenter 'vCenter1' -ImageType VDI + Get-HVBaseImageVM -VirtualCenter 'vCenter1' -Type VDI .EXAMPLE - Get-HVBaseImageVM -VirtualCenter $vCenter1 -ImageType ALL + Get-HVBaseImageVM -VirtualCenter $vCenter1 -Type ALL .EXAMPLE Get-HVBaseImageVM -Name '*WIN10*' @@ -7099,7 +7099,7 @@ function Get-HVBaseImageVM { #> [cmdletbinding( - DefaultParameterSetName='ImageType' + DefaultParameterSetName='Type' )] param( @@ -7109,9 +7109,9 @@ function Get-HVBaseImageVM { [Parameter(Mandatory = $false)] $VirtualCenter = $null, - [Parameter(Mandatory = $false,ParameterSetName = 'ImageType')] + [Parameter(Mandatory = $false,ParameterSetName = 'Type')] [ValidateSet('VDI','RDS','ALL')] - $ImageType = 'VDI', + $Type = 'VDI', [Parameter(Mandatory = $false,ParameterSetName = 'Name')] [string]$Name = $null @@ -7153,7 +7153,7 @@ function Get-HVBaseImageVM { If ($null -ne $PSBoundParameters.Name) { $CompatibleBaseImageVMs = $BaseImageVMList | Where-Object {$_.Name -like $Name} } Else { - Switch ($ImageType) { + Switch ($Type) { 'VDI' { $CompatibleBaseImageVMs = $BaseImageVMList | Where-Object { @@ -7231,7 +7231,7 @@ function Get-HVBaseImageSnapshot { #> [cmdletbinding( - DefaultParameterSetName='ImageType' + DefaultParameterSetName='Type' )] param( From fe603f60d65096cfa443fbee846ad81fbdd12517 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Tue, 26 Mar 2019 23:55:29 -0400 Subject: [PATCH 089/175] Add SDDC Cluster Functions Added the following functions: Get-VMCSDDCCluster New-VMCSDDCCluster Remove-VMCSDDCCluster --- Modules/VMware.VMC/VMware.VMC.psd1 | Bin 8558 -> 8696 bytes Modules/VMware.VMC/VMware.VMC.psm1 | 203 ++++++++++++++++++++++++++++- 2 files changed, 199 insertions(+), 4 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psd1 b/Modules/VMware.VMC/VMware.VMC.psd1 index 105fec0612b9384cc68ec1d1240ff768945cef05..020717c99a0e06de49d27ef6235b0a50c69faad1 100755 GIT binary patch delta 111 zcmaFo^uu|B6ceNIW@)Bm;mJOtB9r@sI4qqRau`Y(iWy26QW=UE)ERUb6o8~3kXO#2 h%Mixk%izoq%-{lq&OnHycCx*QtSDBQ&DElxxdDP27(f63 delta 19 acmez2{LX2E6ceM-W@)Bm;msUkAGiTZ8wPy< diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index de3d1ab..d7a824f 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -690,7 +690,7 @@ Function Get-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://thatcouldbeaproblem.com + Blog: https://www.kmruddy.com Twitter: @kmruddy =========================================================================== @@ -761,7 +761,7 @@ Function Remove-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://thatcouldbeaproblem.com + Blog: https://www.kmruddy.com Twitter: @kmruddy =========================================================================== @@ -808,7 +808,7 @@ Function New-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://thatcouldbeaproblem.com + Blog: https://www.kmruddy.com Twitter: @kmruddy =========================================================================== @@ -1299,10 +1299,205 @@ Twitter: @LucD22 } } } +Function New-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new cluster for the designated SDDC + .DESCRIPTION + Creates a new cluster + .EXAMPLE + New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][Int]$HostCount, + [Parameter(Mandatory=$true)][ValidateSet("8","16","32")]$CPUCoreCount + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters + + $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() + $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount + $sddcClusterCreateSpec.num_hosts = $HostCount + + $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} +Function Get-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Retreives cluster information for the designated SDDC + .DESCRIPTION + Lists cluster information for an SDDC + .EXAMPLE + Get-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='Low')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SddcName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $clusterOutput = @() + $sddcClusters = Get-VMCSDDC -Org $OrgName -Name $SDDCName | Select-Object -ExpandProperty resource_config | Select-Object -ExpandProperty clusters + foreach ($c in $sddcClusters) { + $tempCluster = "" | Select-Object Id, Name, State + $tempCluster.Id = $c.cluster_id + $tempCluster.Name = $c.cluster_name + $tempCluster.State = $c.cluster_state + $clusterOutput += $tempCluster + } + return $clusterOutput +} +Function New-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new cluster for the designated SDDC + .DESCRIPTION + Creates a new cluster + .EXAMPLE + New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SddcName, + [Parameter(Mandatory=$true)][Int]$HostCount, + [Parameter(Mandatory=$false)][ValidateSet("8","16","36","48")]$CPUCoreCount + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters + + $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() + $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount + $sddcClusterCreateSpec.num_hosts = $HostCount + + $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} +Function Remove-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Removes a specified cluster from the designated SDDC + .DESCRIPTION + Deletes a cluster from an SDDC + .EXAMPLE + Remove-VMCSDDCCluster -OrgName -SDDCName -Cluster + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][String]$ClusterName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + $clusterId = Get-VMCSDDCCluster -SddcName $SDDCName -OrgName $OrgName | Where-Object {$_.Name -eq $ClusterName} | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + if(-not $clusterId) { + Write-Host -ForegroundColor red "Unable to find cluster $ClusterName, please verify input" + break + } + + $sddcClusterTask = $sddcClusterSvc.Delete($orgId, $sddcId, $clusterId) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', - 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat' + 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat', + 'Get-VMCSDDCCluster', 'New-VMCSDDCCluster', 'Remove-VMCSDDCCluster' From 45ac4a47fb73b2d850266cbcff8836645ae389a3 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Wed, 27 Mar 2019 00:00:01 -0400 Subject: [PATCH 090/175] Revert "Add SDDC Cluster Functions" This reverts commit fe603f60d65096cfa443fbee846ad81fbdd12517. --- Modules/VMware.VMC/VMware.VMC.psd1 | Bin 8696 -> 8558 bytes Modules/VMware.VMC/VMware.VMC.psm1 | 203 +---------------------------- 2 files changed, 4 insertions(+), 199 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psd1 b/Modules/VMware.VMC/VMware.VMC.psd1 index 020717c99a0e06de49d27ef6235b0a50c69faad1..105fec0612b9384cc68ec1d1240ff768945cef05 100755 GIT binary patch delta 19 acmez2{LX2E6ceM-W@)Bm;msUkAGiTZ8wPy< delta 111 zcmaFo^uu|B6ceNIW@)Bm;mJOtB9r@sI4qqRau`Y(iWy26QW=UE)ERUb6o8~3kXO#2 h%Mixk%izoq%-{lq&OnHycCx*QtSDBQ&DElxxdDP27(f63 diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index d7a824f..de3d1ab 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -690,7 +690,7 @@ Function Get-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://www.kmruddy.com + Blog: https://thatcouldbeaproblem.com Twitter: @kmruddy =========================================================================== @@ -761,7 +761,7 @@ Function Remove-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://www.kmruddy.com + Blog: https://thatcouldbeaproblem.com Twitter: @kmruddy =========================================================================== @@ -808,7 +808,7 @@ Function New-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://www.kmruddy.com + Blog: https://thatcouldbeaproblem.com Twitter: @kmruddy =========================================================================== @@ -1299,205 +1299,10 @@ Twitter: @LucD22 } } } -Function New-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Creates a new cluster for the designated SDDC - .DESCRIPTION - Creates a new cluster - .EXAMPLE - New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][Int]$HostCount, - [Parameter(Mandatory=$true)][ValidateSet("8","16","32")]$CPUCoreCount - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters - - $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() - $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount - $sddcClusterCreateSpec.num_hosts = $HostCount - - $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) - $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table -} -Function Get-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Retreives cluster information for the designated SDDC - .DESCRIPTION - Lists cluster information for an SDDC - .EXAMPLE - Get-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='Low')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SddcName - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $clusterOutput = @() - $sddcClusters = Get-VMCSDDC -Org $OrgName -Name $SDDCName | Select-Object -ExpandProperty resource_config | Select-Object -ExpandProperty clusters - foreach ($c in $sddcClusters) { - $tempCluster = "" | Select-Object Id, Name, State - $tempCluster.Id = $c.cluster_id - $tempCluster.Name = $c.cluster_name - $tempCluster.State = $c.cluster_state - $clusterOutput += $tempCluster - } - return $clusterOutput -} -Function New-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Creates a new cluster for the designated SDDC - .DESCRIPTION - Creates a new cluster - .EXAMPLE - New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SddcName, - [Parameter(Mandatory=$true)][Int]$HostCount, - [Parameter(Mandatory=$false)][ValidateSet("8","16","36","48")]$CPUCoreCount - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters - - $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() - $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount - $sddcClusterCreateSpec.num_hosts = $HostCount - - $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) - $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table -} -Function Remove-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Removes a specified cluster from the designated SDDC - .DESCRIPTION - Deletes a cluster from an SDDC - .EXAMPLE - Remove-VMCSDDCCluster -OrgName -SDDCName -Cluster - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][String]$ClusterName - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - $clusterId = Get-VMCSDDCCluster -SddcName $SDDCName -OrgName $OrgName | Where-Object {$_.Name -eq $ClusterName} | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - if(-not $clusterId) { - Write-Host -ForegroundColor red "Unable to find cluster $ClusterName, please verify input" - break - } - - $sddcClusterTask = $sddcClusterSvc.Delete($orgId, $sddcId, $clusterId) - $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table -} Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', - 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat', - 'Get-VMCSDDCCluster', 'New-VMCSDDCCluster', 'Remove-VMCSDDCCluster' + 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat' From 528eca815c35e4db8f2f935b723a3a2ba8ebf4b8 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Wed, 27 Mar 2019 00:12:03 -0400 Subject: [PATCH 091/175] Add SDDC Cluster Functions Add the following SDDC Cluster Functions: Get-VMCSDDCCluster New-VMCSDDCCluster Remove-VMCSDDCCluster --- Modules/VMware.VMC/VMware.VMC.psd1 | Bin 8558 -> 8706 bytes Modules/VMware.VMC/VMware.VMC.psm1 | 204 ++++++++++++++++++++++++++++- 2 files changed, 199 insertions(+), 5 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psd1 b/Modules/VMware.VMC/VMware.VMC.psd1 index 105fec0612b9384cc68ec1d1240ff768945cef05..397ab8df97385b930488b229cabe25d0817ac0b1 100755 GIT binary patch delta 121 zcmaFo)a0^3iiy#9vouq(@MIrRk;#2R9L~-RISi!?#SA43sSHI7>I^yz3JhF841wwl nen9bZ23>|Q244nehF}I4Aan*oBwds3MPx;>%51I{{mcyj;64~% delta 19 acmZp2dFQl2iiy!^vouq(@Ma;g58MDjlLit1 diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 33f78a7..f2151c9 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -690,7 +690,7 @@ Function Get-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://thatcouldbeaproblem.com + Blog: https://www.kmruddy.com Twitter: @kmruddy =========================================================================== @@ -761,7 +761,7 @@ Function Remove-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://thatcouldbeaproblem.com + Blog: https://www.kmruddy.com Twitter: @kmruddy =========================================================================== @@ -808,7 +808,7 @@ Function New-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://thatcouldbeaproblem.com + Blog: https://www.kmruddy.com Twitter: @kmruddy =========================================================================== @@ -1417,11 +1417,205 @@ Twitter: @LucD22 } } } +Function New-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new cluster for the designated SDDC + .DESCRIPTION + Creates a new cluster + .EXAMPLE + New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][Int]$HostCount, + [Parameter(Mandatory=$true)][ValidateSet("8","16","32")]$CPUCoreCount + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters + + $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() + $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount + $sddcClusterCreateSpec.num_hosts = $HostCount + + $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} +Function Get-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Retreives cluster information for the designated SDDC + .DESCRIPTION + Lists cluster information for an SDDC + .EXAMPLE + Get-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='Low')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SddcName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $clusterOutput = @() + $sddcClusters = Get-VMCSDDC -Org $OrgName -Name $SDDCName | Select-Object -ExpandProperty resource_config | Select-Object -ExpandProperty clusters + foreach ($c in $sddcClusters) { + $tempCluster = "" | Select-Object Id, Name, State + $tempCluster.Id = $c.cluster_id + $tempCluster.Name = $c.cluster_name + $tempCluster.State = $c.cluster_state + $clusterOutput += $tempCluster + } + return $clusterOutput +} +Function New-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new cluster for the designated SDDC + .DESCRIPTION + Creates a new cluster + .EXAMPLE + New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SddcName, + [Parameter(Mandatory=$true)][Int]$HostCount, + [Parameter(Mandatory=$false)][ValidateSet("8","16","36","48")]$CPUCoreCount + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters + + $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() + $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount + $sddcClusterCreateSpec.num_hosts = $HostCount + + $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} +Function Remove-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Removes a specified cluster from the designated SDDC + .DESCRIPTION + Deletes a cluster from an SDDC + .EXAMPLE + Remove-VMCSDDCCluster -OrgName -SDDCName -Cluster + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][String]$ClusterName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + $clusterId = Get-VMCSDDCCluster -SddcName $SDDCName -OrgName $OrgName | Where-Object {$_.Name -eq $ClusterName} | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + if(-not $clusterId) { + Write-Host -ForegroundColor red "Unable to find cluster $ClusterName, please verify input" + break + } + + $sddcClusterTask = $sddcClusterSvc.Delete($orgId, $sddcId, $clusterId) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', 'Set-VMCSDDC', - 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat' - + 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat', + 'Get-VMCSDDCCluster', 'New-VMCSDDCCluster', 'Remove-VMCSDDCCluster' \ No newline at end of file From db8f4407a04b4e0717673cff133665e7c499b3c3 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Fri, 5 Apr 2019 11:19:38 -0500 Subject: [PATCH 092/175] Address Issue #273 --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index f176258..5d4e80f 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -2057,7 +2057,7 @@ function New-HVFarm { Set to true to enable provision of RDSServers immediately in farm. Applicable to Linked Clone and Instant Clone farms. -.PARAMETER StopOnProvisioningError +.PARAMETER StopProvisioningOnError Set to true to stop provisioning of all RDSServers on error. Applicable to Linked Clone and Instant Clone farms. @@ -2130,11 +2130,11 @@ function New-HVFarm { 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 -StopProvisioningOnError $false -NamingPattern "LCFarmVM_PS" -MinReady 1 -MaximumCount 1 -SysPrepName "RDSH_Cust2" -NetBiosName "adviewdev" Creates new linkedClone farm by using naming pattern .EXAMPLE - 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" + 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 -StopProvisioningOnError $false -NamingPattern "ICFarmCL-" -NetBiosName "ad-vimalg" Creates new linkedClone farm by using naming pattern .EXAMPLE @@ -2344,11 +2344,11 @@ function New-HVFarm { [boolean] $EnableProvisioning = $true, - #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.stopOnProvisioningError if LINKED_CLONE, INSTANT_CLONE + #farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.stopProvisioningOnError if LINKED_CLONE, INSTANT_CLONE [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [boolean] - $StopOnProvisioningError = $true, + $StopProvisioningOnError = $true, [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] @@ -3448,7 +3448,7 @@ function New-HVPool { .PARAMETER BlackoutTimes A list of blackout times. -.PARAMETER StopOnProvisioningError +.PARAMETER StopProvisioningOnError Set to true to stop provisioning of all VMs on error. Applicable to Full, Linked, Instant Clone Pools. @@ -3575,7 +3575,7 @@ function New-HVPool { 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 + 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 -StopProvisioningOnError $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 .EXAMPLE @@ -4030,12 +4030,12 @@ function New-HVPool { [boolean] $EnableProvisioning = $true, - #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.stopOnProvisioningError if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + #desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.stopProvisioningOnError 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] - $StopOnProvisioningError = $true, + $StopProvisioningOnError = $true, [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] From 3b5f501d724065c945c0a40d35b379da2d11dabe Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Mon, 8 Apr 2019 00:56:49 -0500 Subject: [PATCH 093/175] Address Issue #180 --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 5d4e80f..bfbd71a 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -4310,6 +4310,7 @@ function New-HVPool { $adContainer = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.AdContainer } $custType = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CustomizationType + $reusePreExistingAccounts = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.reusePreExistingAccounts if ($jsonObject.AutomatedDesktopSpec.ProvisioningType -eq "INSTANT_CLONE_ENGINE") { $InstantClone = $true if ($null -ne $jsonObject.AutomatedDesktopSpec.CustomizationSettings.CloneprepCustomizationSettings) { @@ -4330,7 +4331,6 @@ function New-HVPool { 'SYS_PREP' { $sysprepCustomizationSettings = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.SysprepCustomizationSettings $sysPrepName = $sysprepCustomizationSettings.customizationSpec - $reusePreExistingAccounts = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.reusePreExistingAccounts } 'QUICK_PREP' { $powerOffScriptName = $jsonObject.AutomatedDesktopSpec.CustomizationSettings.QuickprepCustomizationSettings.PowerOffScriptName @@ -5401,7 +5401,7 @@ function Get-HVPoolCustomizationSetting { } if ($null -eq $ViewComposerDomainAdministratorID) { throw "No Composer Domain Administrator found with netBiosName: [$netBiosName]" - } + } if ($custType -eq 'SYS_PREP') { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = 'SYS_PREP' $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.SysprepCustomizationSettings = Get-CustomizationObject @@ -5425,6 +5425,7 @@ function Get-HVPoolCustomizationSetting { throw "The customization type: [$custType] is not supported for LinkedClone Pool" } $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.DomainAdministrator = $ViewComposerDomainAdministratorID + $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.ReusePreExistingAccounts = $reusePreExistingAccounts } elseIf ($FullClone) { if ($custType -eq 'SYS_PREP') { $desktopSpecObj.AutomatedDesktopSpec.CustomizationSettings.CustomizationType = 'SYS_PREP' From b95886558fefd7eefb929aa866eb198037b9cba3 Mon Sep 17 00:00:00 2001 From: Mark McGilly Date: Tue, 9 Apr 2019 10:55:34 -0400 Subject: [PATCH 094/175] Get-HcxMigration: Allow array of MigrationIds --- Modules/VMware.HCX/VMware.HCX.psm1 | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index cfbe95b..5582681 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -453,12 +453,23 @@ Function Get-HcxMigration { Get-HcxMigration -MigrationId #> Param ( - [Parameter(Mandatory=$false)][String]$MigrationId, + [Parameter(Mandatory=$false)][String[]]$MigrationId, [Switch]$RunningMigrations ) If (-Not $global:hcxConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxManager " } Else { - $spec = @{} + If($PSBoundParameters.ContainsKey("MigrationId")){ + $spec = @{ + filter = @{ + migrationId = $MigrationId + } + paging =@{ + pageSize = $MigrationId.Count + } + } + } Else { + $spec = @{} + } $body = $spec | ConvertTo-Json $hcxQueryUrl = $global:hcxConnection.Server + "/migrations?action=query" @@ -468,10 +479,10 @@ Function Get-HcxMigration { $requests = Invoke-WebRequest -Uri $hcxQueryUrl -Method POST -Headers $global:hcxConnection.headers -UseBasicParsing } - $migrations = ($requests.content | ConvertFrom-Json).rows - if($PSBoundParameters.ContainsKey("MigrationId")){ - $migrations = $migrations | where { $_.migrationId -eq $MigrationId } + $migrations = ($requests.content | ConvertFrom-Json).items + } else { + $migrations = ($requests.content | ConvertFrom-Json).rows } if($RunningMigrations){ From 423e752404c1d933bceda6b49df8f038b129f161 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 13 Apr 2019 13:41:51 -0700 Subject: [PATCH 095/175] Adding Route Based VPN functions --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 393 +++++++++++++++++-- 2 files changed, 371 insertions(+), 24 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index 45e549d..4b50bf0 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', 'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index d29abbc..e5c7c06 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1641,53 +1641,400 @@ Function Get-NSXTInfraGroup { .EXAMPLE Get-NSXTInfraGroup -Name "S3 Prefixes" #> - param( - [Parameter(Mandatory=$false)][String]$Name, - [Switch]$Troubleshoot - ) + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) - If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { - $method = "GET" - $infraGroupsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/groups" + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $infraGroupsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/groups" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$infraGroupsURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $infraGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $infraGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Infrastructure Groups" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $groups = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $groups = $groups | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($group in $groups) { + $tmp = [pscustomobject] @{ + Name = $group.display_name; + ID = $group.id; + Path = $group.path; + } + $results+=$tmp + } + $results + } + } +} + +Function New-NSXTRouteBasedVPN { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 04/13/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Infrastructure Scopes + .DESCRIPTION + This cmdlet retrieves all NSX-T Infrastructure Scopes + .EXAMPLE + New-NSXTRouteBasedVPN -Name VPN3 ` + -PublicIP 18.184.241.223 ` + -RemotePublicIP 18.194.148.62 ` + -BGPLocalIP 169.254.51.2 ` + -BGPRemoteIP 169.254.51.1 ` + -BGPLocalASN 65056 ` + -BGPremoteASN 64512 ` + -BGPNeighborID 60 ` + -TunnelEncryption AES_256 ` + -TunnelDigestEncryption SHA2_256 ` + -IKEEncryption AES_256 ` + -IKEDigestEncryption SHA2_256 ` + -DHGroup GROUP14 ` + -IKEVersion IKE_V1 ` + -PresharedPassword VMware123. ` + -Troubleshoot + #> + param( + [Parameter(Mandatory=$true)][String]$Name, + [Parameter(Mandatory=$true)][String]$PublicIP, + [Parameter(Mandatory=$true)][String]$RemotePublicIP, + [Parameter(Mandatory=$true)][String]$BGPLocalIP, + [Parameter(Mandatory=$true)][String]$BGPRemoteIP, + [Parameter(Mandatory=$false)][int]$BGPLocalPrefix=30, + [Parameter(Mandatory=$true)][ValidateRange(64512,65534)][int]$BGPLocalASN, + [Parameter(Mandatory=$true)][ValidateRange(64512,65534)][int]$RemoteBGPASN, + [Parameter(Mandatory=$true)][String]$BGPNeighborID, + [Parameter(Mandatory=$true)][String][ValidateSet("AES_128","AES_256","AES_GCM_128","AES_GCM_192","AES_GCM_256")]$TunnelEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("SHA1","SHA2_256")]$TunnelDigestEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("AES_128","AES_256","AES_GCM_128","AES_GCM_192","AES_GCM_256")]$IKEEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("SHA1","SHA2_256")]$IKEDigestEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("GROUP2","GROUP5","GROUP14","GROUP15","GROUP16")]$DHGroup, + [Parameter(Mandatory=$true)][String][ValidateSet("IKE_V1","IKE_V2","IKE_FLEX")]$IKEVersion, + [Parameter(Mandatory=$true)][String]$PresharedPassword, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + + ## Configure BGP ASN + + $payload = @{ + local_as_num = $BGPLocalASN; + } + $body = $payload | ConvertTo-Json -Depth 5 + + $ASNmethod = "patch" + $bgpAsnURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/bgp" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $ASNmethod`n$bgpAsnURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $bgpAsnURL -Body $body -Method $ASNmethod -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $bgpAsnURL -Body $body -Method $ASNmethod -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in updating BGP ASN" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + ## Configure BGP Neighbor + + $payload = @{ + resource_type = "BgpNeighborConfig"; + id = $BGPNeighborID; + remote_as_num = $RemoteBGPASN; + neighbor_address = $BGPRemoteIP; + } + $body = $payload | ConvertTo-Json -Depth 5 + + $method = "put" + $bgpNeighborURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/bgp/neighbors/$BGPNeighborID" if($Troubleshoot) { - Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$infraGroupsURL`n" + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$bgpNeighborURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" } try { if($PSVersionTable.PSEdition -eq "Core") { - $requests = Invoke-WebRequest -Uri $infraGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + $requests = Invoke-WebRequest -Uri $bgpNeighborURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck } else { - $requests = Invoke-WebRequest -Uri $infraGroupsURL -Method $method -Headers $global:nsxtProxyConnection.headers + $requests = Invoke-WebRequest -Uri $bgpNeighborURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { if($_.Exception.Response.StatusCode -eq "Unauthorized") { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break } else { - Write-Error "Error in retrieving NSX-T Infrastructure Groups" + Write-Error "Error in configuring BGP Neighbor" Write-Error "`n($_.Exception.Message)`n" break } } if($requests.StatusCode -eq 200) { - $groups = ($requests.Content | ConvertFrom-Json).results + ## Configure Route Based Policy VPN - if ($PSBoundParameters.ContainsKey("Name")){ - $groups = $groups | where {$_.display_name -eq $Name} + $TunnelSubnets = @{ + ip_addresses = @("$BGPLocalIP"); + prefix_length = $BGPLocalPrefix; } - $results = @() - foreach ($group in $groups) { - $tmp = [pscustomobject] @{ - Name = $group.display_name; - ID = $group.id; - Path = $group.path; + $payload = @{ + display_name = $Name; + enabled = $true; + local_address = $PublicIP; + remote_private_address = $RemotePublicIP; + remote_public_address = $RemotePublicIP; + passphrases = @("$PresharedPassword"); + tunnel_digest_algorithms = @("$TunnelDigestEncryption"); + ike_digest_algorithms = @("$IKEDigestEncryption"); + ike_encryption_algorithms = @("$IKEEncryption"); + enable_perfect_forward_secrecy = $true; + dh_groups = @("$DHGroup"); + ike_version = $IKEVersion; + l3vpn_session = @{ + resource_type = "RouteBasedL3VpnSession"; + tunnel_subnets = @($TunnelSubnets); + default_rule_logging = $false; + force_whitelisting = $false; + routing_config_path = "/infra/tier-0s/vmc/locale-services/default/bgp/neighbors/$BGPNeighborID"; + }; + tunnel_encryption_algorithms = @("$TunnelEncryption"); + } + $body = $payload | ConvertTo-Json -Depth 5 + + $routeBasedVPNURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l3vpns/$Name" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$bgpNeighborURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $routeBasedVPNURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $routeBasedVPNURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in configuring Route Based VPN" + Write-Error "`n($_.Exception.Message)`n" + break } - $results+=$tmp } - $results + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully created Route Based VPN" + ($requests.Content | ConvertFrom-Json) + } } } - } \ No newline at end of file + } +} + +Function Get-NSXTRouteBasedVPN { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 04/13/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Route Based VPN Tunnels + .DESCRIPTION + This cmdlet retrieves all NSX-T Route Based VPN Tunnels description + .EXAMPLE + Get-NSXTRouteBasedVPN + .EXAMPLE + Get-NSXTRouteBasedVPN -Name "VPN-T1" + #> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $routeBaseVPNURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l3vpns" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$routeBaseVPNURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $routeBaseVPNURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $routeBaseVPNURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Route Based VPN Tunnels" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $groups = ($requests.Content | ConvertFrom-Json).results + + if ($PSBoundParameters.ContainsKey("Name")){ + $groups = $groups | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($group in $groups) { + $tmp = [pscustomobject] @{ + Name = $group.display_name; + ID = $group.id; + Path = $group.path; + RoutingConfigPath = $group.l3vpn_session.routing_config_path; + } + $results+=$tmp + } + $results + } + } +} + +Function Remove-NSXTRouteBasedVPN { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 04/13/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes a route based VPN Tunnel and it's associated BGP neighbor + .DESCRIPTION + This cmdlet removes a route based VPN Tunnel and it's associated BGP neighbor + .EXAMPLE + Remove-NSXTRouteBasedVPN -Name VPN1 -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $TunnelId = (Get-NSXTRouteBasedVPN -Name $Name).ID + $path = (Get-NSXTRouteBasedVPN -Name $Name).RoutingConfigPath + + # Delete IPSEC tunnel + $method = "DELETE" + $deleteVPNtunnelURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l3vpns/$TunnelId" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteVPNtunnelURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteVPNtunnelURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteVPNtunnelURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in removing NSX-T IPSEC Tunnel: $Name" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully removed NSX-T IPSEC Tunnel: $Name" + } + + # Delete BGP Neighbor + $method = "DELETE" + $deleteBGPnbURL = $global:nsxtProxyConnection.Server + "/policy/api/v1$path" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteBGPnbURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteBGPnbURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteBGPnbURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in removing NSX-T BGP Neighbor" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Succesfully removed NSX-T BGP Neighbor" + } + } +} \ No newline at end of file From 0cfb39779ba66690bfd22e3dd0969f8a3a41595e Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 13 Apr 2019 14:11:49 -0700 Subject: [PATCH 096/175] Fix "Successfully" typo --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 28 ++++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index e5c7c06..3e73913 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -205,7 +205,7 @@ Function New-NSXTSegment { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully created new NSX-T Segment $Name" + Write-Host "Successfully created new NSX-T Segment $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } } @@ -260,7 +260,7 @@ Function Remove-NSXTSegment { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T Segment $Name" + Write-Host "Successfully removed NSX-T Segment $Name" } } } @@ -577,7 +577,7 @@ Function New-NSXTFirewall { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully created new NSX-T Firewall Rule $Name" + Write-Host "Successfully created new NSX-T Firewall Rule $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } } @@ -633,7 +633,7 @@ Function Remove-NSXTFirewall { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T Firewall Rule" + Write-Host "Successfully removed NSX-T Firewall Rule" } } } @@ -791,7 +791,7 @@ Function New-NSXTGroup { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully created new NSX-T Group $Name" + Write-Host "Successfully created new NSX-T Group $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } } @@ -847,7 +847,7 @@ Function Remove-NSXTGroup { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T Group $Name" + Write-Host "Successfully removed NSX-T Group $Name" } } } @@ -997,7 +997,7 @@ Function New-NSXTService { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully created new NSX-T Service $Name" + Write-Host "Successfully created new NSX-T Service $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } } @@ -1352,7 +1352,7 @@ Function New-NSXTDistFirewall { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully created new NSX-T Distributed Firewall Rule $Name" + Write-Host "Successfully created new NSX-T Distributed Firewall Rule $Name" ($requests.Content | ConvertFrom-Json) | select display_name, id } } @@ -1411,7 +1411,7 @@ Function Remove-NSXTDistFirewall { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T Distributed Firewall Rule" + Write-Host "Successfully removed NSX-T Distributed Firewall Rule" } } } @@ -1477,7 +1477,7 @@ Function Get-NSXTRouteTable { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully retrieved NSX-T Routing Table`n" + Write-Host "Successfully retrieved NSX-T Routing Table`n" $routeTables = ($requests.Content | ConvertFrom-Json).results foreach ($routeTable in $routeTables) { @@ -1544,7 +1544,7 @@ If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection f } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully retrieved NSX-T Overview Information" + Write-Host "Successfully retrieved NSX-T Overview Information" ($requests.Content | ConvertFrom-Json) } } @@ -1872,7 +1872,7 @@ Function New-NSXTRouteBasedVPN { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully created Route Based VPN" + Write-Host "Successfully created Route Based VPN" ($requests.Content | ConvertFrom-Json) } } @@ -2005,7 +2005,7 @@ Function Remove-NSXTRouteBasedVPN { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T IPSEC Tunnel: $Name" + Write-Host "Successfully removed NSX-T IPSEC Tunnel: $Name" } # Delete BGP Neighbor @@ -2034,7 +2034,7 @@ Function Remove-NSXTRouteBasedVPN { } if($requests.StatusCode -eq 200) { - Write-Host "Succesfully removed NSX-T BGP Neighbor" + Write-Host "Successfully removed NSX-T BGP Neighbor" } } } \ No newline at end of file From 25450e9003f90dbb3dbfb7fb5b33ea556a00ccd9 Mon Sep 17 00:00:00 2001 From: William Lam Date: Mon, 15 Apr 2019 09:15:40 -0700 Subject: [PATCH 097/175] Fix No DHCP NSX-T Segment creation --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 3e73913..1f34f3d 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -152,6 +152,8 @@ Function New-NSXTSegment { This cmdlet creates a new NSX-T Segment (Logical Networks) .EXAMPLE New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" + .EXAMPLE + New-NSXTSegment -Name "sddc-cgw-network-5" -Gateway "192.168.5.1/24" #> Param ( [Parameter(Mandatory=$True)]$Name, @@ -163,14 +165,14 @@ Function New-NSXTSegment { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { if($DHCP) { - $dhcpConf = @($DHCPRange) + $subnets = @{ + gateway_address = $gateway; + dhcp_ranges = @($DHCPRange) + } } else { - $dhcpConf = @($null) - } - - $subnets = @{ - gateway_address = $gateway; - dhcp_ranges = $dhcpConf; + $subnets = @{ + gateway_address = $gateway; + } } $payload = @{ From 2cebd97c014c3fe736ef9f783db7699864fa16a6 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 19 Apr 2019 16:24:19 -0700 Subject: [PATCH 098/175] Fixed Distributed Firewall Rule Section + Remove NSX-T Service --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 169 +++++++++++++++---- 2 files changed, 136 insertions(+), 35 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index 4b50bf0..c18be71 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', 'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', 'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN', 'Remove-NSXTService', 'New-NSXTDistFirewallSection', 'Get-NSXTDistFirewallSection' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 1f34f3d..59606b5 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -520,7 +520,7 @@ Function New-NSXTFirewall { if($serviceName -eq "ANY") { $services = @("ANY") } else { - $tmp = "/infra/services/$serviceName" + $tmp = (Get-NSXTService -Name "$serviceName").Path $services+=$tmp } } @@ -924,6 +924,7 @@ Function Get-NSXTService { Protocol = $serviceProtocol; Source = $serviceSourcePorts; Destination = $serviceDestinationPorts; + Path = $service.path; } $results += $tmp } @@ -932,6 +933,60 @@ Function Get-NSXTService { } } +Function Remove-NSXTService { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 04/10/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes an NSX-T Service + .DESCRIPTION + This cmdlet removes an NSX-T Service + .EXAMPLE + Remove-NSXTService -Id VMware-Blast -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Id, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "DELETE" + $deleteServiceURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/services/$Id" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteServiceURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteServiceURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteServiceURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in removing NSX-T Service" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully removed NSX-T Service $Id" + } + } +} + Function New-NSXTService { <# .NOTES @@ -1005,27 +1060,23 @@ Function New-NSXTService { } } -Function Get-NSXTDistFirewallSection { +Function New-NSXTDistFirewallSection { <# .NOTES =========================================================================== Created by: William Lam - Date: 01/01/2019 + Date: 04/19/2019 Organization: VMware Blog: http://www.virtuallyghetto.com Twitter: @lamw =========================================================================== .SYNOPSIS - Returns all NSX-T Distributed Firewall Groups + Creates new NSX-T Distributed Firewall Section .DESCRIPTION - This cmdlet retrieves all NSX-T Distributed Firewall Sections + This cmdlet to create new NSX-T Distributed Firewall Section .EXAMPLE - Get-NSXTDistFirewallSection - .EXAMPLE - Get-NSXTDistFirewallSection -Name "App Section 1" - .EXAMPLE - et-NSXTDistFirewallSection -Category Emergency + Get-NSXTDistFirewallSection -Name "App Section 1" -Category Application #> param( [Parameter(Mandatory=$false)][String]$Name, @@ -1034,52 +1085,102 @@ Function Get-NSXTDistFirewallSection { ) If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { - $method = "GET" - $distFirewallGroupURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps" + $payload = @{ + display_name = $Name; + category = $Category; + resource_type = "CommunicationMap"; + } + + $body = $payload | ConvertTo-Json -depth 5 + + $method = "PUT" + $generatedId = (New-Guid).Guid + $distFirewallSectionURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$generatedId" if($Troubleshoot) { - Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$distFirewallGroupURL`n" + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$distFirewallSectionURL`n" } try { if($PSVersionTable.PSEdition -eq "Core") { - $requests = Invoke-WebRequest -Uri $distFirewallGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + $requests = Invoke-WebRequest -Uri $distFirewallSectionURL -Method $method -Body $body -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck } else { - $requests = Invoke-WebRequest -Uri $distFirewallGroupURL -Method $method -Headers $global:nsxtProxyConnection.headers + $requests = Invoke-WebRequest -Uri $distFirewallSectionURL -Method $method -Body $body -Headers $global:nsxtProxyConnection.headers } } catch { if($_.Exception.Response.StatusCode -eq "Unauthorized") { Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" break } else { - Write-Error "Error in retrieving NSX-T Distributed Firewall Sections" + Write-Error "Error in creating NSX-T Distributed Firewall Section" Write-Error "`n($_.Exception.Message)`n" break } } if($requests.StatusCode -eq 200) { - $groups = ($requests.Content | ConvertFrom-Json).results + Write-Host "Successfully created new NSX-T Distributed Firewall Section $Section" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } + } +} + +Function Get-NSXTDistFirewallSection { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 04/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns all NSX-T Distributed Firewall Sections + .DESCRIPTION + This cmdlet retrieves all NSX-T Distributed Firewall Sections + .EXAMPLE + Get-NSXTDistFirewallSection +#> + param( + [Parameter(Mandatory=$true)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $distFirewallSectionURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$distFirewallSectionURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $distFirewallSectionURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $distFirdistFirewallSectionURLwallURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Distributed Firewall Section" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $sections = ($requests.Content | ConvertFrom-Json).results if ($PSBoundParameters.ContainsKey("Name")){ - $groups = $groups | where {$_.display_name -eq $Name} + $sections = $sections | where {$_.display_name -eq $Name} } - if ($PSBoundParameters.ContainsKey("Category")){ - $groups = $groups | where {$_.category -eq $Category} - } - - $results = @() - foreach ($group in $groups | Sort-Object -Property category) { - $tmp = [pscustomobject] @{ - Id = $group.id; - Section = $group.display_name; - Category = $group.category; - Precedence = $group.precedence; - } - $results+=$tmp - } - $results + $sections | Sort-Object -Propert display_name | select display_name, id } } } @@ -1329,7 +1430,7 @@ Function New-NSXTDistFirewall { $method = "PUT" $generatedId = (New-Guid).Guid - $newDistFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$sectionId/communication-entries/$generatedId" + $newDistFirewallURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$($sectionId)/communication-entries/$generatedId" if($Troubleshoot) { Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newDistFirewallURL`n" From 3134d1acd934ac43da93b9649ef344b82bac3c63 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 20 Apr 2019 12:29:24 -0700 Subject: [PATCH 099/175] Removing -Name as required param + DROP keyword for action --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 59606b5..15e969e 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1144,7 +1144,7 @@ Function Get-NSXTDistFirewallSection { Get-NSXTDistFirewallSection #> param( - [Parameter(Mandatory=$true)][String]$Name, + [Parameter(Mandatory=$false)][String]$Name, [Switch]$Troubleshoot ) @@ -1376,7 +1376,7 @@ Function New-NSXTDistFirewall { [Parameter(Mandatory=$True)]$SourceGroup, [Parameter(Mandatory=$True)]$DestinationGroup, [Parameter(Mandatory=$True)]$Service, - [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, + [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DROP")]$Action, [Parameter(Mandatory=$false)][Boolean]$Logged=$false, [Switch]$Troubleshoot ) From fd7429055ddba34648bebde67f9a805a0a223cba Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 20 Apr 2019 12:42:15 -0700 Subject: [PATCH 100/175] Add Remove-NSXTDistFirewallSection --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 54 ++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 15e969e..f3ea7e6 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1185,6 +1185,60 @@ Function Get-NSXTDistFirewallSection { } } +Function Remove-NSXTDistFirewallSection { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 04/20/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes an NSX-T Distributed Firewall Section + .DESCRIPTION + This cmdlet removes an NSX-T Distributed Firewall Section + .EXAMPLE + Remove-NSXTDistFirewallSection -Id -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Id, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "DELETE" + $deleteDistFirewallSectioneURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/domains/cgw/communication-maps/$Id" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteDistFirewallSectioneURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteDistFirewallSectioneURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteDistFirewallSectioneURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in removing NSX-T Distributed Firewall Section" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully removed NSX-T Distributed Firewall Section $Id" + } + } +} + Function Get-NSXTDistFirewall { <# .NOTES From 4c9fab7b6ca14d1e240ef8047a8d73fccb5bf932 Mon Sep 17 00:00:00 2001 From: Thibaut Noben Date: Mon, 22 Apr 2019 21:01:59 +0200 Subject: [PATCH 101/175] removed return farm summary --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c58e1c0..c3e4e3e 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -1004,8 +1004,7 @@ function Get-HVFarm { 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 = @() From 11181a95ecde249a9689b99e2f8563e26d8c5df3 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 4 May 2019 12:48:19 -0700 Subject: [PATCH 102/175] Added New-SubscribedContentLibrary function --- Modules/ContentLibrary/ContentLibrary.psm1 | 74 +++++++++++++++++++++- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/Modules/ContentLibrary/ContentLibrary.psm1 b/Modules/ContentLibrary/ContentLibrary.psm1 index 9a8574b..5729445 100644 --- a/Modules/ContentLibrary/ContentLibrary.psm1 +++ b/Modules/ContentLibrary/ContentLibrary.psm1 @@ -190,7 +190,7 @@ Function Get-ContentLibraryItemFiles { $itemIds = $contentLibraryItemService.list($libraryID) $DatastoreID = $library.storage_backings.datastore_id.Value $Datastore = get-datastore -id "Datastore-$DatastoreID" - + foreach($itemId in $itemIds) { $itemName = ($contentLibraryItemService.get($itemId)).name $contentLibraryItemFileSerice = Get-CisService com.vmware.content.library.item.file @@ -205,7 +205,7 @@ Function Get-ContentLibraryItemFiles { else{ $fullfilepath = "UNKNOWN" } - + if(!$LibraryItemName) { $fileResult = [pscustomobject] @{ Name = $file.name; @@ -709,4 +709,72 @@ Function New-VMFromVMTX { Write-Host "`nDeploying new VM $NewVMName from VMTX Template $VMTXName ..." $results = $vmtxService.deploy($vmtxId,$vmtxDeploySpec) -} +} + +Function New-SubscribedContentLibrary { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + This function creates a new Subscriber Content Library from Subscription URL + .PARAMETER LibraryName + The name of the new vSphere Content Library + .PARAMETER DatastoreName + The name of the vSphere Datastore to store the Content Library + .PARAMETER SubscriptionURL + The URL of the published Content Library + .PARAMETER SubscriptionThumbprint + The SSL Thumbprint for the published Content Library + .PARAMETER OnDemand + Specifies whether content is downloaded on-demand (e.g. no immediately) + .PARAMETER AutomaticSync + Specifies whether automatic synchronization with the external content library is enabled + .EXAMPLE + New-SubscribedContentLibrary -LibraryName NestedESXi -DatastoreName vsanDatastore -SubscriptionURL https://download3.vmware.com/software/vmw-tools/lib.json -SubscriptionThumbprint "7a:c4:08:2d:d3:55:56:af:9f:26:43:65:d0:31:99:0b:d2:f3:d8:69" -AutomaticSync + .EXAMPLE + New-SubscribedContentLibrary -LibraryName NestedESXi -DatastoreName vsanDatastore -SubscriptionURL https://download3.vmware.com/software/vmw-tools/lib.json -SubscriptionThumbprint "7a:c4:08:2d:d3:55:56:af:9f:26:43:65:d0:31:99:0b:d2:f3:d8:69" -OnDemand +#> + param( + [Parameter(Mandatory=$true)][String]$LibraryName, + [Parameter(Mandatory=$true)][String]$DatastoreName, + [Parameter(Mandatory=$true)][String]$SubscriptionURL, + [Parameter(Mandatory=$true)][String]$SubscriptionThumbprint, + [Parameter(Mandatory=$false)][Switch]$OnDemand, + [Parameter(Mandatory=$false)][Switch]$AutomaticSync + ) + + $datastore = Get-Datastore -Name $DatastoreName + + if($datastore) { + $datastoreId = $datastore.ExtensionData.MoRef.Value + $subscribeLibraryService = Get-CisService -Name "com.vmware.content.subscribed_library" + + $StorageSpec = [pscustomobject] @{ + datastore_id = $datastoreId; + type = "DATASTORE"; + } + + $UniqueChangeId = [guid]::NewGuid().tostring() + + $createSpec = $subscribeLibraryService.help.create.create_spec.create() + $createSpec.name = $LibraryName + $createSpec.type = "SUBSCRIBED" + $addResults = $createSpec.storage_backings.Add($StorageSpec) + + if($OnDemand) { $OnDemandFlag = $true } else { $OnDemandFlag = $false } + if($AutomaticSync) { $AutomaticSyncFlag = $true } else { $AutomaticSyncFlag = $false } + $createSpec.subscription_info.on_demand = $OnDemandFlag + $createSpec.subscription_info.automatic_sync_enabled = $AutomaticSyncFlag + $createSpec.subscription_info.subscription_url = $SubscriptionURL + $createSpec.subscription_info.authentication_method = "NONE" + $createSpec.subscription_info.ssl_thumbprint = $SubscriptionThumbprint + + Write-Host "Creating new Subscribed Content Library called $LibraryName ..." + $library = $subscribeLibraryService.create($UniqueChangeId, $createSpec) + } +} \ No newline at end of file From f4fc007bd5d0eca17a3fef0575fb2ac1c86ac18b Mon Sep 17 00:00:00 2001 From: William Lam Date: Mon, 6 May 2019 12:14:41 -0700 Subject: [PATCH 103/175] Added Destination Resource Pool / VM Folder --- Modules/CrossvCentervmotion/XVM.psm1 | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/Modules/CrossvCentervmotion/XVM.psm1 b/Modules/CrossvCentervmotion/XVM.psm1 index cb9d225..555ec5d 100644 --- a/Modules/CrossvCentervmotion/XVM.psm1 +++ b/Modules/CrossvCentervmotion/XVM.psm1 @@ -152,10 +152,12 @@ Function New-XVCMRequest { The name of the source vSphere Datacenter .PARAMETER DstDatacenter The name of the destination vSphere Datacenter - .PARAMETER SrcCluster - .PARAMETER DstCluster The name of the destination vSphere Cluster, set to null if DstHost is defined + .PARAMETER DstPool + The name of the destination vSphere Resource Pool + .PARAMETER DstFolder + The name of the destination vSphere Folder .PARAMETER DstDatastore The name of the destination Datastore .PARAMETER DstHost @@ -171,6 +173,15 @@ Function New-XVCMRequest { -DstDatastore vsanDatastore ` -srcVMs @("PhotonOS-01","PhotonOS-02","PhotonOS-03","PhotonOS-04") ` -NetworkMapping @{"DVPG-VM Network 1"="DVPG-Internal Network";"DVPG-VM Network 2"="DVPG-External Network"} + .EXAMPLE + New-XVCMRequest -opType Clone -SrcSite OREGON -DstSite CALIF ` + -SrcDatacenter SDDC-Datacenter -srcVMs @(“DUDE-ubuntu”) ` + -DstDatacenter SDDC-Datacenter ` + -DstCluster "Cluster-1" -DstHost $null ` + -DstPool Compute-ResourcePool ` + -DstFolder Workloads ` + -DstDatastore WorkloadDatastore ` + -NetworkMapping @{"OREGON-VMs-sddc"="CALIF-sddc-VMs"} #> param( [Parameter(Mandatory=$true)][String]$opType, #Added by CPM for 2.0 @@ -178,8 +189,9 @@ Function New-XVCMRequest { [Parameter(Mandatory=$true)][String]$DstSite, [Parameter(Mandatory=$true)][String]$SrcDatacenter, [Parameter(Mandatory=$true)][String]$DstDatacenter, - #[Parameter(Mandatory=$true)][String]$SrcCluster, #Removed by CPM for 2.0 [Parameter(Mandatory=$true)][AllowNull()] $DstCluster, #Added [AllowNull()], removed [String] by CPM for 2.0 + [Parameter(Mandatory=$true)][String]$DstPool, + [Parameter(Mandatory=$true)][String]$DstFolder, [Parameter(Mandatory=$true)][String]$DstDatastore, [Parameter(Mandatory=$true)][AllowNull()] $DstHost, #Added by CPM for 2.0 [Parameter(Mandatory=$true)][String[]]$srcVMs, @@ -193,7 +205,8 @@ Function New-XVCMRequest { "targetSite"=$DstSite; "sourceDatacenter"=$SrcDatacenter; "targetDatacenter"=$dstDatacenter; - #"sourceCluster"=$SrcCluster; #Removed by CPM for 2.0 + "targetPool"=$DstPool; + "targetFolder"=$DstFolder; "targetCluster"=$DstCluster; "targetDatastore"=$DstDatastore; "targetHost"=$DstHost; #Added by CPM for 2.0 From 6f22da7f67924e405f3e9a4d86a273a68c57311b Mon Sep 17 00:00:00 2001 From: LucD Date: Wed, 8 May 2019 10:07:26 +0200 Subject: [PATCH 104/175] Save-PowerCLI v2.1 - fixed incorrect module version download - added a working cleanup in End Signed-off-by: Luc Dekens --- Scripts/Save-PowerCLI.ps1 | 281 ++++++++++++++++++++------------------ 1 file changed, 146 insertions(+), 135 deletions(-) diff --git a/Scripts/Save-PowerCLI.ps1 b/Scripts/Save-PowerCLI.ps1 index e9127bc..495c153 100644 --- a/Scripts/Save-PowerCLI.ps1 +++ b/Scripts/Save-PowerCLI.ps1 @@ -1,147 +1,158 @@ -function Save-PowerCLI { - <# - .SYNOPSIS - Advanced function which can be used to easily download specific versions of PowerCLI from an online gallery - .DESCRIPTION - Downloads a specific version of PowerCLI and all the dependencies at the appropriate version - .NOTES - Author: 1.0 - Dimitar Milov - Author: 2.0 - Kyle Ruddy, @kmruddy - .PARAMETER RequiredVersion - Dynamic parameter used to specify the PowerCLI version - .PARAMETER Path - Directory path where the modules should be downloaded - .PARAMETER Repository - Repository to access the PowerCLI modules - .PARAMETER Simple - Switch used to specify the nested version folders should be removed (therefore adding PowerShell 3/4 compatibility) - .EXAMPLE - Save-PowerCLI -RequiredVersion '10.0.0.7895300' -Path .\Downloads\ - Downloads PowerCLI 10.0.0 to the Downloads folder - .EXAMPLE - Save-PowerCLI -RequiredVersion '6.5.2.6268016' -Path .\Downloads\ -Simple - Downloads PowerCLI 6.5.2 to the Downloads folder and removes the nested version folders - #> - [CmdletBinding(SupportsShouldProcess = $True)] - param( - [Parameter(Mandatory = $true, Position = 1)] - [ValidateScript( { Test-Path $_} )] - $Path, - [Parameter(Mandatory = $false, Position = 2)] - [string]$Repository = 'PSGallery', - [Parameter(Mandatory = $false, Position = 3)] - [Switch]$Simple - ) - DynamicParam - { - # Set the dynamic parameters name - $ParameterName = 'RequiredVersion' - - # Create the dictionary - $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary - - # Create the collection of attributes - $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - - # Create and set the parameters' attributes - $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute - $ParameterAttribute.ValueFromPipeline = $true - $ParameterAttribute.ValueFromPipelineByPropertyName = $true - $ParameterAttribute.Mandatory = $true - $ParameterAttribute.Position = 0 - - # Add the attributes to the attributes collection - $AttributeCollection.Add($ParameterAttribute) - - # Generate and set the ValidateSet - $pcliVersions = Find-Module -Name 'VMware.PowerCLI' -AllVersions - $arrSet = $pcliVersions | select-Object -ExpandProperty Version - $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) - - # Add the ValidateSet to the attributes collection - $AttributeCollection.Add($ValidateSetAttribute) - - # Create and return the dynamic parameter - $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) - $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) - return $RuntimeParameterDictionary +function Save-PowerCLI { +<# +.SYNOPSIS + Advanced function which can be used to easily download specific versions of PowerCLI from an online gallery +.DESCRIPTION + Downloads a specific version of PowerCLI and all the dependencies at the appropriate version +.NOTES + Author: 1.0 - Dimitar Milov + Author: 2.0 - Kyle Ruddy, @kmruddy + Author: 2.1 - Luc Dekens, @LucD22 + - fixed issue with downloading the correct versions + - added a working cleanup of unwanted versions +.PARAMETER RequiredVersion + Dynamic parameter used to specify the PowerCLI version +.PARAMETER Path + Directory path where the modules should be downloaded +.PARAMETER Repository + Repository to access the PowerCLI modules +.PARAMETER Simple + Switch used to specify the nested version folders should be removed (therefore adding PowerShell 3/4 compatibility) +.EXAMPLE + Save-PowerCLI -RequiredVersion '10.0.0.7895300' -Path .\Downloads\ + Downloads PowerCLI 10.0.0 to the Downloads folder +.EXAMPLE + Save-PowerCLI -RequiredVersion '6.5.2.6268016' -Path .\Downloads\ -Simple + Downloads PowerCLI 6.5.2 to the Downloads folder and removes the nested version folders +#> + [CmdletBinding(SupportsShouldProcess = $True)] + param( + [Parameter(Mandatory = $true, Position = 1)] + [ValidateScript( { Test-Path $_} )] + $Path, + [Parameter(Mandatory = $false, Position = 2)] + [string]$Repository = 'PSGallery', + [Parameter(Mandatory = $false, Position = 3)] + [Switch]$Simple + ) + DynamicParam + { + # Set the dynamic parameters name + $ParameterName = 'RequiredVersion' + + # Create the dictionary + $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary + + # Create the collection of attributes + $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + + # Create and set the parameters' attributes + $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute + $ParameterAttribute.ValueFromPipeline = $true + $ParameterAttribute.ValueFromPipelineByPropertyName = $true + $ParameterAttribute.Mandatory = $true + $ParameterAttribute.Position = 0 + + # Add the attributes to the attributes collection + $AttributeCollection.Add($ParameterAttribute) + + # Generate and set the ValidateSet + $pcliVersions = Find-Module -Name 'VMware.PowerCLI' -AllVersions + $arrSet = $pcliVersions | select-Object -ExpandProperty Version + $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) + + # Add the ValidateSet to the attributes collection + $AttributeCollection.Add($ValidateSetAttribute) + + # Create and return the dynamic parameter + $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [String], $AttributeCollection) + $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) + return $RuntimeParameterDictionary + } + + begin { + $powercliModuleName = 'VMware.PowerCLI' + $desiredPowerCLIModule = Find-Module -Name $powercliModuleName -RequiredVersion $PSBoundParameters.RequiredVersion -Repository $Repository + + $depsOrder = 'VMware.VimAutomation.Sdk', 'VMware.VimAutomation.Common', 'VMware.Vim', 'VMware.VimAutomation.Cis.Core', 'VMware.VimAutomation.Core', 'VMware.VimAutomation.Nsxt', 'VMware.VimAutomation.Vmc', 'VMware.VimAutomation.Vds', 'VMware.VimAutomation.Srm', 'VMware.ImageBuilder', 'VMware.VimAutomation.Storage', 'VMware.VimAutomation.StorageUtility', 'VMware.VimAutomation.License', 'VMware.VumAutomation', 'VMware.VimAutomation.HorizonView', 'VMware.DeployAutomation', 'VMware.VimAutomation.vROps', 'VMware.VimAutomation.PCloud' + $orderedDependencies = @() + foreach ($depModuleName in $depsOrder) { + $orderedDependencies += $desiredPowerCLIModule.Dependencies | Where-Object {$_.Name -eq $depModuleName} } - - begin { - $powercliModuleName = 'VMware.PowerCLI' - $desiredPowerCLIModule = Find-Module -Name $powercliModuleName -RequiredVersion $RequiredVersion -Repository $Repository - - $depsOrder = 'VMware.VimAutomation.Sdk', 'VMware.VimAutomation.Common', 'VMware.Vim', 'VMware.VimAutomation.Cis.Core', 'VMware.VimAutomation.Core', 'VMware.VimAutomation.Nsxt', 'VMware.VimAutomation.Vmc', 'VMware.VimAutomation.Vds', 'VMware.VimAutomation.Srm', 'VMware.ImageBuilder', 'VMware.VimAutomation.Storage', 'VMware.VimAutomation.StorageUtility', 'VMware.VimAutomation.License', 'VMware.VumAutomation', 'VMware.VimAutomation.HorizonView', 'VMware.DeployAutomation', 'VMware.VimAutomation.vROps', 'VMware.VimAutomation.PCloud' - $orderedDependencies = @() - foreach ($depModuleName in $depsOrder) { - $orderedDependencies += $desiredPowerCLIModule.Dependencies | Where-Object {$_.Name -eq $depModuleName} + + foreach ($remainingDep in $desiredPowerCLIModule.Dependencies) { + if ($orderedDependencies.Name -notcontains $remainingDep.Name) { + $orderedDependencies += $remainingDep } - foreach ($remainingDep in $desiredPowerCLIModule.Dependencies) { - if ($orderedDependencies.Name -notcontains $remainingDep.Name) { - $orderedDependencies += $remainingDep - } - + } + } + + process { + # Save PowerCLI Module Version + $desiredPowerCLIModule | Save-Module -Path $Path + + # Working with the depenent modules + foreach ($dependency in $orderedDependencies) { + if (Get-ChildItem -Path (Join-Path $path $dependency.Name) | Where-Object {$_.Name -ne $dependency.MinimumVersion}) { + # Save dependencies with minimum version + Find-Module $dependency.Name -RequiredVersion $dependency.MinimumVersion | Save-Module -Path $Path } } - - process { - # Save PowerCLI Module Version - $desiredPowerCLIModule | Save-Module -Path $Path - - # Working with the depenent modules - foreach ($dependency in $orderedDependencies) { - if (Get-ChildItem -Path (Join-Path $path $dependency.Name) | Where-Object {$_.Name -ne $dependency.MinimumVersion}) { - # Save dependencies with minimum version - Find-Module $dependency.Name -RequiredVersion $dependency.MinimumVersion | Save-Module -Path $Path - - # Remove newer dependencies version - Get-ChildItem -Path (Join-Path $path $dependency.Name) | Where-Object {$_.Name -ne $dependency.MinimumVersion} | Remove-Item -Confirm:$false -Force -Recurse + } + + end { + Get-Item -Path "$($Path)\*" -PipelineVariable dir | + ForEach-Object -Process { + $children = Get-ChildItem -Path $dir.FullName -Directory + if($children.Count -gt 1){ + $tgtVersion = $orderedDependencies.GetEnumerator() | where {$_.Name -eq $dir.Name} + $children | where{$_.Name -ne $tgtVersion.MinimumVersion} | + ForEach-Object -Process { + Remove-Item -Path $_.FullName -Recurse -Force -Confirm:$false } } } - - end { - if ($Simple) { - - function FolderCleanup { - param( - [Parameter(Mandatory = $true, Position = 0)] - [ValidateScript( { Test-Path $_} )] - $ParentFolder, - [Parameter(Mandatory = $true, Position = 1)] - [String]$ModuleName, - [Parameter(Mandatory = $true, Position = 2)] - $Version - ) - - - $topFolder = Get-Item -Path (Join-Path $ParentFolder $ModuleName) - $versionFolder = $topFolder | Get-ChildItem -Directory | Where-Object {$_.Name -eq $Version} - $versionFolder | Get-ChildItem | Copy-Item -Destination $topFolder - - # Checking for any nested folders within the PowerCLI module version folder - if ($versionFolder| Get-ChildItem -Directory) { - - # Obtaining and storing the child items to a variable, then copying the items to the parent folder's nested folder - $nestFolder = $versionFolder| Get-ChildItem -Directory - foreach ($nestDir in $nestFolder) { - $nestDir | Get-ChildItem | Copy-Item -Destination (Join-Path $topFolder $nestDir.Name) - } - + + if ($Simple) { + + function FolderCleanup { + param( + [Parameter(Mandatory = $true, Position = 0)] + [ValidateScript( { Test-Path $_} )] + $ParentFolder, + [Parameter(Mandatory = $true, Position = 1)] + [String]$ModuleName, + [Parameter(Mandatory = $true, Position = 2)] + $Version + ) + + + $topFolder = Get-Item -Path (Join-Path $ParentFolder $ModuleName) + $versionFolder = $topFolder | Get-ChildItem -Directory | Where-Object {$_.Name -eq $Version} + $versionFolder | Get-ChildItem | Copy-Item -Destination $topFolder + + # Checking for any nested folders within the PowerCLI module version folder + if ($versionFolder| Get-ChildItem -Directory) { + + # Obtaining and storing the child items to a variable, then copying the items to the parent folder's nested folder + $nestFolder = $versionFolder| Get-ChildItem -Directory + foreach ($nestDir in $nestFolder) { + $nestDir | Get-ChildItem | Copy-Item -Destination (Join-Path $topFolder $nestDir.Name) } - - # Removing any of the former, no longer needed, directory structure - $versionFolder| Remove-Item -Recurse -Force + } - - FolderCleanup -ParentFolder $Path -ModuleName $desiredPowerCLIModule.Name -Version $desiredPowerCLIModule.Version - foreach ($cleanUp in $orderedDependencies) { - - FolderCleanup -ParentFolder $Path -ModuleName $cleanUp.Name -Version $cleanUp.MinimumVersion - } - + + # Removing any of the former, no longer needed, directory structure + $versionFolder| Remove-Item -Recurse -Force } - + + FolderCleanup -ParentFolder $Path -ModuleName $desiredPowerCLIModule.Name -Version $desiredPowerCLIModule.Version + foreach ($cleanUp in $orderedDependencies) { + + FolderCleanup -ParentFolder $Path -ModuleName $cleanUp.Name -Version $cleanUp.MinimumVersion + } + } - } \ No newline at end of file + } +} From 50559d9c6d96756d05d2c8cbd2815959d76de1bc Mon Sep 17 00:00:00 2001 From: samiullasha <46373019+samiullasha@users.noreply.github.com> Date: Wed, 8 May 2019 18:26:00 +0530 Subject: [PATCH 105/175] Adding new functions to Application Pool Adding the below new functions to Application Pool. Get-HVApplication, Remove-HVApplication, New-HVManualApplication, Get-HVPreInstalledApplication, New-HVPreInstalledApplication --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 532 +++++++++++++++++- 1 file changed, 531 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 608180d..a73fc56 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -11946,12 +11946,542 @@ function Set-HVInstantCloneMaintenance { [System.gc]::collect() } } + +Function Get-HVApplication { +<# +.Synopsis + Gets the application information. + +.DESCRIPTION + Gets the application information. This will be useful to find out whether the specified application exists or not. If the application name is not specified, this will lists all the applications in the Pod. + +.PARAMETER ApplicationName + Name of the application. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.PARAMETER FormatList + Displays the list of the available applications in Table Format if this parameter is set to True. + +.EXAMPLE + Get-HVApplication -ApplicationName 'App1' -HvServer $HvServer + Queries and returns 'App1' information. + +.EXAMPLE + Get-HVApplication -HvServer $HvServer -FormatList:$True + Lists all the applications in the Pod. + +.OUTPUTS + Returns the information of the specified application if it specified, else displays all the available applications. + +.NOTES + Author : Samiullasha S + Author email : ssami@vmware.com + Version : 1.2 + + ===Tested Against Environment==== + Horizon View Server Version : 7.8.0 + PowerCLI Version : PowerCLI 11.1 + PowerShell Version : 5.0 +#> + param ( + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [string]$ApplicationName = $Null, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + $HvServer = $Null, + + [Parameter(Mandatory = $False)] + [string]$FormatList = $False + ) + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve View API services from connection object." + break + } + } + process { + if ($ApplicationName) { + $eqFilter = Get-HVQueryFilter 'data.name' -Eq $ApplicationName + $ResourceObjs = Get-HVQueryResult -EntityType ApplicationInfo -Filter $eqFilter -HvServer $HvServer + if(!$ResourceObjs){Write-host "No application found with specified name: $ApplicationName"; return} + Write-host "Application found with specified name: $ApplicationName" + return $ResourceObjs + } + $ResourceObjs = Get-HVQueryResult -EntityType ApplicationInfo -HvServer $HvServer + if ($FormatList -eq $True){ return $ResourceObjs.data | Format-Table -AutoSize} + return $ResourceObjs.data + } + end { + [System.GC]::Collect() + } +} + +Function Remove-HVApplication { +<# +.Synopsis + Removes the specified application if exists. + +.DESCRIPTION + Removes the specified application if exists. + +.PARAMETER ApplicationName + Application to be deleted. + The name of the application must be given that is to be searched for and remove if exists. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.EXAMPLE + Remove-HVApplication -ApplicationName 'App1' -HvServer $HvServer + Removes 'App1', if exists. + +.OUTPUTS + Removes the specified application if exists. + +.NOTES + Author : Samiullasha S + Author email : ssami@vmware.com + Version : 1.2 + + ===Tested Against Environment==== + Horizon View Server Version : 7.8.0 + PowerCLI Version : PowerCLI 11.1 + PowerShell Version : 5.0 +#> + param ( + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [string]$ApplicationName, + + [Parameter(Mandatory = $False)] + $HvServer = $null + ) + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve View API services from connection object" + break + } + } + process { + $App= Get-HVApplication -ApplicationName $ApplicationName -HvServer $HvServer + if (!$App) { + Write-Host "Application '$ApplicationName' not found. $_" + return + } + $AppService= New-Object VMware.Hv.ApplicationService + $AppService.Application_Delete($services,$App.Id) + if ($?) { + Write-Host "'$ApplicationName' has been successfully removed." + } + } + end { + [System.GC]::Collect() + } +} + +Function New-HVManualApplication { +<# +.Synopsis + Creates a Manual Application. + +.DESCRIPTION + Creates Application manually with given parameters. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.PARAMETER Name + The Application name is the unique identifier used to identify this Application. + +.PARAMETER DisplayName + The display name is the name that users will see when they connect to view client. If the display name is left blank, it defaults to Name. + +.PARAMETER Description + The description is a set of notes about the Application. + +.PARAMETER ExecutablePath + Path to Application executable. + +.PARAMETER Version + Application version. + +.PARAMETER Publisher + Application publisher. + +.PARAMETER Enabled + Indicates if Application is enabled. + +.PARAMETER EnablePreLaunch + Application can be pre-launched if value is true. + +.PARAMETER ConnectionServerRestrictions + Connection server restrictions. This is a list of tags that access to the application is restricted to. Empty/Null list means that the application can be accessed from any connection server. + +.PARAMETER CategoryFolderName + Name of the category folder in the user's OS containing a shortcut to the application. Unset if the application does not belong to a category. + +.PARAMETER ClientRestrictions + Client restrictions to be applied to Application. Currently it is valid for RDSH pools. + +.PARAMETER ShortcutLocations + Locations of the category folder in the user's OS containing a shortcut to the desktop. The value must be set if categoryFolderName is provided. + +.PARAMETER MultiSessionMode + Multi-session mode for the application. An application launched in multi-session mode does not support reconnect behavior when user logs in from a different client instance. + +.PARAMETER MaxMultiSessions + Maximum number of multi-sessions a user can have in this application pool. + +.PARAMETER StartFolder + Starting folder for Application. + +.PARAMETER Args + Parameters to pass to application when launching. + +.PARAMETER Farm + Farm name. + +.PARAMETER AutoUpdateFileTypes + Whether or not the file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +.PARAMETER AutoUpdateOtherFileTypes + Whether or not the other file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +.EXAMPLE + New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' + Creates a manual application App1 in the farm specified. + +.OUTPUTS + A success message is displayed when done. + +.NOTES + Author : Samiullasha S + Author email : ssami@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.8.0 + PowerCLI Version : PowerCLI 11.1 + PowerShell Version : 5.0 +#> + param ( + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [VMware.VimAutomation.HorizonView.Impl.V1.ViewServerImpl]$HvServer, + + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [string][ValidateLength(1,64)]$Name, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String][ValidateLength(1,256)]$DisplayName = $Name, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String][ValidateLength(1,1024)]$Description, + + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [String]$ExecutablePath, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$Version, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$Publisher, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$Enabled = $True, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$EnablePreLaunch=$False, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [string[]]$ConnectionServerRestrictions, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True, ParameterSetName = 'categoryFolderName')] + [String][ValidateRange(1,64)]$CategoryFolderName, + + #Below Parameter is for Client restrictions to be applied to Application. Currently it is valid for RDSH pools. + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$clientRestrictions = $False, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True, ParameterSetName = 'categoryFolderName')] + [String[]]$ShortcutLocations, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [ValidateSet('DISABLED','ENABLED_DEFAULT_OFF','ENABLED_DEFAULT_ON','ENABLED_ENFORCED')] + [String]$MultiSessionMode = 'DISABLED', + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [ValidateScript({if(($MultiSessionMode -eq 'ENABLED_DEFAULT_OFF') -or ($MultiSessionMode -eq 'ENABLED_DEFAULT_ON') -or ($MultiSessionMode -eq 'ENABLED_ENFORCED')){$_ -eq 1}})] + [Int]$MaxMultiSessions, + + #Below parameters are for ExecutionData, moved ExecutablePath, Version and Publisher to above from this. + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$StartFolder, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$Args, + + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [String]$Farm, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$AutoUpdateFileTypes = $True, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$AutoUpdateOtherFileTypes = $True + ) + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve View API services from connection object" + break + } + $FarmInfo = Get-HVFarm -FarmName $Farm + if ($null -eq $FarmInfo) { + Write-Error "Could not find the specified Farm." + break + } + } + process { + $App = Get-HVApplication -ApplicationName $Name -HvServer $HvServer + if ($App) { + Write-Host "Application already exists with the name : $Name" + return + } + $AppData = New-Object VMware.Hv.ApplicationData -Property @{ 'Name' = $Name; 'DisplayName' = $DisplayName; 'Description' = $Description; 'Enabled' = $Enabled; 'EnableAntiAffinityRules' = $EnableAntiAffinityRules; 'AntiAffinityPatterns' = $AntiAffinityPatterns; 'AntiAffinityCount' = $AntiAffinityCount; 'EnablePreLaunch' = $EnablePreLaunch; 'multiSessionMode' = $MultiSessionMode; 'maxMultiSessions' = $MaxMultiSessions; 'ConnectionServerRestrictions' = $ConnectionServerRestrictions; 'CategoryFolderName' = $CategoryFolderName; 'ClientRestrictions' = $ClientRestrictions; 'ShortcutLocations' = $ShortcutLocations} + $ExecutionData = New-object VMware.Hv.ApplicationExecutionData -Property @{ 'ExecutablePath' = $ExecutablePath; 'Version' = $Version; 'Publisher' = $Publisher; 'StartFolder' = $StartFolder; 'Args' = $Args; 'Farm' = $FarmInfo.id; 'AutoUpdateFileTypes' = $AutoUpdateFileTypes; 'AutoUpdateOtherFileTypes' = $AutoUpdateOtherFileTypes} + $AppSpec = New-Object VMware.Hv.ApplicationSpec -Property @{ 'Data' = $AppData; 'ExecutionData' = $ExecutionData} + $AppService = New-Object VMware.Hv.ApplicationService + $AppService.Application_Create($services,$AppSpec) + if ($?) { + Write-Host "Application '$Name' created successfully" + return + } + Write-Host "Application creation of '$Name' has failed. $_" + } + end { + [System.GC]::Collect() + } +} + +Function Get-HVPreInstalledApplication { +<# +.Synopsis + Gets the list of Pre-installed Applications from the RDS Server(s). + +.DESCRIPTION + Gets the list of Pre-installed Applications from the RDS Server(s). + +.PARAMETER FarmName + Name of the Farm on which to discover installed applications. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.EXAMPLE + Get-HVPreInstalledApplication -FarmName 'Farm1' -HvServer $HvServer + Gets the list of Applications present in 'Farm1', if exists. + +.OUTPUTS + Gets the list of Applications from the specified Farm if exists. + +.NOTES + Author : Samiullasha S + Author email : ssami@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.8.0 + PowerCLI Version : PowerCLI 11.1 + PowerShell Version : 5.0 +#> + param ( + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [String][ValidateLength(1,64)]$FarmName, + + [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 + } + $Farm = Get-HVFarm -FarmName $FarmName + if($null -eq $Farm) { + Write-Error "Could not find the specified Farm." + break + } + } + process { + $FarmService = New-Object VMware.Hv.FarmService + $Data = $FarmService.Farm_DiscoverInstalledApplications($services,$Farm.Id) + return $Data + } + end { + [System.GC]::Collect() + } +} + +Function New-HVPreInstalledApplication { +<# +.Synopsis + Creates a application pool from Pre-installed applications on RDS Server(s). + +.DESCRIPTION + Creates a application pool from Pre-installed applications on RDS Server(s). + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.PARAMETER ApplicationName + The Application name is the unique identifier used to identify this Application. + +.PARAMETER DisplayName + The display name is the name that users will see when they connect to view client. If the display name is left blank, it defaults to Name. + +.PARAMETER FarmName + Farm name. + +.PARAMETER EnablePreLaunch + Application can be pre-launched if value is true. + +.PARAMETER ConnectionServerRestrictions + Connection server restrictions. This is a list of tags that access to the application is restricted to. Empty/Null list means that the application can be accessed from any connection server. + +.PARAMETER CategoryFolderName + Name of the category folder in the user's OS containing a shortcut to the application. Unset if the application does not belong to a category. + +.PARAMETER ClientRestrictions + Client restrictions to be applied to Application. Currently it is valid for RDSH pools. + +.EXAMPLE + New-HVPreInstalledApplication -ApplicationName 'App1' -DisplayName 'DisplayName' -FarmName 'FarmName' + Creates a application App1 from the farm specified. + +.EXAMPLE + New-HVPreInstalledApplication -ApplicationName 'App2' -FarmName FarmManual -EnablePreLaunch $True + Creates a application App2 from the farm specified and the PreLaunch option will be enabled. + +.OUTPUTS + A success message is displayed when done. + +.NOTES + Author : Samiullasha S + Author email : ssami@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.8.0 + PowerCLI Version : PowerCLI 11.1 + PowerShell Version : 5.0 +#> + param ( + [Parameter(Mandatory = $False)] + $HvServer = $null, + + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [string][ValidateLength(1,64)]$ApplicationName, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String][ValidateLength(1,256)]$DisplayName = $ApplicationName, + + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + [String][ValidateLength(1,64)]$FarmName, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$EnablePreLaunch=$False, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [string[]]$ConnectionServerRestrictions, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True,ParameterSetName = 'categoryFolderName')] + [String][ValidateRange(1,64)]$CategoryFolderName, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$clientRestrictions = $False + ) + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break + } + $FarmInfo = Get-HVFarm -FarmName $FarmName + if($null -eq $FarmInfo) { + Write-Error "Could not find the specified Farm $FarmName." + break + } + } + process { + #Validate the Application name uniqueness with existing applications. + $ResourceObjs = Get-HVApplication -HvServer $HvServer + foreach($App in ($ResourceObjs.name)) { + if($App -eq $ApplicationName) { + Write-Host "$ApplicationName already exists in the Application Pool." + return + } + } + #Validate the application name uniqueness with Desktops. + $DesktopSummary = Get-HVQueryResult -EntityType DesktopSummaryView -HvServer $hvserver + foreach($App in $DesktopSummary) { + if($App.DesktopSummaryData.Name -eq $ApplicationName) { + Write-Host "$ApplicationName already exists in the Desktop Pool." + return + } + } + #get all the applications installed in RDS Server(s). + $AppsInRDS = Get-HVPreinstalledApplication -FarmName $FarmName + $AppFoundInRDS = $False + foreach($App in ($AppsInRDS)) { + if($($App.name) -eq ($ApplicationName)) { + $AppFoundInRDS = $True + $ApplicationID = $ApplicationName -replace " ","_" + $ApplicationData = New-Object VMware.Hv.ApplicationData -Property @{ 'Name' = $ApplicationID; + 'DisplayName' = $DisplayName; + 'EnablePreLaunch' = $EnablePreLaunch; + 'ConnectionServerRestrictions' = $ConnectionServerRestrictions; + 'CategoryFolderName' = $CategoryFolderName; + 'ClientRestrictions' = $ClientRestrictions } + $ExecutionData = New-object VMware.Hv.ApplicationExecutionData -Property @{ 'ExecutablePath' = $App.ExecutionData.ExecutablePath; + 'Version' = $App.ExecutionData.Version; + 'Publisher' = $App.ExecutionData.Publisher; + 'Args' = $App.ExecutionData.Args; + 'StartFolder' = $App.ExecutionData.StartFolder; + 'Farm' = $FarmInfo.Id; + 'AutoUpdateFileTypes' = $App.ExecutionData.AutoUpdateFileTypes; + 'AutoUpdateOtherFileTypes' = $App.executionData.AutoUpdateOtherFileTypes } + $ApplicationSpec = New-Object VMware.Hv.ApplicationSpec -Property @{ 'Data' = $ApplicationData; 'ExecutionData' = $ExecutionData} + $AppService = New-Object VMware.Hv.ApplicationService + $AppService.Application_Create($services,$ApplicationSpec) + if($?) { + Write-Host "Application '$ApplicationName' created successfully" + return + } + Write-Host "Failed to create Application '$ApplicationName'. $_ " + return + } + } + if ($AppFoundInRDS -eq $False) { + Write-Host ""$ApplicationName" does not exist in any of the RDS Server(s) belongs to the Farm $FarmName." + } + } + end { + [System.GC]::Collect() + } +} + # Object related Export-ModuleMember -Function Get-HVMachine, Get-HVMachineSummary, Get-HVQueryResult, Get-HVQueryFilter, Get-HVInternalName # RDS Farm related Export-ModuleMember -Function Get-HVFarmSummary, Start-HVFarm, Start-HVPool, New-HVFarm, Remove-HVFarm, Get-HVFarm, Set-HVFarm, Add-HVRDSServer # Desktop Pool related Export-ModuleMember -Function Get-HVPoolSummary, New-HVPool, Remove-HVPool, Get-HVPool, Set-HVPool, Get-HVPoolSpec, Add-HVDesktop +# Application Pool related +Export-ModuleMember -Function Get-HVApplication, Remove-HVApplication, New-HVManualApplication, Get-HVPreInstalledApplication, New-HVPreInstalledApplication # Entitlement related Export-ModuleMember -Function New-HVEntitlement,Get-HVEntitlement,Remove-HVEntitlement Export-ModuleMember -Function Set-HVMachine, Reset-HVMachine, Remove-HVMachine @@ -11966,4 +12496,4 @@ Export-ModuleMember -Function Get-HVEventDatabase, Set-HVEventDatabase, Clear-HV # vCenter Server related Export-ModuleMember -Function Get-HVvCenterServer, Get-HVvCenterServerHealth # Misc/other related -Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot \ No newline at end of file +Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot From e8fdf541d4049497bc1c2eca1403981c2c653fbe Mon Sep 17 00:00:00 2001 From: Mark McGilly Date: Thu, 9 May 2019 04:49:39 -0400 Subject: [PATCH 106/175] Added Get-HcxLicense function Added parameter to set Proxy Exclusions in Set-HcxProxy Added ability to return UserName from Get-HcxNSXConfig Added ability to return UserName, LookupServiceURL from Get-HcxVCConfig --- Modules/VMware.HCX/VMware.HCX.psd1 | 2 +- Modules/VMware.HCX/VMware.HCX.psm1 | 42 +++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psd1 b/Modules/VMware.HCX/VMware.HCX.psd1 index a5e74f0..3b3f3b0 100644 --- a/Modules/VMware.HCX/VMware.HCX.psd1 +++ b/Modules/VMware.HCX/VMware.HCX.psd1 @@ -36,7 +36,7 @@ Description = 'PowerShell Module for Managing Hybrid Cloud Extension (HCX) on VM PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', 'Get-HcxRoleMapping', 'Set-HcxRoleMapping', 'Get-HcxProxy', 'Set-HcxProxy', 'Remove-HcxProxy' +FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', 'Get-HcxRoleMapping', 'Set-HcxRoleMapping', 'Get-HcxProxy', 'Set-HcxProxy', 'Remove-HcxProxy', 'Get-HcxLicense' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index 5582681..6ba3e8a 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -570,16 +570,22 @@ Function Get-HcxVCConfig { #> If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { $vcConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/vcenter" + $pscConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/lookupservice" if($PSVersionTable.PSEdition -eq "Core") { $vcRequests = Invoke-WebRequest -Uri $vcConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + $ssoRequests = Invoke-WebRequest -Uri $pscConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck } else { $vcRequests = Invoke-WebRequest -Uri $vcConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + $ssoRequests = Invoke-WebRequest -Uri $pscConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing } $vcData = ($vcRequests.content | ConvertFrom-Json).data.items + $ssoData = ($ssoRequests.content | ConvertFrom-Json).data.items $tmp = [pscustomobject] @{ Name = $vcData.config.name; + UserName = $vcData.Config.userName + LookupServiceUrl = $ssoData.config.lookupServiceUrl Version = $vcData.config.version; Build = $vcData.config.buildNumber; UUID = $vcData.config.vcuuid; @@ -589,6 +595,38 @@ Function Get-HcxVCConfig { } } +Function Get-HcxLicense { + <# + .NOTES + =========================================================================== + Created by: Mark McGilly + Date: 4/29/2019 + Organization: Liberty Mutual Insurance + =========================================================================== + + .SYNOPSIS + Returns the license key that is registered with HCX Manager + .DESCRIPTION + This cmdlet returns the license key registered with HCX Manager + .EXAMPLE + Get-HcxLicense + #> + + If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $hcxConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/hcx" + + if($PSVersionTable.PSEdition -eq "Core") { + $licenseRequests = Invoke-WebRequest -Uri $hcxConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $licenseRequests = Invoke-WebRequest -Uri $hcxConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing + } + $license = ($licenseRequests.content | ConvertFrom-Json).data.items + if($licenseRequests) { + $license.config.activationKey + } + } +} + Function Set-HcxLicense { <# .NOTES @@ -800,6 +838,7 @@ Function Get-HcxNSXConfig { $tmp = [pscustomobject] @{ Name = $nsxData.config.url; + UserName = $nsxData.config.userName Version = $nsxData.config.version; HCXUUID = $nsxData.config.uuid; } @@ -1211,6 +1250,7 @@ Function Set-HcxProxy { [Parameter(Mandatory=$True)]$ProxyPort, [Parameter(Mandatory=$False)]$ProxyUser, [Parameter(Mandatory=$False)]$ProxyPassword, + [Parameter(Mandatory=$False)]$ProxyExclusions, [Switch]$Troubleshoot ) @@ -1225,7 +1265,7 @@ Function Set-HcxProxy { config = @{ proxyHost = "$ProxyServer"; proxyPort = "$ProxyPort"; - nonProxyHosts = ""; + nonProxyHosts = "$ProxyExclusions"; userName = "$ProxyUser"; password = "$ProxyPassword"; } From 0576034d74146d3e2f4547b6d4b1b7372894986e Mon Sep 17 00:00:00 2001 From: Mark McGilly Date: Thu, 9 May 2019 04:57:23 -0400 Subject: [PATCH 107/175] Fix tabs instead of spaces --- Modules/VMware.HCX/VMware.HCX.psm1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index 6ba3e8a..b8f8866 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -570,7 +570,7 @@ Function Get-HcxVCConfig { #> If (-Not $global:hcxVAMIConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { $vcConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/vcenter" - $pscConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/lookupservice" + $pscConfigUrl = $global:hcxVAMIConnection.Server + "/api/admin/global/config/lookupservice" if($PSVersionTable.PSEdition -eq "Core") { $vcRequests = Invoke-WebRequest -Uri $vcConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing -SkipCertificateCheck @@ -580,12 +580,12 @@ Function Get-HcxVCConfig { $ssoRequests = Invoke-WebRequest -Uri $pscConfigUrl -Method GET -Headers $global:hcxVAMIConnection.headers -UseBasicParsing } $vcData = ($vcRequests.content | ConvertFrom-Json).data.items - $ssoData = ($ssoRequests.content | ConvertFrom-Json).data.items + $ssoData = ($ssoRequests.content | ConvertFrom-Json).data.items $tmp = [pscustomobject] @{ Name = $vcData.config.name; - UserName = $vcData.Config.userName - LookupServiceUrl = $ssoData.config.lookupServiceUrl + UserName = $vcData.Config.userName + LookupServiceUrl = $ssoData.config.lookupServiceUrl Version = $vcData.config.version; Build = $vcData.config.buildNumber; UUID = $vcData.config.vcuuid; @@ -838,7 +838,7 @@ Function Get-HcxNSXConfig { $tmp = [pscustomobject] @{ Name = $nsxData.config.url; - UserName = $nsxData.config.userName + UserName = $nsxData.config.userName Version = $nsxData.config.version; HCXUUID = $nsxData.config.uuid; } @@ -1250,7 +1250,7 @@ Function Set-HcxProxy { [Parameter(Mandatory=$True)]$ProxyPort, [Parameter(Mandatory=$False)]$ProxyUser, [Parameter(Mandatory=$False)]$ProxyPassword, - [Parameter(Mandatory=$False)]$ProxyExclusions, + [Parameter(Mandatory=$False)]$ProxyExclusions, [Switch]$Troubleshoot ) From 5f1a86e78ba5351d3b3128dcd2ca0ed81503549a Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 9 May 2019 06:50:22 -0700 Subject: [PATCH 108/175] Added Get/New/Remove functions for Policy Based VPN --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 8 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 297 ++++++++++++++++++- 2 files changed, 296 insertions(+), 9 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index c18be71..3f6f507 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -36,7 +36,13 @@ Description = 'PowerShell Module for Managing NSX-T on VMware Cloud on AWS' PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', 'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', 'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN', 'Remove-NSXTService', 'New-NSXTDistFirewallSection', 'Get-NSXTDistFirewallSection' +FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', ` +'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', ` +'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', ` +'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', ` +'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', ` +'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN', 'Remove-NSXTService', 'New-NSXTDistFirewallSection', 'Get-NSXTDistFirewallSection', ` +'New-NSXTPolicyBasedVPN', 'Get-NSXTPolicyBasedVPN', 'Remove-NSXTPolicyBasedVPN' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index f3ea7e6..0a7b5bd 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -2089,20 +2089,32 @@ Function Get-NSXTRouteBasedVPN { if($requests.StatusCode -eq 200) { $groups = ($requests.Content | ConvertFrom-Json).results - if ($PSBoundParameters.ContainsKey("Name")){ $groups = $groups | where {$_.display_name -eq $Name} } $results = @() foreach ($group in $groups) { - $tmp = [pscustomobject] @{ - Name = $group.display_name; - ID = $group.id; - Path = $group.path; - RoutingConfigPath = $group.l3vpn_session.routing_config_path; + if($group.l3vpn_session.resource_type -eq "RouteBasedL3VpnSession") { + $tmp = [pscustomobject] @{ + Name = $group.display_name; + ID = $group.id; + Path = $group.path; + Routing_Config_Path = $group.l3vpn_session.routing_config_path; + Local_IP = $group.local_address; + Remote_Public_IP = $group.remote_public_address; + Tunnel_IP_Address = $group.l3vpn_session.tunnel_subnets.ip_addresses + IKE_Version = $group.ike_version; + IKE_Encryption = $group.ike_encryption_algorithms; + IKE_Digest = $group.ike_digest_algorithms; + Tunnel_Encryption = $group.tunnel_encryption_algorithms; + Tunnel_Digest = $group.tunnel_digest_algorithms; + DH_Group = $group.dh_groups; + Created_by = $group._create_user; + Last_Modified_by = $group._last_modified_user; + } + $results+=$tmp } - $results+=$tmp } $results } @@ -2194,4 +2206,273 @@ Function Remove-NSXTRouteBasedVPN { Write-Host "Successfully removed NSX-T BGP Neighbor" } } -} \ No newline at end of file +} + +Function New-NSXTPolicyBasedVPN { +<# +.NOTES +=========================================================================== +Created by: William Lam +Date: 05/09/2019 +Organization: VMware +Blog: http://www.virtuallyghetto.com +Twitter: @lamw +=========================================================================== + +.SYNOPSIS + Creates a new NSX-T Policy Based VPN +.DESCRIPTION + This cmdlet creates a new NSX-T Policy Based VPN +.EXAMPLE + New-NSXTPolicyBasedVPN -Name Policy1 ` + -LocalIP 18.194.102.229 ` + -RemotePublicIP 3.122.124.16 ` + -RemotePrivateIP 169.254.90.1 ` + -SequenceNumber 0 ` + -SourceIPs @("192.168.4.0/24", "192.168.5.0/24") ` + -DestinationIPs @("172.204.10.0/24", "172.204.20.0/24") ` + -TunnelEncryption AES_256 ` + -TunnelDigestEncryption SHA2_256 ` + -IKEEncryption AES_256 ` + -IKEDigestEncryption SHA2_256 ` + -DHGroup GROUP14 ` + -IKEVersion IKE_V1 ` + -PresharedPassword VMware123. ` + -Troubleshoot +#> + param( + [Parameter(Mandatory=$true)][String]$Name, + [Parameter(Mandatory=$true)][String]$LocalIP, + [Parameter(Mandatory=$true)][String]$RemotePublicIP, + [Parameter(Mandatory=$true)][String]$RemotePrivateIP, + [Parameter(Mandatory=$True)]$SequenceNumber, + [Parameter(Mandatory=$true)][String[]]$SourceIPs, + [Parameter(Mandatory=$true)][String[]]$DestinationIPs, + [Parameter(Mandatory=$true)][String][ValidateSet("AES_128","AES_256","AES_GCM_128","AES_GCM_192","AES_GCM_256")]$TunnelEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("SHA1","SHA2_256")]$TunnelDigestEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("AES_128","AES_256","AES_GCM_128","AES_GCM_192","AES_GCM_256")]$IKEEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("SHA1","SHA2_256")]$IKEDigestEncryption, + [Parameter(Mandatory=$true)][String][ValidateSet("GROUP2","GROUP5","GROUP14","GROUP15","GROUP16")]$DHGroup, + [Parameter(Mandatory=$true)][String][ValidateSet("IKE_V1","IKE_V2","IKE_FLEX")]$IKEVersion, + [Parameter(Mandatory=$true)][String]$PresharedPassword, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + + $generatedId = (New-Guid).Guid + + $sources = @() + foreach ($source in $SourceIPs) { + $tmp = @{ subnet = $source} + $sources+=$tmp + } + + $destinations = @() + foreach ($destination in $DestinationIPs) { + $tmp = @{ subnet = $destination} + $destinations+=$tmp + } + + $payload = @{ + display_name = $Name; + enabled = $true; + local_address = $LocalIP; + remote_private_address = $RemotePrivateIP; + remote_public_address = $RemotePublicIP; + passphrases = @("$PresharedPassword"); + tunnel_digest_algorithms = @("$TunnelDigestEncryption"); + tunnel_encryption_algorithms = @("$TunnelEncryption"); + ike_digest_algorithms = @("$IKEDigestEncryption"); + ike_encryption_algorithms = @("$IKEEncryption"); + enable_perfect_forward_secrecy = $true; + dh_groups = @("$DHGroup"); + ike_version = $IKEVersion; + + l3vpn_session = @{ + resource_type = "PolicyBasedL3VpnSession"; + rules = @( + @{ + id = $generatedId; + display_name = $generatedId; + sequence_number = $SequenceNumber; + sources = @($sources) + destinations = @($destinations) + } + ) + } + } + $body = $payload | ConvertTo-Json -Depth 5 + + $method = "put" + $policyBasedVPNURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l3vpns/$Name" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$policyBasedVPNURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $policyBasedVPNURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $policyBasedVPNURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in configuring Policy Based VPN" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully created Policy Based VPN" + ($requests.Content | ConvertFrom-Json) + } + } +} + +Function Get-NSXTPolicyBasedVPN { +<# +.NOTES +=========================================================================== +Created by: William Lam +Date: 05/09/2019 +Organization: VMware +Blog: http://www.virtuallyghetto.com +Twitter: @lamw +=========================================================================== + +.SYNOPSIS + Returns all NSX-T Policy Based VPN Tunnels +.DESCRIPTION + This cmdlet retrieves all NSX-T Policy Based VPN Tunnels description +.EXAMPLE + Get-NSXTPolicyBasedVPN +.EXAMPLE + Get-NSXTPolicyBasedVPN -Name "VPN-T1" +#> + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $policyBaseVPNURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l3vpns" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$routeBaseVPNURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $policyBaseVPNURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $policyBaseVPNURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Policy Based VPN Tunnels" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $groups = ($requests.Content | ConvertFrom-Json).results + if ($PSBoundParameters.ContainsKey("Name")){ + $groups = $groups | where {$_.display_name -eq $Name} + } + + $results = @() + foreach ($group in $groups) { + if($group.l3vpn_session.resource_type -eq "PolicyBasedL3VpnSession") { + $tmp = [pscustomobject] @{ + Name = $group.display_name; + ID = $group.id; + Path = $group.path; + Local_IP = $group.local_address; + Remote_Public_IP = $group.remote_public_address; + Tunnel_IP_Address = $group.remote_private_address; + IKE_Version = $group.ike_version; + IKE_Encryption = $group.ike_encryption_algorithms; + IKE_Digest = $group.ike_digest_algorithms; + Tunnel_Encryption = $group.tunnel_encryption_algorithms; + Tunnel_Digest = $group.tunnel_digest_algorithms; + DH_Group = $group.dh_groups; + IP_Sources = $group.l3vpn_session.rules.sources.subnet; + IP_Destinations = $group.l3vpn_session.rules.destinations.subnet + Created_by = $group._create_user; + Last_Modified_by = $group._last_modified_user; + } + $results+=$tmp + } + } + $results + } + } +} + +Function Remove-NSXTPolicyBasedVPN { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 05/09/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes a policy based VPN Tunnel + .DESCRIPTION + This cmdlet removes a policy based VPN Tunnel + .EXAMPLE + Remove-NSXTPolicyBasedVPN -Name "Policy1" -Troubleshoot +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $TunnelId = (Get-NSXTPolicyBasedVPN -Name $Name).ID + + # Delete IPSEC tunnel + $method = "DELETE" + $deleteVPNtunnelURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l3vpns/$TunnelId" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$deleteVPNtunnelURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $deleteVPNtunnelURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $deleteVPNtunnelURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in removing NSX-T VPN Tunnel: $Name" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully removed NSX-T VPN Tunnel: $Name" + } + } +} From 2a5eff4fd1195164fef8c1fd461afc808946d910 Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 28 May 2019 06:20:26 -0700 Subject: [PATCH 109/175] Adding DRaaS Module + VMC module typo fix --- Modules/VMware.DRaaS/VMware.DRaaS.psd1 | Bin 0 -> 7718 bytes Modules/VMware.DRaaS/VMware.DRaaS.psm1 | 256 +++++++++++++++++++++++++ Modules/VMware.VMC/VMware.VMC.psm1 | 7 +- 3 files changed, 260 insertions(+), 3 deletions(-) create mode 100755 Modules/VMware.DRaaS/VMware.DRaaS.psd1 create mode 100644 Modules/VMware.DRaaS/VMware.DRaaS.psm1 diff --git a/Modules/VMware.DRaaS/VMware.DRaaS.psd1 b/Modules/VMware.DRaaS/VMware.DRaaS.psd1 new file mode 100755 index 0000000000000000000000000000000000000000..fd5ab0692124655225f62337b7c4fa3c07651ab6 GIT binary patch literal 7718 zcmeI1Yfl?T6o%(BzhWgm098XmN|L5hr63y;Btj98v|oLtZt$hHfkajQdfWGz<6&mJ zYiv-WR#j!;_3qA`%X{v_Uw^K**%jkRW~Yg;s$?vwjL*Bfzbh}SE3t?x*sC0_j{ zG=`!IjVJDzd+eV2?;ZDYwrfo^|Ilxf;mozfzvo6?lYXYDY1P!*f!E?wNyo0<87d87 zG12apo zSthg9HLdGwH5m0I8R%85E*uqB z&W(Q>!#UTH_z^i5(vB=ZE-=sU&(M#VVG;iDo~L7cH-+q$s6G{@#BMQ{O$wm}E=3{( z(M7JoKgP-%c*%BRi@JXo<2^)4vR*dE znvN%;b>n3{6NY#%`lL}95qv8-kmW+W2l~$OC=_qR8uFj&yXB<>1>#{-aTBt}R)WV{ zPpc=tB1;q=v9Zvr#syCt2vKAP>1yeTJChMvum+LY^S_qkRYkKp6Yb7rq3E}{HCL0G z__SJfUy0WjAn|5KG0J5&k1_N$(EoaRR9oS`+MqM>2in+)ys_<$RV&W*>p*YFavgaX zdF;czJ!o4y&TlI%(Mk*iAH=gQMywKFiyN60zYIMLnF`OX^29=MM0WWgD&(y~cWI5I z!VX07lXSA$Sl5%O^y}!mtlgKvG)PR$_w}*LPxnM5Ug>(_H5&W8Mok1^vO-POR=kvAU3hu{|}Hu9CipUvzu)Ky+DX8G16Zw{=XxV=m;YL#-zY z@a2K8Y@jsoKEnD!RH*WXm+en!hiU}P(BDQGP2*G1POCs#;m`st^GiL04wJ`{gCBmZvOtK23z_0NFQ{6X@4>yx&B-*>psuq>sgJds01MkO7uz2=AA#p0fs#4F#OF0V3WZ=#;O%|{?pcaI=ows>sl)j~V$BIm^pkn*Y z7f-csel~rab*W`fvAC!11!?AWD96r$kAT>BBe7}PaUUg}Ptvbe=N$5NsOET^ zWks|b&z{=}29c-YKp z6o_HG+$IXB)AiWg8s>BBTC6@1TS$jiRvC)2pqtzBBuz@~S{T|&;3KQiU zB;U}CjBZtL&MMxRp&wGrBruzHSRHR`$5>ze&*ic~sx`dT_z>vA8KKP`gm zqSf+e2|3MGBs!88Sk|?QgXWi#Fs(TF2d987O;a|ZkXgyPWY9&q-DFE^N#s?oDDhn` zM_TtED#L*!CF@5XW&U(eJ@wRfDn{MlSHo*ZK8H86NU&3=9Vt#)=L6jlbB@l2QV|LW@t$np$nRNT&jDGfF_YgowidvP6nbU=hg%p zB8yW*s=U>GdS7sdE48?gEEYAavH1u6gT&#QOP+gRSQDtLE~6f4E|Y z#kBCOjaj7+J3i|fyY__yx!d^VQCH3t{MTsF&NN%b*si7l=Qm#Wk^X}-@SVN+_TjB8 z)yP{7ncquPurt*Z9-R1fT|-s%QpnnA2v2(IrQ@7|7jX7w69VX`GmA}A%jOnx$xpMa z020g + Param ( + [Parameter(Mandatory=$true)][String]$RefreshToken, + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName + ) + + If (-Not $global:DefaultVMCServers.IsConnected) { Write-error "No valid VMC Connection found, please use the Connect-VMC to connect"; break } Else { + $sddcService = Get-VmcService "com.vmware.vmc.orgs.sddcs" + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $sddc = $sddcService.get($orgId,$sddcId) + + } + + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + if($results.StatusCode -ne 200) { + Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" + break + } + $accessToken = ($results | ConvertFrom-Json).access_token + + $headers = @{ + "csp-auth-token"="$accessToken" + "Content-Type"="application/json" + "Accept"="application/json" + } + $global:draasConnection = new-object PSObject -Property @{ + 'Server' = "https://vmc.vmware.com/vmc/draas/api/orgs/$orgId/sddcs/$sddcId/site-recovery" + 'headers' = $headers + } + $global:draasConnection +} + +Function Get-DRaas { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 05/23/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns information about DRaaS configuration for a given SDDC + .DESCRIPTION + This cmdlet returns information about DRaaS configuration for a given SDDC. Can be used to monitor both activate and deactivate operations. + .EXAMPLE + Get-DRaas +#> + Param ( + [Switch]$Troubleshoot + ) + + If (-Not $global:draasConnection) { Write-error "No DRaaS Connection found, please use Connect-DRaaS" } Else { + $method = "GET" + $draasUrl = $global:draasConnection.Server + $draasVersionUrl = $global:draasConnection.Server + "/versions" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$draasUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $draasUrl -Method $method -Headers $global:draasConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $draasUrl -Method $method -Headers $global:draasConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe CSP session is no longer valid, please re-run the Connect-DRaaS cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving DRaaS Information" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $json = ($requests.Content | ConvertFrom-Json) + + $draasId = $json.id; + $draasState = $json.site_recovery_state; + $srmNode = $json.srm_node.ip_address; + $srmNodeState = $json.site_recovery_state; + $vrNode = $json.vr_node.ip_address; + $vrNodeState = $json.vr_node.state; + $draasUrl = $json.draas_h5_url; + + if($srmNodeState -eq "ACTIVATED") { + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$draasVersionUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $draasVersionUrl -Method $method -Headers $global:draasConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $draasVersionUrl -Method $method -Headers $global:draasConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe CSP session is no longer valid, please re-run the Connect-DRaaS cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving DRaaS Information" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $json = ($requests.Content | ConvertFrom-Json).node_versions + + $srmVersion,$srmDescription = ($json | where {$_.node_ip -eq $srmNode}).full_version.split("`n") + $vrVersion,$vrDescription = ($json | where {$_.node_ip -eq $vrNode}).full_version.split("`n") + + $results = [pscustomobject] @{ + ID = $draasId; + DRaaSState = $draasState; + SRMNode = $srmNode; + SRMVersion = $srmVersion; + SRMNodeState = $srmNodeState; + VRNode = $vrNode; + VRVersion = $vrVersion; + VRNodeState = $vrNodeState; + DRaaSURL = $draasUrl; + } + + $results + } + } elseif ($srmNodeState -eq "ACTIVATING" -or $srmNodeState -eq "DEACTIVATING") { + $results = [pscustomobject] @{ + ID = $draasId; + DRaaSState = $draasState; + SRMNode = $srmNode; + SRMNodeState = $srmNodeState; + VRNode = $vrNode; + VRNodeState = $vrNodeState; + DRaaSURL = $draasUrl; + } + + $results + } else { + Write-Host "`nDRaaS is currently deactivated, please run Set-DRaas -Activate`n" + } + } else { + Write-Host "`nDRaaS has not been activated before, please run Set-DRaas -Activate`n" + } + } +} + + +Function Set-DRaas { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 05/23/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Activate or deactivate DRaaS for a given SDDC + .DESCRIPTION + This cmdlet activates or deactivates DRaaS for a given SDDC + .EXAMPLE + Get-DRaas +#> + Param ( + [Switch]$Activate, + [Switch]$Deactivate, + [Switch]$Troubleshoot + ) + + If (-Not $global:draasConnection) { Write-error "No DRaaS Connection found, please use Connect-DRaaS" } Else { + $draasUrl = $global:draasConnection.server + + if($Activate) { + $method = "POST" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$draasUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $draasUrl -Method $method -Headers $global:draasConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $draasUrl -Method $method -Headers $global:draasConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe CSP session is no longer valid, please re-run the Connect-DRaaS cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in activating DRaaS" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + Write-Host "`nActivating DRaaS, this will take some time and you can monitor the progress using Get-DRaaS or using the VMC Console UI`n" + } elseif ($Deactivate) { + $method = "DELETE" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$draasUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $draasUrl -Method $method -Headers $global:draasConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $draasUrl -Method $method -Headers $global:draasConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe CSP session is no longer valid, please re-run the Connect-DRaaS cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in deactivating DRaaS" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + Write-Host "`nDeactivating DRaaS, this will take some time and you can monitor the progress using Get-DRaaS or the VMC Console UI`n" + } else { + Write-Error "Invalid Operation" + } + } +} \ No newline at end of file diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 33f78a7..63ad087 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -874,8 +874,8 @@ Function Get-VMCSDDCSummary { Get-VMCSDDCSummary -Name -Org #> Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName + [Parameter(Mandatory=$True)]$Org, + [Parameter(Mandatory=$True)]$Name ) If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { @@ -895,6 +895,7 @@ Function Get-VMCSDDCSummary { InstanceType = $sddc.resource_config.sddc_manifest.esx_ami.instance_type; VpcCIDR = $sddc.resource_config.vpc_info.vpc_cidr; NSXT = $sddc.resource_config.nsxt; + VPC_VGW = $sddc.resource_config.vpc_info.vgw_id; } $results } @@ -903,7 +904,7 @@ Function Get-VMCPublicIP { <# .NOTES =========================================================================== - Created by: William Lam + Created by: William LamVPC_VGW Date: 09/12/2018 Organization: VMware Blog: http://www.virtuallyghetto.com From 5f3f41ff449c9f7d5e3e5dcb7235887640dd9231 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 8 Jun 2019 13:13:19 -0700 Subject: [PATCH 110/175] Added Get/Set NSX-T DNS Zone Configuration --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 2 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 129 ++++++++++++++++++- 2 files changed, 129 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index 3f6f507..1b97cd3 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -42,7 +42,7 @@ FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', ' 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', ` 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', ` 'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN', 'Remove-NSXTService', 'New-NSXTDistFirewallSection', 'Get-NSXTDistFirewallSection', ` -'New-NSXTPolicyBasedVPN', 'Get-NSXTPolicyBasedVPN', 'Remove-NSXTPolicyBasedVPN' +'New-NSXTPolicyBasedVPN', 'Get-NSXTPolicyBasedVPN', 'Remove-NSXTPolicyBasedVPN', 'Get-NSXTDNS', 'Set-NSXTDNS' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 0a7b5bd..5004034 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -2334,7 +2334,7 @@ Twitter: @lamw } } } - + Function Get-NSXTPolicyBasedVPN { <# .NOTES @@ -2476,3 +2476,130 @@ Function Remove-NSXTPolicyBasedVPN { } } } + +Function Get-NSXTDNS { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/08/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns DNS Zone configuration for MGW or CGW + .DESCRIPTION + This cmdlet retrieves DNS Zone configuration for MGW or CGW + .EXAMPLE + Get-NSXTDNS -GatewayType MGW + .EXAMPLE + Get-NSXTDNS -GatewayType CGW +#> + param( + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $dnsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/dns-forwarder-zones/$($GatewayType.toLower())-dns-zone" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$dnsURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $dnsURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $dnsURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T DNS Zones" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $dnsZone = ($requests.Content | ConvertFrom-Json) + + $results = [pscustomobject] @{ + Name = $dnsZone.display_name; + DNS1 = $dnsZone.upstream_servers[0]; + DNS2 = $dnsZone.upstream_servers[1]; + Domain = $dnsZone.dns_domain_names; + } + $results + } + } +} + +Function Set-NSXTDNS { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/08/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns DNS Zone configuration for MGW or CGW + .DESCRIPTION + This cmdlet retrieves DNS Zone configuration for MGW or CGW + .EXAMPLE + Set-NSXTDNS -GatewayType MGW -DNS @("192.168.1.14","192.168.1.15") + .EXAMPLE + Set-NSXTDNS -GatewayType CGW -DNS @("8.8.8.8") +#> + param( + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Parameter(Mandatory=$true)][String[]]$DNS, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "PATCH" + $dnsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/dns-forwarder-zones/$($GatewayType.toLower())-dns-zone" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$dnsURL`n" + } + + $payload = @{ + upstream_servers = @($DNS) + } + + $body = $payload | ConvertTo-Json -Depth 5 + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $dnsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $dnsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in updating NSX-T DNS Zones" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully updated NSX-T DNS for $GatewayType" + } + } +} \ No newline at end of file From b5563cc11a4adf1ea6ba155a05388865c80d90d1 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Fri, 14 Jun 2019 10:10:09 -0400 Subject: [PATCH 111/175] Update VMware.Community.CISTag.psm1 Add Datastore support for New-CISTagAssignment --- .../VMware.Community.CISTag.psm1 | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 index 05594e4..062cd95 100644 --- a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 +++ b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 @@ -40,7 +40,7 @@ function Get-CISTag { } else { $tagArray = @() $tagIdList = $tagSvc.list() | Select-Object -ExpandProperty Value - [integer]$counter = 1 + [int]$counter = 1 foreach ($t in $tagIdList) { $tagArray += $tagSvc.get($t) $counter++ @@ -49,11 +49,11 @@ function Get-CISTag { } if ($PSBoundParameters.ContainsKey("Name")) { if ($vCenterConn){ - $tagOutput = $vCTagList | where {$_.Name -eq $Name} - } else {$tagOutput = $tagArray | Where {$_.Name -eq $Name}} + $tagOutput = $vCTagList | Where-Object {$_.Name -eq $Name} + } else {$tagOutput = $tagArray | Where-Where-Object {$_.Name -eq $Name}} } elseif ($PSBoundParameters.ContainsKey("Category")) { if ($vCenterConn){ - $tagOutput = $vCTagList | where {$_.Category -eq $Category} + $tagOutput = $vCTagList | Where-Object {$_.Category -eq $Category} } else { $tagCatid = Get-CISTagCategory -Name $Category | Select-Object -ExpandProperty Id $tagIdList = $tagSvc.list_tags_for_category($tagCatid) @@ -199,7 +199,7 @@ function Get-CISTagCategory { $tagCatArray += $tagCatSvc.get($tc) } if ($PSBoundParameters.ContainsKey("Name")) { - $tagCatOutput = $tagCatArray | Where {$_.Name -eq $Name} + $tagCatOutput = $tagCatArray | Where-Where-Object {$_.Name -eq $Name} } else { $tagCatOutput = $tagCatArray } @@ -337,6 +337,8 @@ function Get-CISTagAssignment { if ($PSBoundParameters.ContainsKey("ObjectId")) { if ($ObjectId.split('-')[0] -eq 'vm') { $objType = 'VirtualMachine' + } elseif ($ObjectId.Split('-')[0] -eq 'datastore') { + $objType = 'Datastore' } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() $objObject.id = $ObjectId @@ -366,7 +368,7 @@ function Get-CISTagAssignment { $tagIdOutput = @() $tagCategories = Get-CISTagCategory | Sort-Object -Property Name if ($Category) { - $tagCatId = $tagCategories | where {$_.Name -eq $Category} | Select-Object -ExpandProperty Id + $tagCatId = $tagCategories | Where-Object {$_.Name -eq $Category} | Select-Object -ExpandProperty Id $tagIdOutput += $tagSvc.list_tags_for_category($tagCatId) } else { foreach ($tagCat in $tagCategories) { @@ -380,9 +382,9 @@ function Get-CISTagAssignment { foreach ($tagId in $tagIdOutput) { $tagAttObj = @() if ($Entity) { - $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) | where {$_.type -eq $viObject.type -and $_.id -eq $viObject.Value} + $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) | Where-Object {$_.type -eq $viObject.type -and $_.id -eq $viObject.Value} } else { - $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) | where {$_.id -eq $ObjectId} + $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) | Where-Object {$_.id -eq $ObjectId} } foreach ($obj in $tagAttObj) { if ($obj.type -eq "VirtualMachine") { @@ -393,7 +395,7 @@ function Get-CISTagAssignment { } else {$objName = 'Object Not Found'} $tempObject = "" | Select-Object Tag, Entity - $tempObject.Tag = $tagReference | where {$_.id -eq $tagId} | Select-Object -ExpandProperty Name + $tempObject.Tag = $tagReference | Where-Object {$_.id -eq $tagId} | Select-Object -ExpandProperty Name $tempObject.Entity = $objName $tagOutput += $tempObject } @@ -419,7 +421,7 @@ function Get-CISTagAssignment { $objName = $vmSvc.list($filterVmObj) | Select-Object -ExpandProperty Name } else {$objName = 'Object Not Found'} $tempObject = "" | Select-Object Tag, Entity - $tempObject.Tag = $tagReference | where {$_.id -eq $tagId} | Select-Object -ExpandProperty Name + $tempObject.Tag = $tagReference | Where-Object {$_.id -eq $tagId} | Select-Object -ExpandProperty Name $tempObject.Entity = $objName $tagOutput += $tempObject } @@ -536,7 +538,9 @@ function New-CISTagAssignment { } elseif ($PSBoundParameters.ContainsKey("TagId") -and $PSBoundParameters.ContainsKey("ObjectId")) { if ($ObjectId.split('-')[0] -eq 'vm') { $objType = 'VirtualMachine' - } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} + } elseif ($ObjectId.Split('-')[0] -eq 'datastore') { + $objType = 'Datastore' + } else {Write-Warning 'Only VirtualMachine and Datastore types currently supported.'; break} if ($TagId -is [array] -and $ObjectId -isnot [array]) { $objObject = $tagAssocSvc.help.attach_multiple_tags_to_object.object_id.create() $objObject.id = $ObjectId @@ -674,7 +678,9 @@ function Remove-CISTagAssignment { } elseif ($PSBoundParameters.ContainsKey("TagId") -and $PSBoundParameters.ContainsKey("ObjectId")) { if ($ObjectId.split('-')[0] -eq 'vm') { $objType = 'VirtualMachine' - } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} + } elseif ($ObjectId.Split('-')[0] -eq 'datastore') { + $objType = 'Datastore' + }else {Write-Warning 'Only VirtualMachine types currently supported.'; break} if ($TagId -is [array] -and $ObjectId -isnot [array]) { $objObject = $tagAssocSvc.help.detach_multiple_tags_from_object.object_id.create() $objObject.id = $ObjectId From b3e9ffc51d63c7e0c879ea25c917f093dcc2aca8 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Fri, 14 Jun 2019 16:59:43 -0400 Subject: [PATCH 112/175] Update VMware.Community.CISTag.psm1 Issues fixed with "where-where-object" typos Loop fixed for detecting the Object Type Get/Remove-CISTagAssignment updated to work with Datastore objects --- .../VMware.Community.CISTag.psm1 | 111 ++++++++++++++---- 1 file changed, 85 insertions(+), 26 deletions(-) diff --git a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 index 062cd95..4ca717c 100644 --- a/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 +++ b/Modules/VMware.Community.CISTag/VMware.Community.CISTag.psm1 @@ -50,7 +50,7 @@ function Get-CISTag { if ($PSBoundParameters.ContainsKey("Name")) { if ($vCenterConn){ $tagOutput = $vCTagList | Where-Object {$_.Name -eq $Name} - } else {$tagOutput = $tagArray | Where-Where-Object {$_.Name -eq $Name}} + } else {$tagOutput = $tagArray | Where-Object {$_.Name -eq $Name}} } elseif ($PSBoundParameters.ContainsKey("Category")) { if ($vCenterConn){ $tagOutput = $vCTagList | Where-Object {$_.Category -eq $Category} @@ -199,7 +199,7 @@ function Get-CISTagCategory { $tagCatArray += $tagCatSvc.get($tc) } if ($PSBoundParameters.ContainsKey("Name")) { - $tagCatOutput = $tagCatArray | Where-Where-Object {$_.Name -eq $Name} + $tagCatOutput = $tagCatArray | Where-Object {$_.Name -eq $Name} } else { $tagCatOutput = $tagCatArray } @@ -336,10 +336,10 @@ function Get-CISTagAssignment { $tagAssocSvc = Get-CisService -Name com.vmware.cis.tagging.tag_association if ($PSBoundParameters.ContainsKey("ObjectId")) { if ($ObjectId.split('-')[0] -eq 'vm') { - $objType = 'VirtualMachine' + $objType = "VirtualMachine" } elseif ($ObjectId.Split('-')[0] -eq 'datastore') { $objType = 'Datastore' - } else {Write-Warning 'Only VirtualMachine types currently supported.'; break} + } else {Write-Warning 'Only VirtualMachine and Datastore types currently supported.'; break} $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() $objObject.id = $ObjectId $objObject.type = $objType @@ -356,8 +356,15 @@ function Get-CISTagAssignment { $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + $dsSvc = Get-CisService com.vmware.vcenter.datastore + $filterDsNameObj = $dsSvc.Help.list.filter.Create() + $filterDsNameObj.names.add($Entity) | Out-Null + $objId = $dsSvc.list($filterDsNameObj) | Select-Object -ExpandProperty datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() $objObject.id = $objId $objObject.type = $objType @@ -392,8 +399,12 @@ function Get-CISTagAssignment { $filterVmObj = $vmsvc.help.list.filter.create() $filterVmObj.vms.add($obj.Id) | Out-Null $objName = $vmSvc.list($filterVmObj) | Select-Object -ExpandProperty Name - } - else {$objName = 'Object Not Found'} + } elseif ($obj.type -eq "Datastore") { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsObj = $dsSvc.help.list.filter.create() + $filterDsObj.datastores.add($obj.Id) | Out-Null + $objName = $dsSvc.list($filterDsObj) | Select-Object -ExpandProperty Name + } else {$objName = 'Object Not Found'} $tempObject = "" | Select-Object Tag, Entity $tempObject.Tag = $tagReference | Where-Object {$_.id -eq $tagId} | Select-Object -ExpandProperty Name $tempObject.Entity = $objName @@ -406,8 +417,10 @@ function Get-CISTagAssignment { $tagAttObj += $tagAssocSvc.list_attached_objects($tagId) if ($global:DefaultVIServer -and $global:DefaultVIServer.Name -eq $global:DefaultCisServers.Name) { [Boolean]$vCenterConn = $true - } elseif ($tagAttObj.Type -contains 'VirtualMachine') { + } elseif ($tagAttObj.Type -contains "VirtualMachine") { if (-Not $vmSvc) {$vmSvc = Get-CisService -Name com.vmware.vcenter.vm} + } elseif ($tagAttObj.Type -contains "Datastore") { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} } foreach ($obj in $tagAttObj) { if ($vCenterConn) { @@ -419,6 +432,10 @@ function Get-CISTagAssignment { $filterVmObj = $vmsvc.help.list.filter.create() $filterVmObj.vms.add($obj.Id) | Out-Null $objName = $vmSvc.list($filterVmObj) | Select-Object -ExpandProperty Name + } elseif ($obj.type -eq "Datastore") { + $filterDsObj = $dsSvc.help.list.filter.create() + $filterDsObj.datastores.add($obj.Id) | Out-Null + $objName = $dsSvc.list($filterDsObj) | Select-Object -ExpandProperty Name } else {$objName = 'Object Not Found'} $tempObject = "" | Select-Object Tag, Entity $tempObject.Tag = $tagReference | Where-Object {$_.id -eq $tagId} | Select-Object -ExpandProperty Name @@ -481,12 +498,19 @@ function New-CISTagAssignment { $objObject.id = $viObject.Value $objObject.type = $viObject.type } else { - $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + if (-Not $vmSvc) {$vmSvc = Get-CisService -Name com.vmware.vcenter.vm} $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsNameObj = $dsSvc.Help.list.filter.Create() + $filterDsNameObj.names.add($Entity) | Out-Null + $objId = $dsSvc.list($filterDsNameObj) | Select-Object -ExpandProperty datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() $objObject.id = $objId $objObject.type = $objType @@ -502,12 +526,19 @@ function New-CISTagAssignment { $objObject.id = $viObject.Value $objObject.type = $viObject.type } else { - $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + if (-Not $vmSvc) {$vmSvc = Get-CisService -Name com.vmware.vcenter.vm} $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsObj = $dsSvc.help.list.filter.create() + $filterDsObj.datastores.add($obj.Id) | Out-Null + $objId = $dsSvc.list($filterDsObj) | Select-Object -ExpandProperty Datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() $objObject.id = $objId $objObject.type = $objType @@ -523,12 +554,19 @@ function New-CISTagAssignment { $objObject.id = $viObject.Value $objObject.type = $viObject.type } else { - $vmSvc = Get-CisService -Name com.vmware.vcenter.vm + if (-Not $vmSvc) {$vmSvc = Get-CisService -Name com.vmware.vcenter.vm} $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsNameObj = $dsSvc.Help.list.filter.Create() + $filterDsNameObj.names.add($Entity) | Out-Null + $objId = $dsSvc.list($filterDsNameObj) | Select-Object -ExpandProperty datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.list_attached_tags.object_id.create() $objObject.id = $objId $objObject.type = $objType @@ -537,7 +575,7 @@ function New-CISTagAssignment { } } elseif ($PSBoundParameters.ContainsKey("TagId") -and $PSBoundParameters.ContainsKey("ObjectId")) { if ($ObjectId.split('-')[0] -eq 'vm') { - $objType = 'VirtualMachine' + $objType = "VirtualMachine" } elseif ($ObjectId.Split('-')[0] -eq 'datastore') { $objType = 'Datastore' } else {Write-Warning 'Only VirtualMachine and Datastore types currently supported.'; break} @@ -625,8 +663,15 @@ function Remove-CISTagAssignment { $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsNameObj = $dsSvc.Help.list.filter.Create() + $filterDsNameObj.names.add($Entity) | Out-Null + $objId = $dsSvc.list($filterDsNameObj) | Select-Object -ExpandProperty datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.detach_multiple_tags_from_object.object_id.create() $objObject.id = $objId $objObject.type = $objType @@ -646,8 +691,15 @@ function Remove-CISTagAssignment { $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsNameObj = $dsSvc.Help.list.filter.Create() + $filterDsNameObj.names.add($Entity) | Out-Null + $objId = $dsSvc.list($filterDsNameObj) | Select-Object -ExpandProperty datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.detach_tag_from_multiple_objects.object_ids.element.create() $objObject.id = $objId $objObject.type = $objType @@ -667,8 +719,15 @@ function Remove-CISTagAssignment { $filterVmNameObj = $vmsvc.help.list.filter.create() $filterVmNameObj.names.add($Entity) | Out-Null $objId = $vmSvc.list($filterVmNameObj) | Select-Object -ExpandProperty vm - if ($objId) {$objType = 'VirtualMachine'} - else {Write-Warning "No entities found."; break} + if ($objId) {$objType = "VirtualMachine"} + else { + if (-Not $dsSvc) {$dsSvc = Get-CisService -Name com.vmware.vcenter.datastore} + $filterDsNameObj = $dsSvc.Help.list.filter.Create() + $filterDsNameObj.names.add($Entity) | Out-Null + $objId = $dsSvc.list($filterDsNameObj) | Select-Object -ExpandProperty datastore + if ($objId) {$objType = "Datastore"} + else {Write-Warning "No entities found."; break} + } $objObject = $tagAssocSvc.help.detach.object_id.create() $objObject.id = $objId $objObject.type = $objType @@ -677,7 +736,7 @@ function Remove-CISTagAssignment { } } elseif ($PSBoundParameters.ContainsKey("TagId") -and $PSBoundParameters.ContainsKey("ObjectId")) { if ($ObjectId.split('-')[0] -eq 'vm') { - $objType = 'VirtualMachine' + $objType = "VirtualMachine" } elseif ($ObjectId.Split('-')[0] -eq 'datastore') { $objType = 'Datastore' }else {Write-Warning 'Only VirtualMachine types currently supported.'; break} From e7222d13f7d9b0d621729ddf6d5ef7e69a254edc Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 19 Jun 2019 06:01:10 -0700 Subject: [PATCH 113/175] Fix Get-VMCOrg / Get-VMCSDDC to use -eq vs -match --- Modules/VMware.VMC/VMware.VMC.psm1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 63ad087..4fe807d 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -81,13 +81,13 @@ Function Get-VMCOrg { Return all the info about the orgs you are a part of #> Param ( - [Parameter(Mandatory=$false)]$Name + [Parameter(Mandatory=$false)]$Name ) If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use Connect-VMC to connect" } Else { $orgService = Get-VMCService com.vmware.vmc.orgs if ($PSBoundParameters.ContainsKey("Name")){ - $orgs = $orgService.list() | Where {$_.display_name -match $Name} + $orgs = $orgService.list() | Where {$_.display_name -eq $Name} } Else { $orgs = $orgService.list() } @@ -130,7 +130,7 @@ Function Get-VMCSDDC { $orgID = $org.ID $sddcService = Get-VMCService com.vmware.vmc.orgs.sddcs if ($PSBoundParameters.ContainsKey("Name")){ - $sddcService.list($OrgID) | Where {$_.name -match $Name} + $sddcService.list($OrgID) | Where {$_.name -eq $Name} } Else { $sddcService.list($OrgID) } From 864a6446f0c311bdbe3a0ae7e5916d0ff5405b86 Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 19 Jun 2019 06:05:44 -0700 Subject: [PATCH 114/175] Add HCX Cloud Service functionality --- Modules/VMware.HCX/VMware.HCX.psd1 | 6 +- Modules/VMware.HCX/VMware.HCX.psm1 | 342 +++++++++++++++++++++++++++++ 2 files changed, 347 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psd1 b/Modules/VMware.HCX/VMware.HCX.psd1 index a5e74f0..e869f17 100644 --- a/Modules/VMware.HCX/VMware.HCX.psd1 +++ b/Modules/VMware.HCX/VMware.HCX.psd1 @@ -36,7 +36,11 @@ Description = 'PowerShell Module for Managing Hybrid Cloud Extension (HCX) on VM PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', 'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', 'Get-HcxRoleMapping', 'Set-HcxRoleMapping', 'Get-HcxProxy', 'Set-HcxProxy', 'Remove-HcxProxy' +FunctionsToExport = 'Connect-HcxServer', 'Get-HcxCloudConfig', 'Get-HcxEndpoint', 'New-HcxMigration', 'Get-HcxMigration', 'Connect-HcxVAMI', +'Get-HcxVCConfig', 'Set-HcxLicense', 'Set-HcxVCConfig', 'Get-HcxNSXConfig', 'Set-HcxNSXConfig', 'Get-HcxCity', 'Get-HcxLocation', 'Set-HcxLocation', +'Get-HcxRoleMapping', 'Set-HcxRoleMapping', 'Get-HcxProxy', 'Set-HcxProxy', 'Remove-HcxProxy', 'Connect-HcxCloudServer', 'Get-HCXCloudActivationKey', +'Get-HCXCloudSubscription', 'New-HCXCloudActivationKey', 'Get-HCXCloud', 'Set-HCXCloud' + # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index cfbe95b..85640ae 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -1306,4 +1306,346 @@ Function Remove-HcxProxy { Write-Warning "No proxy settings were configured" } } +} + +Function Connect-HcxCloudServer { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Connect to the HCX Cloud Service + .DESCRIPTION + This cmdlet connects to the HCX Cloud Service + .EXAMPLE + Connect-HcxCloudServer -RefreshToken +#> + Param ( + [Parameter(Mandatory=$true)][String]$RefreshToken, + [Switch]$Troubleshoot + ) + + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + if($results.StatusCode -ne 200) { + Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" + break + } + $accessToken = ($results | ConvertFrom-Json).access_token + + $payload = @{ + token = $accessToken; + } + $body = $payload | ConvertTo-Json + + $hcxCloudLoginUrl = "https://connect.hcx.vmware.com/provider/csp/api/sessions" + + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $hcxCloudLoginUrl -Body $body -Method POST -UseBasicParsing -ContentType "application/json" -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $hcxCloudLoginUrl -Body $body -Method POST -UseBasicParsing -ContentType "application/json" + } + + if($results.StatusCode -eq 200) { + $hcxAuthToken = $results.Headers.'x-hm-authorization' + + $headers = @{ + "x-hm-authorization"="$hcxAuthToken" + "Content-Type"="application/json" + "Accept"="application/json" + } + + $global:hcxCloudConnection = new-object PSObject -Property @{ + 'Server' = "https://connect.hcx.vmware.com/provider/csp/consumer/api"; + 'headers' = $headers + } + $global:hcxCloudConnection + } else { + Write-Error "Failed to connect to HCX Cloud Service, please verify your CSP Refresh Token is valid" + } +} + +Function Get-HCXCloudActivationKey { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the activation keys from HCX Cloud + .DESCRIPTION + This cmdlet returns the activation keys from HCX Cloud + .EXAMPLE + Get-HCXCloudActivationKeys + .EXAMPLE + Get-HCXCloudActivationKeys -Type [AVAILABLE|CONSUMED|DEACTIVATED|DELETED] +#> + Param ( + [Parameter(Mandatory=$false)][ValidateSet("AVAILABLE","CONSUMED","DEACTIVATED","DELETED")][String]$Type, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxCloudConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $method = "GET" + $hcxLicenseUrl = $global:hcxCloudConnection.Server + "/activationKeys" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$hcxLicenseUrl`n" + } + + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $hcxLicenseUrl -Method $method -Headers $global:hcxCloudConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $hcxLicenseUrl -Method $method -Headers $global:hcxCloudConnection.headers -UseBasicParsing + } + if($Type) { + ($results.content | ConvertFrom-Json).result.activationKeys | where { $_.status -eq $Type} + } else { + ($results.content | ConvertFrom-Json).result.activationKeys + } + } +} + +Function Get-HCXCloudSubscription { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns the subscription information for HCX CLoud Service + .DESCRIPTION + This cmdlet returns the subscription information for HCX Cloud Service + .EXAMPLE + Get-HCXCloudSubscription +#> + Param ( + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxCloudConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $method = "GET" + $hcxSubscriptionUrl = $global:hcxCloudConnection.Server + "/subscriptions" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$hcxSubscriptionUrl`n" + } + + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $hcxSubscriptionUrl -Method $method -Headers $global:hcxCloudConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $hcxSubscriptionUrl -Method $method -Headers $global:hcxCloudConnection.headers -UseBasicParsing + } + + ($results.content | ConvertFrom-Json).subscriptions | select @{Name = "SID"; Expression = {$_.sid}},@{Name = "STATUS"; Expression = {$_.status}},@{Name = 'OfferName'; Expression = {$_.subscriptionComponents.offerName}} + } +} + +Function New-HCXCloudActivationKey { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Requests new HCX Activation License Key + .DESCRIPTION + This cmdlet requests new HCX Activation License Key + .EXAMPLE + Get-HCXCloudActivationKey -SID -SystemType [HCX-CLOUD|HCX-ENTERPRISE] +#> + Param ( + [Parameter(Mandatory=$true)][String]$SID, + [Parameter(Mandatory=$true)][ValidateSet("HCX-CLOUD","HCX-ENTERPRISE")][String]$SystemType, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxCloudConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $method = "POST" + $hcxLicenseUrl = $global:hcxCloudConnection.Server + "/activationKeys" + + $payload = @{ + numberOfKeys = "1"; + sid = $SID; + systemType = ($SystemType).toLower(); + } + $body = $payload | ConvertTo-Json + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$hcxSubscriptionUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $hcxLicenseUrl -Method $method -Body $body -Headers $global:hcxCloudConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $hcxLicenseUrl -Method $method -Body $body -Headers $global:hcxCloudConnection.headers -UseBasicParsing + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe HCX Cloud session is no longer valid, please re-run the Connect-HCXCloudServer cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in requesting new HCX license key" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully requestd new $SystemType License Key" + ($requests.content | ConvertFrom-Json).activationKeys + } + } +} + +Function Get-HCXCloud { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns HCX deployment information for all SDDCs + .DESCRIPTION + This cmdlet returns HCX deployment information for all SDDCs + .EXAMPLE + Get-HCXCloud +#> + Param ( + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxCloudConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $method = "GET" + $hcxCloudSDDCUrl = $global:hcxCloudConnection.Server + "/sddcs" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$hcxSubscriptionUrl`n" + } + + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-WebRequest -Uri $hcxCloudSDDCUrl -Method $method -Headers $global:hcxCloudConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $results = Invoke-WebRequest -Uri $hcxCloudSDDCUrl -Method $method -Headers $global:hcxCloudConnection.headers -UseBasicParsing + } + + ($results.content | ConvertFrom-Json).sddcs | Sort-Object -Property Name | select @{Name = "SDDCName"; Expression = {$_.name}}, @{Name = "SDDCID"; Expression = {$_.id}}, @{Name = "HCXStatus"; Expression = {$_.activationStatus}}, @{Name = "Region"; Expression = {$_.region}} + } +} + +Function Set-HCXCloud { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 06/19/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Activate or Deactivate HCX for given VMC SDDC + .DESCRIPTION + This cmdlet activates or deactivates HCX for given VMC SDDC + .EXAMPLE + Set-HCXCloud -Activate -SDDCID $SDDCID + .EXAMPLE + Set-HCXCloud -Deactivate -SDDCID $SDDCID +#> + Param ( + [Parameter(Mandatory=$true)][String]$SDDCID, + [Switch]$Activate, + [Switch]$Deactivate, + [Switch]$Troubleshoot + ) + + If (-Not $global:hcxCloudConnection) { Write-error "HCX Auth Token not found, please run Connect-HcxVAMI " } Else { + $method = "POST" + + if($Activate) { + $HcxSid = (Get-HCXCloudSubscription | where {$_.STATUS -eq "ACTIVE"}).SID + + # Check to see if there is an available HCX-Cloud Key + $HcxKey = ((Get-HCXCloudActivationKeys -Type AVAILABLE | where {$_.systemType -eq 'hcx-cloud'}) | select -First 1).activationKey + if($HcxKey -eq $null) { + $HcxKey = New-HCXCloudActivationKey -SID $HcxSid -SystemType HCX-CLOUD + } + + if($HCXKey -eq $null -or $HcxSid -eq $null) { + Write-Error "Failed to retrieve HCX Subscription ID or request HCX Cloud License Key" + break + } + + $hcxSDDCUrl = $global:hcxCloudConnection.Server + "/sddcs/$($SDDCID)?action=activate" + + $payload = @{ + activationKey = $HcxKey; + } + } else { + $payload = "" + + $hcxSDDCUrl = $global:hcxCloudConnection.Server + "/sddcs/$($SDDCID)?action=deactivate" + } + + $body = $payload | ConvertTo-Json + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $METHOD`n$hcxSDDCUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $hcxSDDCUrl -Method $method -Body $body -Headers $global:hcxCloudConnection.headers -UseBasicParsing -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $hcxSDDCUrl -Method $method -Body $body -Headers $global:hcxCloudConnection.headers -UseBasicParsing + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe HCX Cloud session is no longer valid, please re-run the Connect-HCXCloudServer cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in attempting to activate or deactivate HCX" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + if($Activate) { + Write-Host "Activating HCX for SDDC: $SDDCID, starting deployment. You can monitor the status using the HCX Cloud Console" + } else { + Write-Host "Deactivating HCX for SDDC: $SDDCID, starting un-deploymentt. You can monitor the status using the HCX Cloud Console" + } + ($requests.content | ConvertFrom-Json) + } + } } \ No newline at end of file From 723acfd8116f688cfb24134bc1f23d09afa181e4 Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 25 Jun 2019 05:43:05 -0700 Subject: [PATCH 115/175] Fixing typo in function name --- Modules/VMware.HCX/VMware.HCX.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index 781e0fe..9bfcc18 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -1645,7 +1645,7 @@ Function Set-HCXCloud { $HcxSid = (Get-HCXCloudSubscription | where {$_.STATUS -eq "ACTIVE"}).SID # Check to see if there is an available HCX-Cloud Key - $HcxKey = ((Get-HCXCloudActivationKeys -Type AVAILABLE | where {$_.systemType -eq 'hcx-cloud'}) | select -First 1).activationKey + $HcxKey = ((Get-HCXCloudActivationKey -Type AVAILABLE | where {$_.systemType -eq 'hcx-cloud'}) | select -First 1).activationKey if($HcxKey -eq $null) { $HcxKey = New-HCXCloudActivationKey -SID $HcxSid -SystemType HCX-CLOUD } From 823e150ef7d3866b0867d397491d9e45fed5600f Mon Sep 17 00:00:00 2001 From: William Lam Date: Mon, 1 Jul 2019 05:41:13 -0700 Subject: [PATCH 116/175] Add {Get,Set,Remove} functions for Public IP & NAT --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 | 7 +- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 310 ++++++++++++++++++- 2 files changed, 302 insertions(+), 15 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 index 1b97cd3..46e5fb2 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psd1 @@ -37,12 +37,13 @@ PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = 'Connect-NSXTProxy', 'Get-NSXTSegment', 'New-NSXTSegment', 'Remove-NSXTSegment', ` -'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTService', 'New-NSXTService', ` +'Get-NSXTGroup', 'New-NSXTGroup', 'Remove-NSXTGroup', 'Get-NSXTServiceDefinition', 'New-NSXTServiceDefinition', ` 'Get-NSXTFirewall', 'New-NSXTFirewall', 'Remove-NSXTFirewall', 'Get-NSXTDistFirewallSection', ` 'Get-NSXTDistFirewall', 'New-NSXTDistFirewall', 'Remove-NSXTDistFirewall', 'Get-NSXTRouteTable', ` 'Get-NSXTOverviewInfo', 'Get-NSXTInfraScope', 'Get-NSXTInfraGroup', 'New-NSXTRouteBasedVPN', ` -'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN', 'Remove-NSXTService', 'New-NSXTDistFirewallSection', 'Get-NSXTDistFirewallSection', ` -'New-NSXTPolicyBasedVPN', 'Get-NSXTPolicyBasedVPN', 'Remove-NSXTPolicyBasedVPN', 'Get-NSXTDNS', 'Set-NSXTDNS' +'Get-NSXTRouteBasedVPN', 'Remove-NSXTRouteBasedVPN', 'Remove-NSXTServiceDefinition', 'New-NSXTDistFirewallSection', 'Get-NSXTDistFirewallSection', ` +'New-NSXTPolicyBasedVPN', 'Get-NSXTPolicyBasedVPN', 'Remove-NSXTPolicyBasedVPN', 'Get-NSXTDNS', 'Set-NSXTDNS', 'Get-NSXTPublicIP', 'New-NSXTPublicIP', ` +'Get-NSXTNatRule', 'New-NSXTNatRule', 'Remove-NSXTNatRule' # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 5004034..ba199f6 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -520,7 +520,7 @@ Function New-NSXTFirewall { if($serviceName -eq "ANY") { $services = @("ANY") } else { - $tmp = (Get-NSXTService -Name "$serviceName").Path + $tmp = (Get-NSXTServiceDefinition -Name "$serviceName").Path $services+=$tmp } } @@ -854,7 +854,7 @@ Function Remove-NSXTGroup { } } -Function Get-NSXTService { +Function Get-NSXTServiceDefinition { <# .NOTES =========================================================================== @@ -870,9 +870,9 @@ Function Get-NSXTService { .DESCRIPTION This cmdlet retrieves all NSX-T Services .EXAMPLE - Get-NSXTService + Get-NSXTServiceDefinition .EXAMPLE - Get-NSXTService -Name "WINS" + Get-NSXTServiceDefinition -Name "WINS" #> param( [Parameter(Mandatory=$false)][String]$Name, @@ -933,7 +933,7 @@ Function Get-NSXTService { } } -Function Remove-NSXTService { +Function Remove-NSXTServiceDefinition { <# .NOTES =========================================================================== @@ -949,7 +949,7 @@ Function Remove-NSXTService { .DESCRIPTION This cmdlet removes an NSX-T Service .EXAMPLE - Remove-NSXTService -Id VMware-Blast -Troubleshoot + Remove-NSXTServiceDefinition -Id VMware-Blast -Troubleshoot #> Param ( [Parameter(Mandatory=$True)]$Id, @@ -987,7 +987,7 @@ Function Remove-NSXTService { } } -Function New-NSXTService { +Function New-NSXTServiceDefinition { <# .NOTES =========================================================================== @@ -1003,7 +1003,7 @@ Function New-NSXTService { .DESCRIPTION This cmdlet creates a new NSX-T Service .EXAMPLE - New-NSXTService -Name "MyHTTP2" -Protocol TCP -DestinationPorts @("8080","8081") + New-NSXTServiceDefinition -Name "MyHTTP2" -Protocol TCP -DestinationPorts @("8080","8081") #> Param ( [Parameter(Mandatory=$True)]$Name, @@ -2571,16 +2571,17 @@ Function Set-NSXTDNS { $method = "PATCH" $dnsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/dns-forwarder-zones/$($GatewayType.toLower())-dns-zone" - if($Troubleshoot) { - Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$dnsURL`n" - } - $payload = @{ upstream_servers = @($DNS) } $body = $payload | ConvertTo-Json -Depth 5 + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$dnsURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + try { if($PSVersionTable.PSEdition -eq "Core") { $requests = Invoke-WebRequest -Uri $dnsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck @@ -2602,4 +2603,289 @@ Function Set-NSXTDNS { Write-Host "Successfully updated NSX-T DNS for $GatewayType" } } +} + +Function Get-NSXTPublicIP { + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $publicIPURL = ($global:nsxtProxyConnection.Server).replace("/sks-nsxt-manager","") + "/cloud-service/api/v1/infra/public-ips" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$publicIPURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $publicIPURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $publicIPURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Public IPs" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $results = ($requests.Content | ConvertFrom-Json).results | select display_name,id,ip + + if ($PSBoundParameters.ContainsKey("Name")){ + $results | where {$_.display_name -eq $Name} + } else { + $results + } + } + } +} + +Function New-NSXTPublicIP { + Param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "PUT" + $publicIPURL = ($global:nsxtProxyConnection.Server).replace("/sks-nsxt-manager","") + "/cloud-service/api/v1/infra/public-ips/$($Name)" + + $payload = @{ + display_name = "$Name"; + } + + $body = $payload | ConvertTo-Json + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$publicIPURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $publicIPURL -Method $method -Body $body -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $publicIPURL -Method $method -Body $body -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Public IPs" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully requested new NSX-T Public IP Address" + ($requests.Content | ConvertFrom-Json) | select display_name,id,ip + } + } +} + +Function Remove-NSXTPublicIP { + Param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "DELETE" + $publicIPURL = ($global:nsxtProxyConnection.Server).replace("/sks-nsxt-manager","") + "/cloud-service/api/v1/infra/public-ips/$($Name)" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$publicIPURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $publicIPURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $publicIPURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in deleting NSX-T Public IPs" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully deleted NSX-T Public IP Address $Name" + } + } +} + +Function Get-NSXTNatRule { + param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "GET" + $natURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/nat/USER/nat-rules" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$natURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $natURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $natURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving NSX-T Public IPs" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + $results = ($requests.Content | ConvertFrom-Json).results | select id,display_name,sequence_number,source_network,translated_network,destination_network,translated_ports,service,scope + + if ($PSBoundParameters.ContainsKey("Name")){ + $results | where {$_.display_name -eq $Name} + } else { + $results + } + } + } +} + +Function New-NSXTNatRule { + Param( + [Parameter(Mandatory=$true)][String]$Name, + [Parameter(Mandatory=$true)][String]$PublicIP, + [Parameter(Mandatory=$true)][String]$InternalIP, + [Parameter(Mandatory=$true)][String]$Service, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $method = "PUT" + $natURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/nat/USER/nat-rules/$($Name)" + + if($service -eq "ANY") { + $payload = @{ + display_name = $Name; + action = "REFLEXIVE"; + service = ""; + translated_network = $PublicIP; + source_network = $InternalIP; + scope = @("/infra/labels/cgw-public"); + firewall_match = "MATCH_INTERNAL_ADDRESS"; + logging = $false; + enabled = $true; + sequence_number = 0; + } + } else { + $nsxtService = Get-NSXTServiceDefinition -Name $Service + $servicePath = $nsxtService.path + $servicePort = $nsxtService.Destination + + $payload = @{ + display_name = $Name; + action = "DNAT"; + service = $servicePath; + translated_network = $InternalIP; + translated_ports = $servicePort; + destination_network = $PublicIP + scope = @("/infra/labels/cgw-public"); + firewall_match = "MATCH_EXTERNAL_ADDRESS"; + logging = $false; + enabled = $true; + sequence_number = 0; + } + } + + $body = $payload | ConvertTo-Json -Depth 5 + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$natURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $natURL -Method $method -Body $body -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $natURL -Method $method -Body $body -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating NSX-T NAT Rule" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully create new NAT Rule" + ($requests.Content | ConvertFrom-Json) | select id,display_name,sequence_number,source_network,translated_network,destination_network,translated_ports,service,scope + } + } +} + +Function Remove-NSXTNatRule { + Param( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + + $natRuleId = (Get-NSXTNatRule -Name $Name).id + + $method = "DELETE" + $natURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/nat/USER/nat-rules/$($natRuleId)" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$natURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $natURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $natURL -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in deleting NSX-T NAT Rule" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully deleted NAT Rule $Name" + } + } } \ No newline at end of file From 98545615912c5fcb9168c4ebc794badf48386d18 Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 9 Jul 2019 06:42:41 -0700 Subject: [PATCH 117/175] Fixing DFW URL --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index ba199f6..c356098 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1160,7 +1160,7 @@ Function Get-NSXTDistFirewallSection { if($PSVersionTable.PSEdition -eq "Core") { $requests = Invoke-WebRequest -Uri $distFirewallSectionURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck } else { - $requests = Invoke-WebRequest -Uri $distFirdistFirewallSectionURLwallURL -Method $method -Headers $global:nsxtProxyConnection.headers + $requests = Invoke-WebRequest -Uri $distFirdistFirewallSectionURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { if($_.Exception.Response.StatusCode -eq "Unauthorized") { From 0887967dc3efc22f3d5910d09d23fc06038d37c1 Mon Sep 17 00:00:00 2001 From: William Lam Date: Tue, 9 Jul 2019 06:44:12 -0700 Subject: [PATCH 118/175] Actually fixing DFW URL :X --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index c356098..b8c9c9a 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1160,7 +1160,7 @@ Function Get-NSXTDistFirewallSection { if($PSVersionTable.PSEdition -eq "Core") { $requests = Invoke-WebRequest -Uri $distFirewallSectionURL -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck } else { - $requests = Invoke-WebRequest -Uri $distFirdistFirewallSectionURL -Method $method -Headers $global:nsxtProxyConnection.headers + $requests = Invoke-WebRequest -Uri $distFirewallSectionURL -Method $method -Headers $global:nsxtProxyConnection.headers } } catch { if($_.Exception.Response.StatusCode -eq "Unauthorized") { From 4436510b02d14a30c3a52184d34e7fe31920765f Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Tue, 30 Jul 2019 16:33:31 -0500 Subject: [PATCH 119/175] Additional EntityID Type, and fixes --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 52 ++++++++++++++----- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index a73fc56..c81ab42 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -213,6 +213,8 @@ function Get-HVvCenterServerHealth { begin { $services = Get-ViewAPIService -hvServer $hvServer + Write-Warning "Get-HvVcenterServerHealth is targeted for deprecation in a future release. Use Get-HVHealth -Servicename VirtualCenter instead." + if ($null -eq $services) { Write-Error "Could not retrieve ViewApi services from connection object" break @@ -8019,6 +8021,10 @@ function Get-HVInternalName { $info = $services.ViewComposerDomainAdministrator.ViewComposerDomainAdministrator_Get($AdministratorId) return $info.base.userName } + 'GlobalApplicationEntitlement' { + $info = $services.GlobalApplicationEntitlement.GlobalApplicationEntitlement_Get($EntityId) + return $info.Base.displayName + } default { $base64String = $tokens[$tokens.Length-1] $mod = $base64String.Length % 4 @@ -10567,7 +10573,7 @@ $bye = $machineService.Machine_DeleteMachines($services,$deleteMachine.id,$delet } -function get-hvhealth { +function Get-HVHealth { <# .Synopsis Pulls health information from Horizon View @@ -10577,7 +10583,7 @@ function get-hvhealth { .PARAMETER Servicename The name of the service to query the health for. - This will default to Connection server health. + This will default to Connection server health. Available services are ADDomain,CertificateSSOConnector,ConnectionServer,EventDatabase,SAMLAuthenticator,SecurityServer,ViewComposer,VirtualCenter,Pod .PARAMETER HvServer @@ -10585,12 +10591,12 @@ function get-hvhealth { first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE - get-hvhealth -service connectionserver + Get-HVHealth -service connectionserver Returns health for the connectionserver(s) .EXAMPLE - get-hvhealth -service ViewComposer + Get-HVHealth -service ViewComposer Returns health for the View composer server(s) .NOTES @@ -12011,9 +12017,13 @@ Function Get-HVApplication { return $ResourceObjs } $ResourceObjs = Get-HVQueryResult -EntityType ApplicationInfo -HvServer $HvServer - if ($FormatList -eq $True){ return $ResourceObjs.data | Format-Table -AutoSize} - return $ResourceObjs.data + if ($FormatList -eq $True){ + return $ResourceObjs.data | Format-Table -AutoSize + } else { + return $ResourceObjs } + + } end { [System.GC]::Collect() } @@ -12085,10 +12095,10 @@ Function Remove-HVApplication { Function New-HVManualApplication { <# .Synopsis - Creates a Manual Application. + Creates a Manual Application. .DESCRIPTION - Creates Application manually with given parameters. + Creates Application manually with given parameters. .PARAMETER HvServer View API service object of Connect-HVServer cmdlet. @@ -12150,9 +12160,12 @@ Function New-HVManualApplication { .PARAMETER AutoUpdateOtherFileTypes Whether or not the other file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. +.PARAMETER GlobalApplicationEntitlement + Specify the Display Name of a Global Application Entitlement to add this Application Pool to. + .EXAMPLE - New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' - Creates a manual application App1 in the farm specified. + New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' + Creates a manual application App1 in the farm specified. .OUTPUTS A success message is displayed when done. @@ -12230,7 +12243,10 @@ Function New-HVManualApplication { [Boolean]$AutoUpdateFileTypes = $True, [Parameter(Mandatory = $False, ValueFromPipeline = $True)] - [Boolean]$AutoUpdateOtherFileTypes = $True + [Boolean]$AutoUpdateOtherFileTypes = $True, + + [Parameter(Mandatory = $False)] + [String]$GlobalApplicationEntitlement = $null ) begin { $services = Get-ViewAPIService -HvServer $HvServer @@ -12243,6 +12259,13 @@ Function New-HVManualApplication { Write-Error "Could not find the specified Farm." break } + if ( $PSBoundParameters.ContainsKey('GlobalApplicationEntitlement') ) { + $GlobalApplicationEntitlementInfo = Get-HVGlobalEntitlement -DisplayName $GlobalApplicationEntitlement + $GlobalApplicationEntitlementId = $GlobalApplicationEntitlementInfo.Id + } else { + $GlobalApplicationEntitlementId = $null + } + } process { $App = Get-HVApplication -ApplicationName $Name -HvServer $HvServer @@ -12250,9 +12273,9 @@ Function New-HVManualApplication { Write-Host "Application already exists with the name : $Name" return } - $AppData = New-Object VMware.Hv.ApplicationData -Property @{ 'Name' = $Name; 'DisplayName' = $DisplayName; 'Description' = $Description; 'Enabled' = $Enabled; 'EnableAntiAffinityRules' = $EnableAntiAffinityRules; 'AntiAffinityPatterns' = $AntiAffinityPatterns; 'AntiAffinityCount' = $AntiAffinityCount; 'EnablePreLaunch' = $EnablePreLaunch; 'multiSessionMode' = $MultiSessionMode; 'maxMultiSessions' = $MaxMultiSessions; 'ConnectionServerRestrictions' = $ConnectionServerRestrictions; 'CategoryFolderName' = $CategoryFolderName; 'ClientRestrictions' = $ClientRestrictions; 'ShortcutLocations' = $ShortcutLocations} - $ExecutionData = New-object VMware.Hv.ApplicationExecutionData -Property @{ 'ExecutablePath' = $ExecutablePath; 'Version' = $Version; 'Publisher' = $Publisher; 'StartFolder' = $StartFolder; 'Args' = $Args; 'Farm' = $FarmInfo.id; 'AutoUpdateFileTypes' = $AutoUpdateFileTypes; 'AutoUpdateOtherFileTypes' = $AutoUpdateOtherFileTypes} - $AppSpec = New-Object VMware.Hv.ApplicationSpec -Property @{ 'Data' = $AppData; 'ExecutionData' = $ExecutionData} + $AppData = New-Object VMware.Hv.ApplicationData -Property @{ 'name' = $Name; 'displayName' = $DisplayName; 'description' = $Description; 'enabled' = $Enabled; 'enableAntiAffinityRules' = $EnableAntiAffinityRules; 'antiAffinityPatterns' = $AntiAffinityPatterns; 'antiAffinityCount' = $AntiAffinityCount; 'enablePreLaunch' = $EnablePreLaunch; 'connectionServerRestrictions' = $ConnectionServerRestrictions; 'categoryFolderName' = $CategoryFolderName; 'clientRestrictions' = $ClientRestrictions; 'shortcutLocations' = $ShortcutLocations; 'globalApplicationEntitlement' = $GlobalApplicationEntitlementId } + $ExecutionData = New-Object VMware.Hv.ApplicationExecutionData -Property @{ 'executablePath' = $ExecutablePath; 'version' = $Version; 'publisher' = $Publisher; 'startFolder' = $StartFolder; 'args' = $Args; 'farm' = $FarmInfo.id; 'autoUpdateFileTypes' = $AutoUpdateFileTypes; 'autoUpdateOtherFileTypes' = $AutoUpdateOtherFileTypes} + $AppSpec = New-Object VMware.Hv.ApplicationSpec -Property @{ 'data' = $AppData; 'executionData' = $ExecutionData} $AppService = New-Object VMware.Hv.ApplicationService $AppService.Application_Create($services,$AppSpec) if ($?) { @@ -12260,6 +12283,7 @@ Function New-HVManualApplication { return } Write-Host "Application creation of '$Name' has failed. $_" + Return $AppSpec } end { [System.GC]::Collect() From 4badbe5ff528a9292ae39b78ff652970f86a8b5d Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Tue, 30 Jul 2019 16:34:02 -0500 Subject: [PATCH 120/175] New-HVManualApplication fixes --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 1 - 1 file changed, 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index c81ab42..5b502a3 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -12283,7 +12283,6 @@ Function New-HVManualApplication { return } Write-Host "Application creation of '$Name' has failed. $_" - Return $AppSpec } end { [System.GC]::Collect() From 10647481f173dc0941538a6dca40b042043dbf5a Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Fri, 2 Aug 2019 16:09:15 -0500 Subject: [PATCH 121/175] Added Set-HVApplication to update ApplicationInfo --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 238 +++++++++++++++++- 1 file changed, 236 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 5b502a3..071af67 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -12161,7 +12161,7 @@ Function New-HVManualApplication { Whether or not the other file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. .PARAMETER GlobalApplicationEntitlement - Specify the Display Name of a Global Application Entitlement to add this Application Pool to. + The name of a Global Application Entitlement to associate this Application pool with. .EXAMPLE New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' @@ -12497,6 +12497,240 @@ Function New-HVPreInstalledApplication { } } +function Set-HVApplication { +<# +.Synopsis + Updates settings for an existing Application Pool. + +.DESCRIPTION + Updates settings for an existing Application Pool. It does not update the Application Icon. See Set-HVApplicationIcon for a function to update icons. This function specifically targets ApplicationInfo.Data and Application.ExecutionData properties. + +.PARAMETER HvServer + View API service object of Connect-HVServer cmdlet. + +.PARAMETER Name + The Application name is the unique identifier used to identify this Application. This cannot be updated but is used to specify which application should be updated. + +.PARAMETER DisplayName + The display name is the name that users will see when they connect to view client. If the display name is left blank, it defaults to Name. + +.PARAMETER Description + The description is a set of notes about the Application. + +.PARAMETER GlobalApplicationEntitlement + The name of a Global Application Entitlement to associate this Application pool with. + +.PARAMETER ExecutablePath + Path to Application executable. + +.PARAMETER Version + Application version. + +.PARAMETER Publisher + Application publisher. + +.PARAMETER Enabled + Indicates if Application is enabled. + +.PARAMETER EnablePreLaunch + Application can be pre-launched if value is true. + +.PARAMETER ConnectionServerRestrictions + Connection server restrictions. This is a list of tags that access to the application is restricted to. Empty/Null list means that the application can be accessed from any connection server. + +.PARAMETER CategoryFolderName + Name of the category folder in the user's OS containing a shortcut to the application. Unset if the application does not belong to a category. + +.PARAMETER ClientRestrictions + Client restrictions to be applied to Application. Currently it is valid for RDSH pools. + +.PARAMETER ShortcutLocations + Locations of the category folder in the user's OS containing a shortcut to the desktop. The value must be set if categoryFolderName is provided. + +.PARAMETER StartFolder + Starting folder for Application. + +.PARAMETER Args + Parameters to pass to application when launching. + +.PARAMETER Farm + Farm name. + +.PARAMETER AutoUpdateFileTypes + Whether or not the file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +.PARAMETER AutoUpdateOtherFileTypes + Whether or not the other file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +.PARAMETER GlobalApplicationEntitlement + Specify the Display Name of a Global Application Entitlement to add this Application Pool to. + +.EXAMPLE + New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' + Creates a manual application App1 in the farm specified. + +.OUTPUTS + A success message is displayed when done. + +.NOTES + Author : Matt Frey + Author email : mfrey@vmware.com + Version : 1.0 + + ===Tested Against Environment==== + Horizon View Server Version : 7.8.0 + PowerCLI Version : PowerCLI 11.1 + PowerShell Version : 5.1 +#> +param ( + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [VMware.VimAutomation.HorizonView.Impl.V1.ViewServerImpl]$HvServer, + + [Parameter(Mandatory = $True, ValueFromPipeline = $True, Position = 0)] + [string][ValidateLength(1,64)]$Name, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String][ValidateLength(1,256)]$DisplayName = $Name, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String][ValidateLength(1,1024)]$Description, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$ExecutablePath, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$Version, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$Publisher, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$Enabled = $True, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$EnablePreLaunch=$False, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [string[]]$ConnectionServerRestrictions, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True, ParameterSetName = 'categoryFolderName')] + [String][ValidateRange(1,64)]$CategoryFolderName, + + #Below Parameter is for Client restrictions to be applied to Application. Currently it is valid for RDSH pools. + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$clientRestrictions = $False, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True, ParameterSetName = 'categoryFolderName')] + [String[]]$ShortcutLocations, + + #Below parameters are for ExecutionData, moved ExecutablePath, Version and Publisher to above from this. + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$StartFolder, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [String]$Args, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$AutoUpdateFileTypes = $True, + + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [Boolean]$AutoUpdateOtherFileTypes = $True, + + [Parameter(Mandatory = $False)] + [String]$GlobalApplicationEntitlement = $null +) + begin { + $services = Get-ViewAPIService -HvServer $HvServer + if ($null -eq $services) { + Write-Error "Could not retrieve View API services from connection object" + break + } + } + process { + $App = Get-HVApplication -ApplicationName $Name -HvServer $HvServer + if (!$App) { + Write-Error "Application $App not found. Please check the syntax or spelling." + return + } + + $updates = @() + if ($PSBoundParameters.ContainsKey("DisplayName")) { + $updates += Get-MapEntry -key 'data.displayName' -value $DisplayName + } + if ($PSBoundParameters.ContainsKey("Description")) { + $updates += Get-MapEntry -key 'data.description' -value $Description + } + if ($PSBoundParameters.ContainsKey("Enabled")) { + $updates += Get-MapEntry -key 'data.enabled' -value $Enabled + } + if ($PSBoundParameters.ContainsKey("EnableAntiAffinityRules")) { + $updates += Get-MapEntry -key 'data.enableAntiAffinityRules' -value $EnableAntiAffinityRules + } + if ($PSBoundParameters.ContainsKey("EnableAntiAffinityPatterns")) { + $updates += Get-MapEntry -key 'data.enableAntiAffinityPatterns' -value $EnableAntiAffinityPatterns + } + if ($PSBoundParameters.ContainsKey("EnableAntiAffinityCount")) { + $updates += Get-MapEntry -key 'data.enableAntiAffinityCount' -value $EnableAntiAffinityCount + } + if ($PSBoundParameters.ContainsKey("EnablePreLaunch")) { + $updates += Get-MapEntry -key 'data.enablePreLaunch' -value $EnablePreLaunch + } + if ($PSBoundParameters.ContainsKey("ConnectionServerRestrictions")) { + $updates += Get-MapEntry -key 'data.connectionServerRestrictions' -value $ConnectionServerRestrictions + } + if ($PSBoundParameters.ContainsKey("EnableAntiAffinityRules")) { + $updates += Get-MapEntry -key 'data.enableAntiAffinityRules' -value $EnableAntiAffinityRules + } + if ($PSBoundParameters.ContainsKey("CategoryFolderName")) { + $updates += Get-MapEntry -key 'data.categoryFolderName' -value $CategoryFolderName + } + if ($PSBoundParameters.ContainsKey("ClientRestrictions")) { + $updates += Get-MapEntry -key 'data.clientRestrictions' -value $ClientRestrictions + } + if ($PSBoundParameters.ContainsKey("ShortcutLocations")) { + $updates += Get-MapEntry -key 'data.shortcutLocations' -value $ShortcutLocations + } + if ($PSBoundParameters.ContainsKey("GlobalApplicationEntitlement")) { + $GlobalApplicationEntitlementInfo = Get-HVGlobalEntitlement -DisplayName $GlobalApplicationEntitlement + $GlobalApplicationEntitlementId = $GlobalApplicationEntitlementInfo.Id + $updates += Get-MapEntry -key 'data.globalApplicationEntitlement' -value $GlobalApplicationEntitlementId + } + + if ($PSBoundParameters.ContainsKey("ExecutablePath")) { + $updates += Get-MapEntry -key 'executionData.executablePath' -value $ExecutablePath + } + if ($PSBoundParameters.ContainsKey("Version")) { + $updates += Get-MapEntry -key 'executionData.version' -value $Version + } + if ($PSBoundParameters.ContainsKey("Publisher")) { + $updates += Get-MapEntry -key 'executionData.publisher' -value $Publisher + } + if ($PSBoundParameters.ContainsKey("StartFolder")) { + $updates += Get-MapEntry -key 'executionData.startFolder' -value $StartFolder + } + if ($PSBoundParameters.ContainsKey("Args")) { + $updates += Get-MapEntry -key 'executionData.args' -value $Args + } + if ($PSBoundParameters.ContainsKey("AutoUpdateFileTypes")) { + $updates += Get-MapEntry -key 'executionData.autoUpdateFileTypes' -value $AutoUpdateFileTypes + } + if ($PSBoundParameters.ContainsKey("AutoUpdateOtherFileTypes")) { + $updates += Get-MapEntry -key 'executionData.autoUpdateOtherFileTypes' -value $AutoUpdateOtherFileTypes + } + + $AppService = New-Object VMware.Hv.ApplicationService + $AppService.Application_Update($services,$App.Id,$updates) + if ($?) { + Write-Host "Application '$Name' updated successfully" + return + } + Write-Host "Application update to '$Name' has failed. $_" + } + end { + [System.GC]::Collect() + } +} + # Object related Export-ModuleMember -Function Get-HVMachine, Get-HVMachineSummary, Get-HVQueryResult, Get-HVQueryFilter, Get-HVInternalName # RDS Farm related @@ -12504,7 +12738,7 @@ Export-ModuleMember -Function Get-HVFarmSummary, Start-HVFarm, Start-HVPool, New # Desktop Pool related Export-ModuleMember -Function Get-HVPoolSummary, New-HVPool, Remove-HVPool, Get-HVPool, Set-HVPool, Get-HVPoolSpec, Add-HVDesktop # Application Pool related -Export-ModuleMember -Function Get-HVApplication, Remove-HVApplication, New-HVManualApplication, Get-HVPreInstalledApplication, New-HVPreInstalledApplication +Export-ModuleMember -Function Get-HVApplication, Remove-HVApplication, New-HVManualApplication, Get-HVPreInstalledApplication, New-HVPreInstalledApplication, Set-HVApplication # Entitlement related Export-ModuleMember -Function New-HVEntitlement,Get-HVEntitlement,Remove-HVEntitlement Export-ModuleMember -Function Set-HVMachine, Reset-HVMachine, Remove-HVMachine From 5f6294cf6744880cea834fcfe87e910b86ce6415 Mon Sep 17 00:00:00 2001 From: seanpmassey Date: Mon, 5 Aug 2019 01:16:33 -0500 Subject: [PATCH 122/175] Update VMware.VMC.psm1 Add switch to Connect-VMCVIServer to allow the use of the management IP Address instead of the Public IP address. This would be used when the DNS resolution for the VMC vCenter is set to the private IP. --- Modules/VMware.VMC/VMware.VMC.psm1 | 945 +++-------------------------- 1 file changed, 94 insertions(+), 851 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index 88eaa28..91b7cff 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -47,15 +47,22 @@ Function Connect-VMCVIServer { Param ( [Parameter(Mandatory=$true)]$Org, [Parameter(Mandatory=$true)]$Sddc, - [switch]$Autologin + [switch]$Autologin, + [switch]$UseManagementIP ) If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { $creds = Get-VMCSDDCDefaultCredential -Org $Org -Sddc $Sddc - Write-Host "Connecting to VMC vCenter Server" $creds.vc_public_ip - Connect-VIServer -Server $creds.vc_public_ip -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" - Write-Host "Connecting to VMC CIS Endpoint" $creds.vc_public_ip - Connect-CisServer -Server $creds.vc_public_ip -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" + If($UseManagementIP){ + $Server = $creds.vc_management_ip + }Else{ + $Server = $creds.vc_public_ip + } + + Write-Host "Connecting to VMC vCenter Server" $Server + Connect-VIServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" + Write-Host "Connecting to VMC CIS Endpoint" $Server + Connect-CisServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" } } Function Get-VMCOrg { @@ -81,13 +88,13 @@ Function Get-VMCOrg { Return all the info about the orgs you are a part of #> Param ( - [Parameter(Mandatory=$false)]$Name + [Parameter(Mandatory=$false)]$Name ) If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use Connect-VMC to connect" } Else { $orgService = Get-VMCService com.vmware.vmc.orgs if ($PSBoundParameters.ContainsKey("Name")){ - $orgs = $orgService.list() | Where {$_.display_name -eq $Name} + $orgs = $orgService.list() | Where {$_.display_name -match $Name} } Else { $orgs = $orgService.list() } @@ -130,7 +137,7 @@ Function Get-VMCSDDC { $orgID = $org.ID $sddcService = Get-VMCService com.vmware.vmc.orgs.sddcs if ($PSBoundParameters.ContainsKey("Name")){ - $sddcService.list($OrgID) | Where {$_.name -eq $Name} + $sddcService.list($OrgID) | Where {$_.name -match $Name} } Else { $sddcService.list($OrgID) } @@ -320,6 +327,7 @@ Function Get-VMCSDDCVersion { } } } + Function Get-VMCFirewallRule { <# .NOTES @@ -393,8 +401,9 @@ Function Get-VMCFirewallRule { } $results } -Function Export-VMCFirewallRule { -<# + + Function Export-VMCFirewallRule { + <# .NOTES =========================================================================== Created by: William Lam @@ -411,45 +420,45 @@ Function Export-VMCFirewallRule { .EXAMPLE Export-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" #> - param( + param( [Parameter(Mandatory=$false)][String]$SDDCName, [Parameter(Mandatory=$false)][String]$OrgName, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$false)][String]$Path ) - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - if($GatewayType -eq "MGW") { + if($GatewayType -eq "MGW") { $EdgeId = "edge-1" } else { $EdgeId = "edge-2" } - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - if(-not $orgId) { + if(-not $orgId) { Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" break } - if(-not $sddcId) { + if(-not $sddcId) { Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" break } - $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config + $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config - $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules - if(-not $ShowAll) { + $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules + if(-not $ShowAll) { $firewallRules = $firewallRules | where { $_.rule_type -ne "default_policy" -and $_.rule_type -ne "internal_high" -and $_.name -ne "vSphere Cluster HA" -and $_.name -ne "Outbound Access" } | Sort-Object -Property rule_tag } else { $firewallRules = $firewallRules | Sort-Object -Property rule_tag } - $results = @() - $count = 0 - foreach ($firewallRule in $firewallRules) { + $results = @() + $count = 0 + foreach ($firewallRule in $firewallRules) { if($firewallRule.source.ip_address.Count -ne 0) { $source = $firewallRule.source.ip_address } else { @@ -471,15 +480,16 @@ Function Export-VMCFirewallRule { $count+=1 $results+=$tmp } - if($Path) { + if($Path) { Write-Host -ForegroundColor Green "Exporting $count VMC Firewall Rules to $Path ..." $results | ConvertTo-Json | Out-File $Path } else { $results | ConvertTo-Json } -} -Function Import-VMCFirewallRule { -<# + } + + Function Import-VMCFirewallRule { + <# .NOTES =========================================================================== Created by: William Lam @@ -496,43 +506,43 @@ Function Import-VMCFirewallRule { .EXAMPLE Import-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" #> - param( + param( [Parameter(Mandatory=$false)][String]$SDDCName, [Parameter(Mandatory=$false)][String]$OrgName, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$false)][String]$Path ) - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - if($GatewayType -eq "MGW") { + if($GatewayType -eq "MGW") { $EdgeId = "edge-1" } else { $EdgeId = "edge-2" } - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - if(-not $orgId) { + if(-not $orgId) { Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" break } - if(-not $sddcId) { + if(-not $sddcId) { Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" break } - $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules - $vmcFirewallRulesJSON = Get-Content -Raw $Path | ConvertFrom-Json + $vmcFirewallRulesJSON = Get-Content -Raw $Path | ConvertFrom-Json - # Create top level Firewall Rules Object - $firewallRules = $firewallService.Help.add.firewall_rules.Create() - # Create top top level Firewall Rule Spec which will be an array of individual Firewall rules as we process them in next section - $ruleSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Create() + # Create top level Firewall Rules Object + $firewallRules = $firewallService.Help.add.firewall_rules.Create() + # Create top top level Firewall Rule Spec which will be an array of individual Firewall rules as we process them in next section + $ruleSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Create() - foreach ($vmcFirewallRule in $vmcFirewallRulesJSON) { + foreach ($vmcFirewallRule in $vmcFirewallRulesJSON) { # Create Individual Firewall Rule Element Spec $ruleElementSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.Create() @@ -629,13 +639,14 @@ Function Import-VMCFirewallRule { Write-host "Creating VMC Firewall Rule Spec:" $vmcFirewallRule.Name "..." $ruleSpecAdd = $ruleSpec.Add($ruleElementSpec) } - $firewallRules.firewall_rules = $ruleSpec + $firewallRules.firewall_rules = $ruleSpec - Write-host "Adding VMC Firewall Rules ..." - $firewallRuleAdd = $firewallService.add($orgId,$sddcId,$EdgeId,$firewallRules) -} -Function Remove-VMCFirewallRule { -<# + Write-host "Adding VMC Firewall Rules ..." + $firewallRuleAdd = $firewallService.add($orgId,$sddcId,$EdgeId,$firewallRules) + } + + Function Remove-VMCFirewallRule { + <# .NOTES =========================================================================== Created by: William Lam @@ -652,37 +663,38 @@ Function Remove-VMCFirewallRule { .EXAMPLE Remove-VMCFirewallRule -OrgName -SDDCName -GatewayType -RuleId #> - param( + param( [Parameter(Mandatory=$false)][String]$SDDCName, [Parameter(Mandatory=$false)][String]$OrgName, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, [Parameter(Mandatory=$false)][String]$RuleId ) - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - if($GatewayType -eq "MGW") { + if($GatewayType -eq "MGW") { $EdgeId = "edge-1" } else { $EdgeId = "edge-2" } - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - if(-not $orgId) { + if(-not $orgId) { Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" break } - if(-not $sddcId) { + if(-not $sddcId) { Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" break } - $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules - Write-Host "Removing VMC Firewall Rule Id $RuleId ..." - $firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId) -} + $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + Write-Host "Removing VMC Firewall Rule Id $RuleId ..." + $firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId) + } + Function Get-VMCLogicalNetwork { <# .NOTES @@ -690,7 +702,7 @@ Function Get-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://www.kmruddy.com + Blog: https://thatcouldbeaproblem.com Twitter: @kmruddy =========================================================================== @@ -722,17 +734,9 @@ Function Get-VMCLogicalNetwork { break } - # @LucD22 - 21/10/18 - Fix for issue #176 VMware.VMC module only lists firts 20 Logical networks - # Loop until entries (total_count) are returned + $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical - $index = [long]0 - - $logicalNetworks = do{ - $netData = $logicalNetworkService.get_0($orgId,$sddcId,$pagesize,$index) - $netData.data | Sort-Object -Property id - $index = $index + $netdata.paging_info.page_size - } - until($index -ge $netData.paging_info.total_count) + $logicalNetworks = ($logicalNetworkService.get_0($orgId, $sddcId)).data | Sort-Object -Property id if($LogicalNetworkName) { $logicalNetworks = $logicalNetworks | Where-Object {$_.Name -eq $LogicalNetworkName} @@ -754,6 +758,7 @@ Function Get-VMCLogicalNetwork { } $results } + Function Remove-VMCLogicalNetwork { <# .NOTES @@ -761,7 +766,7 @@ Function Remove-VMCLogicalNetwork { Created by: Kyle Ruddy Date: 03/06/2018 Organization: VMware - Blog: https://www.kmruddy.com + Blog: https://thatcouldbeaproblem.com Twitter: @kmruddy =========================================================================== @@ -801,24 +806,25 @@ Function Remove-VMCLogicalNetwork { $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical $logicalNetworkService.delete($orgId,$sddcId,$lsId) } -Function New-VMCLogicalNetwork { -<# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/06/2018 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - .SYNOPSIS - Creates a new Logical Network - .DESCRIPTION - Creates a new Logical Network - .EXAMPLE - New-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName -SubnetMask -Gateway -#> +Function New-VMCLogicalNetwork { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/06/2018 + Organization: VMware + Blog: https://thatcouldbeaproblem.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new Logical Network + .DESCRIPTION + Creates a new Logical Network + .EXAMPLE + New-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName -SubnetMask -Gateway + #> [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] param( [Parameter(Mandatory=$true)][String]$SDDCName, @@ -855,768 +861,5 @@ Function New-VMCLogicalNetwork { $logicalNetworkService.create($orgId, $sddcId, $logicalNetworkSpec) Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName } -Function Get-VMCSDDCSummary { - <# - .NOTES - =========================================================================== - Created by: VMware - Date: 09/04/18 - Organization: VMware - Blog: https://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - .SYNOPSIS - Returns a number of useful informational data about a given SDDC within VMC Org - .DESCRIPTION - Returns Version, Create/Expiration Date, Deployment Type, Region, AZ, Instance Type, VPC CIDR & NSX-T - .EXAMPLE - Get-VMCSDDCSummary -Name -Org - #> - Param ( - [Parameter(Mandatory=$True)]$Org, - [Parameter(Mandatory=$True)]$Name - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $Org).Id - $sddcId = (Get-VMCSDDC -Name $Name -Org $Org).Id - - $sddcService = Get-VmcService "com.vmware.vmc.orgs.sddcs" - $sddc = $sddcService.get($orgId,$sddcId) - - $results = [pscustomobject] @{ - Version = $sddc.resource_config.sddc_manifest.vmc_version; - CreateDate = $sddc.created; - ExpirationDate = $sddc.expiration_date; - DeploymentType = $sddc.resource_config.deployment_type; - Region = $sddc.resource_config.region; - AvailabilityZone = $sddc.resource_config.availability_zones; - InstanceType = $sddc.resource_config.sddc_manifest.esx_ami.instance_type; - VpcCIDR = $sddc.resource_config.vpc_info.vpc_cidr; - NSXT = $sddc.resource_config.nsxt; - VPC_VGW = $sddc.resource_config.vpc_info.vgw_id; - } - $results - } -} -Function Get-VMCPublicIP { - <# - .NOTES - =========================================================================== - Created by: William LamVPC_VGW - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Retrieves all public IP Addresses for a given SDDC - .DESCRIPTION - This cmdlet retrieves all public IP Address for a given SDDC - .EXAMPLE - Get-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName - #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - $publicIPs = $publicIPService.list($orgId,$sddcId) - - $publicIPs | select public_ip, name, allocation_id - } -} - -Function New-VMCPublicIP { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Request a new public IP Address for a given SDDC - .DESCRIPTION - This cmdlet requests a new public IP Address for a given SDDC - .EXAMPLE - New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" - #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$False)]$Description - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - - $publicIPSpec = $publicIPService.Help.create.spec.Create() - $publicIPSpec.count = 1 - $publicIPSpec.names = @($Description) - - Write-Host "Requesting a new public IP Address for your SDDC ..." - $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) - } -} - -Function Remove-VMCPublicIP { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Removes a specific public IP Addresses for a given SDDC - .DESCRIPTION - This cmdlet removes a specific public IP Address for a given SDDC - .EXAMPLE - Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" - #> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$True)]$AllocationId - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - - Write-Host "Deleting public IP Address with ID $AllocationId ..." - $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) - } -} - -Function Set-VMCSDDC { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 01/12/2019 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Rename an SDDC - .DESCRIPTION - This cmdlet renames an SDDC - .EXAMPLE - Set-VMCSDDC -SDDC $SDDCName -OrgName $OrgName -Name $NewSDDCName - #> - Param ( - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$Name - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $sddc = Get-VMCSDDC -Org $OrgName -Name $SDDCName - if($sddc) { - $sddcService = Get-VmcService com.vmware.vmc.orgs.sddcs - $renameSpec = $sddcService.help.patch.sddc_patch_request.Create() - $renameSpec.name = $Name - - Write-Host "`nRenaming SDDC `'$SDDCName`' to `'$Name`' ...`n" - $results = $sddcService.patch($sddc.org_id,$sddc.id,$renameSpec) - } - } -} - -Function New-VMCPublicIP { -<# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Request a new public IP Address for a given SDDC - .DESCRIPTION - This cmdlet requests a new public IP Address for a given SDDC - .EXAMPLE - New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" -#> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$False)]$Description - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - - $publicIPSpec = $publicIPService.Help.create.spec.Create() - $publicIPSpec.count = 1 - $publicIPSpec.names = @($Description) - - Write-Host "Requesting a new public IP Address for your SDDC ..." - $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) - } -} - -Function Remove-VMCPublicIP { -<# - .NOTES - =========================================================================== - Created by: William Lam - Date: 09/12/2018 - Organization: VMware - Blog: http://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Removes a specific public IP Addresses for a given SDDC - .DESCRIPTION - This cmdlet removes a specific public IP Address for a given SDDC - .EXAMPLE - Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" -#> - Param ( - [Parameter(Mandatory=$True)]$OrgName, - [Parameter(Mandatory=$True)]$SDDCName, - [Parameter(Mandatory=$True)]$AllocationId - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" - - Write-Host "Deleting public IP Address with ID $AllocationId ..." - $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) - } -} - -Function Get-VMCEdge { -<# -.NOTES -=========================================================================== -Created by: Luc Dekens -Date: 23/10/2018 -Organization: Community -Blog: http://lucd.info -Twitter: @LucD22 -=========================================================================== - -.SYNOPSIS - Returns all the VMC Edges -.DESCRIPTION - Returns all the VMC Edges -.EXAMPLE - Get-VMCEdge -OrgName $orgName -SddcName $SDDCName -EdgeType gatewayServices -#> - Param ( - [Parameter(Mandatory=$True)] - [string]$OrgName, - [Parameter(Mandatory=$True)] - [string]$SDDCName, - [ValidateSet('gatewayServices','distributedRouter')] - [string]$EdgeType = '' - ) - - If (-Not $global:DefaultVMCServers) { - Write-error "No VMC Connection found, please use the Connect-VMC to connect" - } - Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $edgeService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges' - $index = [long]0 - $edges = do{ - $edgeData = $edgeService.get($orgId,$sddcId,$EdgeType,'',$index) - $edgeData.edge_page.data | Sort-Object -Property id - $index = $index + $edgeData.edge_page.paging_info.page_size - } - until($index -ge $edgeData.paging_info.total_count) - $edges | %{ - [pscustomobject]@{ - Name = $_.Name - Id = $_.id - Type = $_.edge_type - State = $_.state - Status = $_.edge_status - VNics = $_.number_of_connected_vnics - TenantId = $_.tenant_id - } - } - } -} - -Function Get-VMCEdgeStatus { -<# -.NOTES -=========================================================================== -Created by: Luc Dekens -Date: 23/10/2018 -Organization: Community -Blog: http://lucd.info -Twitter: @LucD22 -=========================================================================== - -.SYNOPSIS - Returns the status of the gateway -.DESCRIPTION - Retrieve the status of the specified management or compute gateway (NSX Edge). -.EXAMPLE - Get-VMCEdgeStatus -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName -#> - Param ( - [Parameter(Mandatory=$True)] - [string]$OrgName, - [Parameter(Mandatory=$True)] - [string]$SDDCName, - [Parameter(Mandatory=$True)] - [string]$EdgeName - ) - - If (-Not $global:DefaultVMCServers) { - Write-error "No VMC Connection found, please use the Connect-VMC to connect" - } - Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id - - $statusService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.status' - $status = $statusService.get($orgId,$sddcId,$edgeId) - - $vmStatus = $status.edge_vm_status | %{ - [pscustomobject]@{ - Name = $_.name - State = $_.edge_VM_status - HAState = $_.ha_state - Index = $_.index - } - } - $featureStatus = $status.feature_statuses | %{ - [pscustomobject]@{ - Service = $_.service - Status = $_.status - } - } - [pscustomobject]@{ - Time = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($status.timestamp/1000)) - Status = $status.edge_status - PublishStatus = $status.publish_status - SystemStatus = $_.system_status - NicInUse = $status.ha_vnic_in_use - } - } -} - -Function Get-VMCEdgeNic { -<# -.NOTES -=========================================================================== -Created by: Luc Dekens -Date: 23/10/2018 -Organization: Community -Blog: http://lucd.info -Twitter: @LucD22 -=========================================================================== - -.SYNOPSIS - Returns all interfaces for the gateway -.DESCRIPTION - Retrieve all interfaces for the specified management or compute gateway (NSX Edge). -.EXAMPLE - Get-VMCEdgeNic -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName -#> - Param ( - [Parameter(Mandatory=$True)] - [string]$OrgName, - [Parameter(Mandatory=$True)] - [string]$SDDCName, - [Parameter(Mandatory=$True)] - [string]$EdgeName - ) - - If (-Not $global:DefaultVMCServers) { - Write-error "No VMC Connection found, please use the Connect-VMC to connect" - } - Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id - - $vnicService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.vnics' - $vnicService.get($orgId,$sddcId,$edgeId) | select -ExpandProperty vnics | %{ - [pscustomobject]@{ - Label = $_.label - Name = $_.Name - Type = $_.type - Index = $_.index - IsConnected = $_.is_connected - Portgroup = $_.portgroup_name - } - } - } -} - -Function Get-VMCEdgeNicStat { -<# -.NOTES -=========================================================================== -Created by: Luc Dekens -Date: 23/10/2018 -Organization: Community -Blog: http://lucd.info -Twitter: @LucD22 -=========================================================================== - -.SYNOPSIS - Returns statistics for the gateway interfaces -.DESCRIPTION - Retrieve interface statistics for a management or compute gateway (NSX Edge). -.EXAMPLE - Get-VMCEdgeNicStat -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName -#> - [CmdletBinding(DefaultParameterSetName='Default')] - Param ( - [Parameter(Mandatory=$True)] - [string]$OrgName, - [Parameter(Mandatory=$True)] - [string]$SDDCName, - [Parameter(Mandatory=$True)] - [string]$EdgeName -# [DateTime]$Start, -# [DateTime]$Finish - ) - - If (-Not $global:DefaultVMCServers) { - Write-error "No VMC Connection found, please use the Connect-VMC to connect" - } - Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id - -# $epoch = Get-Date 01/01/1970 -# -# if($start){ -# $startEpoch = (New-TimeSpan -Start $epoch -End $Start.ToUniversalTime()).TotalMilliseconds -# } -# if($Finish){ -# $finishEpoch = (New-TimeSpan -Start $epoch -End $Finish.ToUniversalTime()).TotalMilliseconds -# } - - $vnicStatService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.statistics.interfaces' -# $stats = $vnicStatService.get($orgId,$sddcId,$edgeId,[long]$startEpoch,[long]$finishEpoch) - $stats = $vnicStatService.get($orgId,$sddcId,$edgeId) - - $stats.data_dto | Get-Member -MemberType NoteProperty | where{$_.Name -ne 'Help'} | %{$_.Name} | %{ - $stats.data_dto."$_" | %{ - [pscustomobject]@{ - vNIC = $_.vnic - Timestamp = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.timestamp)) - In = $_.in - Out = $_.out - Unit = 'Kbps' - Interval = $stats.meta_dto.interval - } - } - } - } -} - -Function Get-VMCEdgeUplinkStat { -<# -.NOTES -=========================================================================== -Created by: Luc Dekens -Date: 23/10/2018 -Organization: Community -Blog: http://lucd.info -Twitter: @LucD22 -=========================================================================== - -.SYNOPSIS - Returns statistics for the uplink interfaces -.DESCRIPTION - Retrieve uplink interface statistics for a management or compute gateway (NSX Edge). -.EXAMPLE - Get-VMCEdgeUplinkStat -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName -#> - Param ( - [Parameter(Mandatory=$True)] - [string]$OrgName, - [Parameter(Mandatory=$True)] - [string]$SDDCName, - [Parameter(Mandatory=$True)] - [string]$EdgeName -# [DateTime]$Start, -# [DateTime]$Finish - ) - - If (-Not $global:DefaultVMCServers) { - Write-error "No VMC Connection found, please use the Connect-VMC to connect" - } - Else { - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id - -# $epoch = Get-Date 01/01/1970 -# -# if($start){ -# $startEpoch = (New-TimeSpan -Start $epoch -End $Start.ToUniversalTime()).TotalMilliseconds -# } -# if($Finish){ -# $finishEpoch = (New-TimeSpan -Start $epoch -End $Finish.ToUniversalTime()).TotalMilliseconds -# } - - $uplinkStatService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.statistics.interfaces.uplink' -# $stats = $uplinkStatService.get($orgId,$sddcId,$edgeId,[long]$startEpoch,[long]$finishEpoch) - $stats = $uplinkStatService.get($orgId,$sddcId,$edgeId) - - $stats.data_dto | Get-Member -MemberType NoteProperty | where{$_.Name -ne 'Help'} | %{$_.Name} | %{ - if($stats.data_dto."$_".Count -ne 0){ - $stats.data_dto."$_" | %{ - [pscustomobject]@{ - vNIC = $_.vnic - Timestamp = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.timestamp)) - In = $_.in - Out = $_.out - Unit = 'Kbps' - Interval = $stats.meta_dto.interval - } - } - } - } - } -} -Function New-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Creates a new cluster for the designated SDDC - .DESCRIPTION - Creates a new cluster - .EXAMPLE - New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][Int]$HostCount, - [Parameter(Mandatory=$true)][ValidateSet("8","16","32")]$CPUCoreCount - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters - - $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() - $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount - $sddcClusterCreateSpec.num_hosts = $HostCount - - $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) - $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table -} -Function Get-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Retreives cluster information for the designated SDDC - .DESCRIPTION - Lists cluster information for an SDDC - .EXAMPLE - Get-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='Low')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SddcName - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $clusterOutput = @() - $sddcClusters = Get-VMCSDDC -Org $OrgName -Name $SDDCName | Select-Object -ExpandProperty resource_config | Select-Object -ExpandProperty clusters - foreach ($c in $sddcClusters) { - $tempCluster = "" | Select-Object Id, Name, State - $tempCluster.Id = $c.cluster_id - $tempCluster.Name = $c.cluster_name - $tempCluster.State = $c.cluster_state - $clusterOutput += $tempCluster - } - return $clusterOutput -} -Function New-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Creates a new cluster for the designated SDDC - .DESCRIPTION - Creates a new cluster - .EXAMPLE - New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SddcName, - [Parameter(Mandatory=$true)][Int]$HostCount, - [Parameter(Mandatory=$false)][ValidateSet("8","16","36","48")]$CPUCoreCount - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters - - $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() - $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount - $sddcClusterCreateSpec.num_hosts = $HostCount - - $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) - $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table -} -Function Remove-VMCSDDCCluster { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/16/2019 - Organization: VMware - Blog: https://www.kmruddy.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Removes a specified cluster from the designated SDDC - .DESCRIPTION - Deletes a cluster from an SDDC - .EXAMPLE - Remove-VMCSDDCCluster -OrgName -SDDCName -Cluster - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][String]$ClusterName - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id - $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id - $clusterId = Get-VMCSDDCCluster -SddcName $SDDCName -OrgName $OrgName | Where-Object {$_.Name -eq $ClusterName} | Select-Object -ExpandProperty Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - if(-not $clusterId) { - Write-Host -ForegroundColor red "Unable to find cluster $ClusterName, please verify input" - break - } - - $sddcClusterTask = $sddcClusterSvc.Delete($orgId, $sddcId, $clusterId) - $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table -} - -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', - 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', - 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', - 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', - 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', 'Set-VMCSDDC', - 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat', - 'Get-VMCSDDCCluster', 'New-VMCSDDCCluster', 'Remove-VMCSDDCCluster' \ No newline at end of file +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork' \ No newline at end of file From 337dc077a9398cfc3b9523922512323f4d22f743 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Tue, 6 Aug 2019 10:33:44 -0500 Subject: [PATCH 123/175] Update version. Minor formatting --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 | 2 +- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 index 42dc6aa..7edd3bc 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.1' +ModuleVersion = '1.3' # 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 071af67..58710e4 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -1,5 +1,5 @@ #Script Module : VMware.Hv.Helper -#Version : 1.2 +#Version : 1.3 #Copyright © 2016 VMware, Inc. All Rights Reserved. @@ -10618,7 +10618,7 @@ function Get-HVHealth { param( [Parameter(Mandatory = $false)] - [ValidateSet('ADDomain', 'CertificateSSOConnector', 'ConnectionServer', 'EventDatabase', 'SAMLAuthenticator', 'SecurityServer', 'ViewComposer', 'VirtualCenter', 'pod')] + [ValidateSet('ADDomain', 'CertificateSSOConnector', 'ConnectionServer', 'EventDatabase', 'SAMLAuthenticator', 'SecurityServer', 'ViewComposer', 'VirtualCenter', 'Pod')] [string] $Servicename = 'ConnectionServer', From cbf397df24661f053a7cd668f4c881344b0ec676 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Tue, 6 Aug 2019 14:28:16 -0500 Subject: [PATCH 124/175] Worked through PSScriptAnalyzer low hanging fruit --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 508 +++++++++--------- 1 file changed, 245 insertions(+), 263 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 58710e4..0b0b3bf 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -482,7 +482,6 @@ function Get-UserId ($User) { $defn = New-Object VMware.Hv.QueryDefinition $defn.queryEntityType = 'ADUserOrGroupSummaryView' - [VMware.Hv.QueryFilter[]]$filters = $null $groupfilter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.group'; 'value' = $false } $userNameFilter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.name'; 'value' = $user } $treeList = @() @@ -668,7 +667,7 @@ function Connect-HVEvent { [CmdletBinding()] param( [Parameter(Mandatory = $false)] - $DbPassword = $null, + [SecureString]$DbPassword = $null, [Parameter(Mandatory = $false)] $HvServer = $null, @@ -705,12 +704,10 @@ function Connect-HVEvent { if (!$dbPassword) { $dbPassword = Read-Host 'Database Password for' $dbUserName@$dbServer -AsSecureString } if ($dbType -eq "SQLSERVER") { - if ($dbPassword.GetType().name -eq 'String'){ - $password = ConvertTo-SecureString $dbPassword -AsPlainText -Force - } elseif ($dbPassword.GetType().name -eq 'SecureString') { + if ($dbPassword.GetType().name -eq 'SecureString') { $password = $dbPassword } else { - Write-Error "Unsupported type recieved for dbPassword: [$dbPassword]. dbpassword should either be String or SecureString type. " + Write-Error "Unsupported type recieved for dbPassword: [$dbPassword]. dbpassword should SecureString type." break } $connectionString = "Data Source=$dbServer, $dbPort; Initial Catalog=$dbName;" @@ -1117,10 +1114,7 @@ function Get-HVFarm { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -1231,10 +1225,7 @@ function Get-HVFarmSummary { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -1337,7 +1328,7 @@ function Find-HVFarm { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $farmList = $queryResults.results | where $scriptBlock + $farmList = $queryResults.results | Where-Object $scriptBlock } Return $farmList } @@ -1419,10 +1410,7 @@ function Get-HVPool { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -1558,10 +1546,7 @@ function Get-HVPoolSummary { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -1675,7 +1660,7 @@ function Find-HVPool { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $poolList = $queryResults.results | where $scriptBlock + $poolList = $queryResults.results | Where-Object $scriptBlock } Return $poolList } @@ -1918,8 +1903,7 @@ function Get-HVQueryResult { PowerShell Version : 5.0 #> - [CmdletBinding(SupportsShouldProcess = $true, - ConfirmImpact = 'High')] + [CmdletBinding()] param( [Parameter(Position = 0,Mandatory = $true)] [ValidateSet('ADUserOrGroupSummaryView','ApplicationIconInfo','ApplicationInfo','DesktopSummaryView', @@ -2835,11 +2819,12 @@ function New-HVFarm { $farmSpecObj.ManualFarmSpec = $FarmManualFarmSpec } - # 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 - #> + If ($DebugPreference -ne 'SilentlyContinue') { + $myDebug = convertto-json -InputObject $farmSpecObj -depth 12 + $DebugOutput = "c:\temp\copiedfarm.json" + $myDebug | Out-File -filepath $DebugOutput + Write-Debug "Output Farm Spec to $DebugOutput." + } if (!$confirmFlag -OR $pscmdlet.ShouldProcess($farmSpecObj.data.name)) { $Id = $farm_service_helper.Farm_Create($services, $farmSpecObj) @@ -3139,7 +3124,7 @@ function Get-HVFarmCustomizationSetting { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $instantCloneEngineDomainAdministrator = $insDomainAdministrators | Where $scriptBlock + $instantCloneEngineDomainAdministrator = $insDomainAdministrators | Where-Object $scriptBlock If ($null -ne $instantCloneEngineDomainAdministrator) { $instantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator[0].id } elseif ($null -ne $insDomainAdministrators) { @@ -3167,7 +3152,7 @@ function Get-HVFarmCustomizationSetting { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $ViewComposerDomainAdministratorID = $lcDomainAdministrators | Where $scriptBlock + $ViewComposerDomainAdministratorID = $lcDomainAdministrators | Where-Object $scriptBlock if ($null -ne $ViewComposerDomainAdministratorID) { $ViewComposerDomainAdministratorID = $ViewComposerDomainAdministratorID[0].id } elseif ($null -ne $lcDomainAdministrators) { @@ -5108,7 +5093,7 @@ function Get-HVHostOrClusterID { if ($hoctn.container) { foreach ($node in $hoctn.treeContainer.children) { $id = Get-HVHostOrClusterID $node - if ($id -ne $null) { + if ($null -ne $id) { return $id } } @@ -5146,7 +5131,7 @@ function Get-HVResourcePoolID { } foreach ($child in $rpi.children) { $id = Get-HVResourcePoolID $child - if ($id -ne $null) { + if ($null -ne $id) { return $id } } @@ -5191,7 +5176,7 @@ function Get-HVAccessGroupID { } foreach ($child in $element.children) { $id = Get-HVAccessGroupID $child - if ($id -ne $null) { + if ($null -ne $id) { return $id } } @@ -5364,7 +5349,7 @@ function Get-HVPoolCustomizationSetting { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $instantCloneEngineDomainAdministrator = $insDomainAdministrators | Where $scriptBlock + $instantCloneEngineDomainAdministrator = $insDomainAdministrators | Where-Object $scriptBlock If ($null -ne $instantCloneEngineDomainAdministrator) { $instantCloneEngineDomainAdministrator = $instantCloneEngineDomainAdministrator[0].id } elseif ($null -ne $insDomainAdministrators) { @@ -5394,7 +5379,7 @@ function Get-HVPoolCustomizationSetting { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $ViewComposerDomainAdministratorID = $lcDomainAdministrators | Where $scriptBlock + $ViewComposerDomainAdministratorID = $lcDomainAdministrators | Where-Object $scriptBlock If ($null -ne $ViewComposerDomainAdministratorID) { $ViewComposerDomainAdministratorID = $ViewComposerDomainAdministratorID[0].id } elseif ($null -ne $lcDomainAdministrators) { @@ -5523,7 +5508,7 @@ function Test-HVPoolSpec { 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) { + if ($null -eq $PoolObject.AutomatedDesktopSpec.ProvisioningType) { Throw "Pool Provisioning type is empty, need to be configured" } $provisionTypeArray = @('VIRTUAL_CENTER', 'VIEW_COMPOSER', 'INSTANT_CLONE_ENGINE') @@ -7441,7 +7426,7 @@ function Find-HVMachine { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $machineList += $queryResults.results | where $scriptBlock + $machineList += $queryResults.results | Where-Object $scriptBlock $GetNext = $true } while ($queryResults.remainingCount -gt 0) $query_service_helper.QueryService_Delete($services, $queryResults.id) @@ -7514,10 +7499,7 @@ function Get-HVMachine { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -7637,10 +7619,7 @@ function Get-HVMachineSummary { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -7915,7 +7894,7 @@ function Get-DataStoreName { ) $dataStoresObj = @() $entityId = New-Object VMware.Hv.EntityId - $datastores | % { + $datastores | ForEach-Object { $entityId.Id = $_.datastore.Id $dataStoresObj += , (New-Object PsObject -Property @{ datastore = Get-HVInternalName -EntityId $entityId; @@ -7958,10 +7937,7 @@ function Get-HVInternalName { PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] @@ -8004,15 +7980,15 @@ function Get-HVInternalName { return $Info.Base.Username } 'BaseImageVm' { - $info = $services.BaseImageVm.BaseImageVm_List($VcId) | where { $_.id.id -eq $EntityId.id } + $info = $services.BaseImageVm.BaseImageVm_List($VcId) | Where-Object { $_.id.id -eq $EntityId.id } return $info.name } 'BaseImageSnapshot' { - $info = $services.BaseImageSnapshot.BaseImageSnapshot_List($BaseImageVmId) | where { $_.id.id -eq $EntityId.id } + $info = $services.BaseImageSnapshot.BaseImageSnapshot_List($BaseImageVmId) | Where-Object { $_.id.id -eq $EntityId.id } return $info.name } 'VmTemplate' { - $info = $services.VmTemplate.VmTemplate_List($VcId) | where { $_.id.id -eq $EntityId.id } + $info = $services.VmTemplate.VmTemplate_List($VcId) | Where-Object { $_.id.id -eq $EntityId.id } return $info.name } 'ViewComposerDomainAdministrator' { @@ -8045,10 +8021,7 @@ function Get-HVInternalName { function Get-UserInfo { - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidatePattern("^.+?[@\\].+?$")] @@ -8370,10 +8343,7 @@ function Get-HVEntitlement { #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] [ValidatePattern("^.+?[@\\].+?$")] @@ -8438,7 +8408,7 @@ function Get-HVEntitlement { } $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $AndFilter -HvServer $HvServer) - $results = $results | where {$_.localData.desktops -ne $null} + $results = $results | Where-Object {$null -ne $_.localData.desktops} } "Application" { if ($ResourceName) { @@ -8452,7 +8422,7 @@ function Get-HVEntitlement { } $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $AndFilter -HvServer $HvServer) - $results = $results | where {$_.localData.applications -ne $null} + $results = $results | Where-Object {$null -ne $_.localData.applications} } "URLRedirection" { $localFilter = @() @@ -8473,11 +8443,11 @@ function Get-HVEntitlement { } $localFilter = Get-HVQueryFilter -And -Filters $localFilter $localResults = Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $localFilter -HvServer $HvServer - $results += ($localResults | where {$_.localData.urlRedirectionSettings -ne $null}) + $results += ($localResults | Where-Object {$null -ne $_.localData.urlRedirectionSettings}) if ($cpaEnabled) { $globalFilter = Get-HVQueryFilter -And -Filters $globalFilter $globalResults = Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $globalFilter -HvServer $HvServer - $globalResults = $globalResults | where {$_.globalData.urlRedirectionSettings -ne $null} + $globalResults = $globalResults | Where-Object {$null -ne $_.globalData.urlRedirectionSettings} $results += $globalResults } } @@ -8497,7 +8467,7 @@ function Get-HVEntitlement { } $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer) - $results = $results| where {$_.globalData.globalApplicationEntitlements -ne $null} + $results = $results| Where-Object {$null -ne $_.globalData.globalApplicationEntitlements} } "GlobalEntitlement" { if (! $cpaEnabled) { @@ -8515,7 +8485,7 @@ function Get-HVEntitlement { } $AndFilter = Get-HVQueryFilter -And -Filters $AndFilter $results = (Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer) - $results = $results | where {$_.globalData.globalEntitlements -ne $null} + $results = $results | Where-Object {$null -ne $_.globalData.globalEntitlements} } } if (! $results) { @@ -9213,7 +9183,7 @@ function Find-HVGlobalEntitlement { } $whereClause = [string]::Join(' -and ', $strFilterSet) $scriptBlock = [Scriptblock]::Create($whereClause) - $GeList = $queryResults.results | where $scriptBlock + $GeList = $queryResults.results | Where-Object $scriptBlock } Return $GeList } @@ -9257,10 +9227,7 @@ function Get-HVGlobalEntitlement { PowerShell Version : 5.0 #> -[CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] +[CmdletBinding()] param( [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] @@ -9613,10 +9580,7 @@ The get-hvglobalsession gets all local session by using view API service object( PowerShell Version : 5.0 #> -[CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' -)] +[CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -9755,23 +9719,25 @@ function Set-HVApplicationIcon { 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 + If ($Force -or $PSCmdlet.ShouldProcess($ApplicationName)) { + $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]." } - Write-Host "Successfully associated customized icon for Application:[$ApplicationName]." } end { @@ -9860,13 +9826,17 @@ Function Remove-HVApplicationIcon { break } - try { - $ApplicationIconHelper.ApplicationIcon_RemoveAssociations($services, $brokerIcon, @($appInfo.Id)) - } catch { - Write-Error "Error in removing the customized icon association for Application:[$ApplicationName] $_ " - break + if ($Force -or $PSCmdlet.ShouldProcess($ApplicationName)) { + + 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]." + } - Write-Host "Successfully removed customized icon association for Application:[$ApplicationName]." } end { @@ -9903,10 +9873,7 @@ function Get-HVGlobalSettings { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -10251,10 +10218,16 @@ function Set-HVGlobalSettings { if ($enableIPSecForSecurityServerPairing) { $updates += Get-MapEntry -key 'securityData.enableIPSecForSecurityServerPairing' -Value $enableIPSecForSecurityServerPairing } - - $global_settings_helper = New-Object VMware.Hv.GlobalSettingsService - $global_settings_helper.GlobalSettings_Update($services,$updates) + if ($Force -or $PSCmdlet.ShouldProcess($HVServer.Name)) { + + $global_settings_helper = New-Object VMware.Hv.GlobalSettingsService + + $global_settings_helper.GlobalSettings_Update($services,$updates) + + Write-Host "Global settings updated." + + } } @@ -10263,19 +10236,19 @@ function Set-HVGlobalSettings { } } -function get-HVlocalsession { +function Get-HVLocalSession { <# .SYNOPSIS Provides a list with all sessions on the local pod (works in CPA and non-CPA) .DESCRIPTION -The get-hvlocalsession gets all local session by using view API service object(hvServer) of Connect-HVServer cmdlet. +The Get-HVLocalSession gets all local session by using view API service object(hvServer) of Connect-HVServer cmdlet. .PARAMETER HvServer View API service object of Connect-HVServer cmdlet. .EXAMPLE - Get-hvlocalsession + Get-HVLocalSession Get all local sessions .NOTES @@ -10289,10 +10262,7 @@ The get-hvlocalsession gets all local session by using view API service object(h PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( [Parameter(Mandatory = $false)] @@ -10304,7 +10274,7 @@ The get-hvlocalsession gets all local session by using view API service object(h Write-Error "Could not retrieve ViewApi services from connection object." break } - + $query_service_helper = New-Object VMware.Hv.QueryServiceService $query = New-Object VMware.Hv.QueryDefinition @@ -10363,35 +10333,46 @@ function Reset-HVMachine { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] - - param( - - [Parameter(Mandatory = $true)] - [string] - $MachineName, - - [Parameter(Mandatory = $false)] - $HvServer = $null - ) + [CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' + )] - - $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 "Reset-HVMachine: No Virtual Machine(s) Found with given search parameters" - break + param( + + [Parameter(Mandatory = $true)] + [string] + $MachineName, + + [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 + } + + $machineList = Find-HVMachine -Param $PSBoundParameters + + if (!$machineList) { + Write-Host "Reset-HVMachine: No Virtual Machine(s) Found with given search parameters" + break + } } - foreach ($machine in $machinelist){ - $services.machine.Machine_ResetMachines($machine.id) + Process { + if ($Force -or $PSCmdlet.ShouldProcess($MachineName)) { + foreach ($machine in $machinelist){ + $services.machine.Machine_ResetMachines($machine.id) + } + } + } + End { + [System.gc]::collect() } } function Remove-HVMachine { @@ -10439,138 +10420,143 @@ function Remove-HVMachine { #> [CmdletBinding( - SupportsShouldProcess = $true, + SupportsShouldProcess = $true, ConfirmImpact = 'High' - )] + )] param( [Parameter(Mandatory = $true)] [array] - $MachineNames, + $MachineNames, - [Parameter(Mandatory = $false)] - [switch]$DeleteFromDisk = $true, + [Parameter(Mandatory = $false)] + [switch]$DeleteFromDisk, [Parameter(Mandatory = $false)] $HVServer = $null ) -#Connect to HV Server -$services = Get-ViewAPIService -HVServer $HVServer - -if ($null -eq $services) { - Write-Error "Could not retrieve ViewApi services from connection object" - break - } - -#Connect to Query Service -$queryService = New-Object 'Vmware.Hv.QueryServiceService' -#QUery Definition -$queryDefinition = New-Object 'Vmware.Hv.QueryDefinition' -#Query Filter -$queryDefinition.queryEntityType = 'MachineNamesView' - -#Create Filter Set so we can populate it with QueryFilterEquals data -[VMware.Hv.queryfilter[]]$filterSet = @() -foreach($machine in $machineNames){ - - #queryfilter values - $queryFilterEquals = New-Object VMware.Hv.QueryFilterEquals - $queryFilterEquals.memberName = "base.name" - $queryFilterEquals.value = "$machine" - - $filterSet += $queryFilterEquals - -} - -#Or Filter -$orFilter = New-Object VMware.Hv.QueryFilterOr -$orFilter.filters = $filterSet - -#Set Definition filter to value of $orfilter -$queryDefinition.filter = $orFilter - -#Retrieve query results. Returns all machines to be deleted -$queryResults = $queryService.QueryService_Query($services,$queryDefinition) - -#Assign VM Object to variable -$deleteThisMachine = $queryResults.Results - -#Machine Service -$machineService = new-object VMware.Hv.MachineService - -#Get Machine Service machine object -$deleteMachine = $machineService.Machine_GetInfos($services,$deleteThisMachine.Id) - -#If sessions exist on the machines we are going to delete than force kill those sessions. -#The deleteMachines method will not work if there are any existing sessions so this step is very important. -write-host "Attemtping log off of machines" - -if($deleteMachine.base.session.id){ -$trys = 0 - - do{ - foreach($session in $deleteMachine.base.session){ - - $sessions = $null - [VMware.Hv.SessionId[]]$sessions += $session - - } - - try{ - - write-host "`n" - write-host "Attemtping log off of machines" - write-host "`n" - $logOffSession = new-object 'VMware.Hv.SessionService' - $logOffSession.Session_LogoffSessionsForced($services,$sessions) - - #Wait more for Sessions to end - - Start-Sleep -Seconds 5 - - } - - catch{ - - Write-Host "Attempted to Log Off Sessions from below machines but recieved an error. This doesn't usually mean it failed. Typically the session is succesfully logged off but takes some time" - write-host "`n" - write-host ($deleteMachine.base.Name -join "`n") - - start-sleep -seconds 5 + Begin { + #Connect to HV Server + $services = Get-ViewAPIService -HVServer $HVServer + if ($null -eq $services) { + Write-Error "Could not retrieve ViewApi services from connection object" + break } - if(($trys -le 10)){ + #Connect to Query Service + $queryService = New-Object 'Vmware.Hv.QueryServiceService' + #QUery Definition + $queryDefinition = New-Object 'Vmware.Hv.QueryDefinition' + #Query Filter + $queryDefinition.queryEntityType = 'MachineNamesView' + } + Process { + #Create Filter Set so we can populate it with QueryFilterEquals data + [VMware.Hv.queryfilter[]]$filterSet = @() + foreach($machine in $machineNames){ - write-host "`n" - write-host "Retrying Logoffs: $trys times" - #Recheck existing sessions - $deleteMachine = $machineService.Machine_GetInfos($services,$deleteThisMachine.Id) + #queryfilter values + $queryFilterEquals = New-Object VMware.Hv.QueryFilterEquals + $queryFilterEquals.memberName = "base.name" + $queryFilterEquals.value = "$machine" + + $filterSet += $queryFilterEquals + } + + #Or Filter + $orFilter = New-Object VMware.Hv.QueryFilterOr + $orFilter.filters = $filterSet + + #Set Definition filter to value of $orfilter + $queryDefinition.filter = $orFilter + + #Retrieve query results. Returns all machines to be deleted + $queryResults = $queryService.QueryService_Query($services,$queryDefinition) + + #Assign VM Object to variable + $deleteThisMachine = $queryResults.Results + + if ($Force -or $PSCmdlet.ShouldProcess($deleteThisMachine)) { + + #Machine Service + $machineService = new-object VMware.Hv.MachineService + + #Get Machine Service machine object + $deleteMachine = $machineService.Machine_GetInfos($services,$deleteThisMachine.Id) + + #If sessions exist on the machines we are going to delete than force kill those sessions. + #The deleteMachines method will not work if there are any existing sessions so this step is very important. + write-host "Attempting log off of machines" + + if($deleteMachine.base.session.id){ + $trys = 0 + + do{ + + foreach($session in $deleteMachine.base.session){ + + $sessions = $null + [VMware.Hv.SessionId[]]$sessions += $session + + } + + try{ + + write-host "`n" + write-host "Attempting log off of machines" + write-host "`n" + $logOffSession = new-object 'VMware.Hv.SessionService' + $logOffSession.Session_LogoffSessionsForced($services,$sessions) + + #Wait more for Sessions to end + Start-Sleep -Seconds 5 + + } + + catch{ + + Write-Host "Attempted to Log Off Sessions from below machines but recieved an error. This doesn't usually mean it failed. Typically the session is succesfully logged off but takes some time" + write-host "`n" + write-host ($deleteMachine.base.Name -join "`n") + + start-sleep -seconds 5 + + } + + if(($trys -le 10)){ + + write-host "`n" + write-host "Retrying Logoffs: $trys times" + #Recheck existing sessions + $deleteMachine = $machineService.Machine_GetInfos($services,$deleteThisMachine.Id) + + } + + $trys++ } - $trys++ + until((!$deleteMachine.base.session.id) -or ($trys -gt 10)) + } + + #Create delete spec for the DeleteMachines method + $deleteSpec = [VMware.Hv.MachineDeleteSpec]::new() + $deleteSpec.DeleteFromDisk = $DeleteFromDisk + $deleteSpec.ArchivePersistentDisk = $false + + #Delete the machines + if($DeleteFromDisk){write-host "Attempting to Delete:"}else{write-host "Attempting to remove from inventory:"} + Write-Output ($deleteMachine.base.Name -join "`n") + $machineService.Machine_DeleteMachines($services,$deleteMachine.id,$deleteSpec) } - - until((!$deleteMachine.base.session.id) -or ($trys -gt 10)) - -} - -#Create delete spec for the DeleteMachines method -$deleteSpec = [VMware.Hv.MachineDeleteSpec]::new() -$deleteSpec.DeleteFromDisk = $DeleteFromDisk -$deleteSpec.ArchivePersistentDisk = $false - -#Delete the machines -if($DeleteFromDisk){write-host "Attempting to Delete:"}else{write-host "Attempting to remove from inventory:"} -Write-Output ($deleteMachine.base.Name -join "`n") -$bye = $machineService.Machine_DeleteMachines($services,$deleteMachine.id,$deleteSpec) - -[System.gc]::collect() - + } + End { + [System.gc]::collect() + } } function Get-HVHealth { @@ -10610,10 +10596,7 @@ function Get-HVHealth { PowerShell Version : 5.0 #> - [CmdletBinding( - SupportsShouldProcess = $true, - ConfirmImpact = 'High' - )] + [CmdletBinding()] param( @@ -10772,7 +10755,7 @@ function remove-hvpodfederation { [System.gc]::collect() } -function get-hvpodfederation { +function Get-HVPodFederation { <# .Synopsis Returns information about a Horizon View Pod Federation (Cloud Pod Architecture) @@ -10785,7 +10768,7 @@ function get-hvpodfederation { first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE - get-hvpodfederation + Get-HVPodFederation Returns information about a Horizon View Pod Federation .NOTES @@ -10801,7 +10784,7 @@ function get-hvpodfederation { [CmdletBinding( SupportsShouldProcess = $false, - ConfirmImpact = 'High' + ConfirmImpact = 'None' )] param( @@ -11053,7 +11036,7 @@ function set-hvpodfederation { $podservicehelper=$podservice.read($services) $podservicehelper.getDatahelper().setdisplayname($name) $podservice.update($services, $podservicehelper) - get-hvpodfederation + Get-HVPodFederation [System.gc]::collect() } @@ -11480,7 +11463,6 @@ function New-HVHomeSite { } process { - $confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys $groupinfo = Get-UserInfo -UserName $Group $UserOrGroupName = $groupinfo.Name $Domain = $groupinfo.Domain From 0cfbf635e703bb05d6a989319d6badc0812ec3f2 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Tue, 6 Aug 2019 17:11:36 -0500 Subject: [PATCH 125/175] Resolved issue with Get-HVEntitlement for user --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 0b0b3bf..bc3a26b 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -8384,10 +8384,10 @@ function Get-HVEntitlement { $userInfo = Get-UserInfo -UserName $User $UserOrGroupName = $userInfo.Name $Domain = $userInfo.Domain - $nameFilter = Get-HVQueryFilter 'base.name' -Eq $UserOrGroupName + $nameFilter = Get-HVQueryFilter 'base.loginName' -Eq $UserOrGroupName $AndFilter += $nameFilter - $doaminFilter = Get-HVQueryFilter 'base.domain' -Eq $Domain - $AndFilter += $doaminFilter + $domainFilter = Get-HVQueryFilter 'base.domain' -Eq $Domain + $AndFilter += $domainFilter } if ($type -eq 'group'){ $IsGroup = ($Type -eq 'Group') From db5cd609165e0a80675f0dc95800a43e4f022a58 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Wed, 7 Aug 2019 13:02:42 -0500 Subject: [PATCH 126/175] Improved New-HVPreinstalledApplication --- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 61 ++++++++++++------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index bc3a26b..f5921d6 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -12043,7 +12043,11 @@ Function Remove-HVApplication { PowerCLI Version : PowerCLI 11.1 PowerShell Version : 5.0 #> - param ( +[CmdletBinding( + SupportsShouldProcess = $true, + ConfirmImpact = 'High' +)] +param ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [string]$ApplicationName, @@ -12064,9 +12068,11 @@ Function Remove-HVApplication { return } $AppService= New-Object VMware.Hv.ApplicationService - $AppService.Application_Delete($services,$App.Id) - if ($?) { - Write-Host "'$ApplicationName' has been successfully removed." + if ($pscmdlet.ShouldProcess($ApplicationName)) { + $AppService.Application_Delete($services,$App.Id) + if ($?) { + Write-Host "'$ApplicationName' has been successfully removed." + } } } end { @@ -12343,10 +12349,13 @@ Function New-HVPreInstalledApplication { View API service object of Connect-HVServer cmdlet. .PARAMETER ApplicationName - The Application name is the unique identifier used to identify this Application. + The Application name to search within the Farm for. This should match the output of (Get-HVPreinstalledApplication).Name + +.PARAMETER ApplicationID + The unique identifier for this application. The ApplicationID can only contain alphanumeric characters, dashes, and underscores. If ApplicationID is not specified, it will be set to match the ApplicationName, with the spaces converted to underscore (_). .PARAMETER DisplayName - The display name is the name that users will see when they connect to view client. If the display name is left blank, it defaults to Name. + The display name is the name that users will see when they connect with the Horizon Client. If the display name is left blank, it defaults to ApplicationName. .PARAMETER FarmName Farm name. @@ -12364,12 +12373,16 @@ Function New-HVPreInstalledApplication { Client restrictions to be applied to Application. Currently it is valid for RDSH pools. .EXAMPLE - New-HVPreInstalledApplication -ApplicationName 'App1' -DisplayName 'DisplayName' -FarmName 'FarmName' - Creates a application App1 from the farm specified. + New-HVPreInstalledApplication -ApplicationName 'App1' -DisplayName 'DisplayName' -FarmName 'FarmName' + Creates a application App1 from the farm specified. .EXAMPLE - New-HVPreInstalledApplication -ApplicationName 'App2' -FarmName FarmManual -EnablePreLaunch $True - Creates a application App2 from the farm specified and the PreLaunch option will be enabled. + New-HVPreInstalledApplication -ApplicationName 'App2' -FarmName FarmManual -EnablePreLaunch $True + Creates a application App2 from the farm specified and the PreLaunch option will be enabled. + +.EXAMPLE + New-HVPreInstalledApplication -ApplicationName 'Excel 2016' -ApplicationID 'Excel-2016' -DisplayName 'Excel' -FarmName 'RDS-FARM-01' + Creates an application, Excel-2016, from the farm RDS-FARM-01. The application will display as 'Excel' to the end user. .OUTPUTS A success message is displayed when done. @@ -12385,12 +12398,12 @@ Function New-HVPreInstalledApplication { PowerShell Version : 5.0 #> param ( - [Parameter(Mandatory = $False)] - $HvServer = $null, - [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [string][ValidateLength(1,64)]$ApplicationName, + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] + [string][ValidateLength(1,64)][ValidatePattern('(?#Alphanumeric, dashes,and underscores)^[a-zA-Z\d-_]+$')]$ApplicationID = $($ApplicationName -replace " ","_"), + [Parameter(Mandatory = $False, ValueFromPipeline = $True)] [String][ValidateLength(1,256)]$DisplayName = $ApplicationName, @@ -12407,7 +12420,10 @@ Function New-HVPreInstalledApplication { [String][ValidateRange(1,64)]$CategoryFolderName, [Parameter(Mandatory = $False, ValueFromPipeline = $True)] - [Boolean]$clientRestrictions = $False + [Boolean]$clientRestrictions = $False, + + [Parameter(Mandatory = $False)] + $HvServer = $null ) begin { $services = Get-ViewAPIService -HvServer $HvServer @@ -12424,17 +12440,17 @@ Function New-HVPreInstalledApplication { process { #Validate the Application name uniqueness with existing applications. $ResourceObjs = Get-HVApplication -HvServer $HvServer - foreach($App in ($ResourceObjs.name)) { - if($App -eq $ApplicationName) { - Write-Host "$ApplicationName already exists in the Application Pool." + foreach($App in ($ResourceObjs.Data.Name)) { + if($App -eq $ApplicationID) { + Write-Error "$ApplicationID already exists in the Application Pool. Use the -ApplicationID parameter to specify a unique ID." return } } #Validate the application name uniqueness with Desktops. $DesktopSummary = Get-HVQueryResult -EntityType DesktopSummaryView -HvServer $hvserver foreach($App in $DesktopSummary) { - if($App.DesktopSummaryData.Name -eq $ApplicationName) { - Write-Host "$ApplicationName already exists in the Desktop Pool." + if($App.DesktopSummaryData.Data.Name -eq $ApplicationID) { + Write-Error "$ApplicationID already exists in the Desktop Pool. Use the -ApplicationID parameter to specify a unique ID." return } } @@ -12444,7 +12460,6 @@ Function New-HVPreInstalledApplication { foreach($App in ($AppsInRDS)) { if($($App.name) -eq ($ApplicationName)) { $AppFoundInRDS = $True - $ApplicationID = $ApplicationName -replace " ","_" $ApplicationData = New-Object VMware.Hv.ApplicationData -Property @{ 'Name' = $ApplicationID; 'DisplayName' = $DisplayName; 'EnablePreLaunch' = $EnablePreLaunch; @@ -12463,15 +12478,15 @@ Function New-HVPreInstalledApplication { $AppService = New-Object VMware.Hv.ApplicationService $AppService.Application_Create($services,$ApplicationSpec) if($?) { - Write-Host "Application '$ApplicationName' created successfully" + Write-Host "Application '$ApplicationId' created successfully" return } - Write-Host "Failed to create Application '$ApplicationName'. $_ " + Write-Host "Failed to create Application '$ApplicationId'. $_ " return } } if ($AppFoundInRDS -eq $False) { - Write-Host ""$ApplicationName" does not exist in any of the RDS Server(s) belongs to the Farm $FarmName." + Write-Error "$ApplicationName does not exist in any of the RDS Server(s) belongs to the Farm $FarmName. Run (Get-HVPreinstalledApplication -FarmName $FarmName).Name to see a list of valid, preinstalled applications." } } end { From 5325596b2fab2bbfeddb957f525ba74d76ccd9ce Mon Sep 17 00:00:00 2001 From: seanpmassey Date: Wed, 7 Aug 2019 15:17:43 -0500 Subject: [PATCH 127/175] Delete VMware.VMC.psm1 --- Modules/VMware.VMC/VMware.VMC.psm1 | 865 ----------------------------- 1 file changed, 865 deletions(-) delete mode 100644 Modules/VMware.VMC/VMware.VMC.psm1 diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 deleted file mode 100644 index 91b7cff..0000000 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ /dev/null @@ -1,865 +0,0 @@ -Function Get-VMCCommand { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Returns all cmdlets for VMware Cloud on AWS - .DESCRIPTION - This cmdlet will allow you to return all cmdlets included in the VMC module - .EXAMPLE - Get-VMCCommand - .EXAMPLE - Get-Command -Module VMware.VMC - .NOTES - You can either use this cmdlet or the Get-Command cmdlet as seen in Example 2 -#> - Get-command -Module VMware.VimAutomation.Vmc - Get-Command -Module VMware.VMC - -} -Function Connect-VMCVIServer { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Cmdlet to connect to your VMC vCenter Server - .DESCRIPTION - This will connect you to both the VMC ViServer as well as the CiSServer at the same time. - .EXAMPLE - Connect-VMCVIServer -Server -User -Password - .NOTES - Easiest way is to pipe through your credentials from Get-VMCSDDCDefaultCredential -#> - Param ( - [Parameter(Mandatory=$true)]$Org, - [Parameter(Mandatory=$true)]$Sddc, - [switch]$Autologin, - [switch]$UseManagementIP - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $creds = Get-VMCSDDCDefaultCredential -Org $Org -Sddc $Sddc - If($UseManagementIP){ - $Server = $creds.vc_management_ip - }Else{ - $Server = $creds.vc_public_ip - } - - Write-Host "Connecting to VMC vCenter Server" $Server - Connect-VIServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" - Write-Host "Connecting to VMC CIS Endpoint" $Server - Connect-CisServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" - } -} -Function Get-VMCOrg { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Return the Orgs that you are a part of - .DESCRIPTION - Depending on what you've purchased, you may be a part of one or more VMC Orgs. This will return your orgs - .EXAMPLE - Get-VMCOrg - .EXAMPLE - Get-VMCOrg -Name - .NOTES - Return all the info about the orgs you are a part of -#> - Param ( - [Parameter(Mandatory=$false)]$Name - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use Connect-VMC to connect" } Else { - $orgService = Get-VMCService com.vmware.vmc.orgs - if ($PSBoundParameters.ContainsKey("Name")){ - $orgs = $orgService.list() | Where {$_.display_name -match $Name} - } Else { - $orgs = $orgService.list() - } - $Orgs | Select display_name, name, user_name, created, id - } -} -Function Get-VMCSDDC { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Returns all of the SDDCs you are associated to - .DESCRIPTION - Returns all of the SDDCs ayou are associated to - .EXAMPLE - Get-VMCSDDC -Org - .EXAMPLE - Get-VMCSDDC -Name -Org -#> - Param ( - [Parameter(Mandatory=$True)]$Org, - [Parameter(Mandatory=$false)]$Name - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - if ($PSBoundParameters.ContainsKey("Org")){ - $orgs = Get-VMCOrg -Name $Org - } else { - $orgs = Get-VMCOrg - } - - foreach ($org in $orgs) { - $orgID = $org.ID - $sddcService = Get-VMCService com.vmware.vmc.orgs.sddcs - if ($PSBoundParameters.ContainsKey("Name")){ - $sddcService.list($OrgID) | Where {$_.name -match $Name} - } Else { - $sddcService.list($OrgID) - } - } - } -} -Function Get-VMCTask { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Returns all of the VMC Tasks - .DESCRIPTION - Returns all of the VMC Tasks that have either occurred or are in process - .EXAMPLE - Get-VMCTask -#> - Param ( - [Parameter(Mandatory=$True)]$Org - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - if ($PSBoundParameters.ContainsKey("Org")){ - $orgs = Get-VMCOrg -Name $Org - } else { - $orgs = Get-VMCOrg - } - - foreach ($org in $orgs) { - $orgID = $org.ID - $taskService = Get-VMCService com.vmware.vmc.orgs.tasks - $taskService.list($OrgID) | Select * -ExcludeProperty Help - } - } -} -Function Get-VMCSDDCDefaultCredential { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Returns the default credential for the SDDC - .DESCRIPTION - Returns the default credential for the sddc - .EXAMPLE - Get-VMCSDDCDefaultCredential -Org - .EXAMPLE - Get-VMCSDDCDefaultCredential -Sddc -Org -#> - Param ( - [Parameter(Mandatory=$true)]$Org, - [Parameter(Mandatory=$false)]$Sddc - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - if ($PSBoundParameters.ContainsKey("Sddc")){ - $sddcs = Get-VMCSDDC -Name $Sddc -Org $Org - } else { - $sddcs = Get-VMCSDDC -Org $Org - } - - foreach ($sddc in $sddcs) { - $sddc.resource_config | Select-object vc_url, vc_management_ip, vc_public_ip, cloud_username, cloud_password - } - } -} -Function Get-VMCSDDCPublicIP { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Returns your Public IPs - .DESCRIPTION - Returns your Public IPs - .EXAMPLE - Get-VMCSDDCPublicIP -Org - .EXAMPLE - Get-VMCSDDCPublicIP -Sddc -Org - .NOTES - Return your Public IPs that you have assigned to your account -#> - Param ( - [Parameter(Mandatory=$true)]$Org, - [Parameter(Mandatory=$false)]$Sddc - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - if ($PSBoundParameters.ContainsKey("Sddc")){ - $sddcs = Get-VMCSDDC -Name $Sddc -Org $Org - } else { - $sddcs = Get-VMCSDDC -Org $Org - } - - foreach ($sddc in $sddcs) { - $sddc.resource_config.Public_ip_pool - } - } -} -Function Get-VMCVMHost { - Param ( - [Parameter(Mandatory=$false)]$Sddc, - [Parameter(Mandatory=$true)]$Org - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - if ($PSBoundParameters.ContainsKey("Sddc")){ - $sddcs = Get-VMCSDDC -Name $Sddc -Org $Org - } else { - $sddcs = Get-VMCSDDC -Org $Org - } - - $results = @() - foreach ($sddc in $sddcs) { - foreach ($vmhost in $sddc.resource_config.esx_hosts) { - $tmp = [pscustomobject] @{ - esx_id = $vmhost.esx_id; - name = $vmhost.name; - hostname = $vmhost.hostname; - esx_state = $vmhost.esx_state; - sddc_id = $sddc.id; - org_id = $sddc.org_id; - } - $results += $tmp - } - $results - } - } -} -Function Get-VMCSDDCVersion { -<# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== - - .SYNOPSIS - Returns SDDC Version - .DESCRIPTION - Returns Version of the SDDC - .EXAMPLE - Get-VMCSDDCVersion -Name -Org -#> - Param ( - [Parameter(Mandatory=$True)]$Org, - [Parameter(Mandatory=$false)]$Name - ) - - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - if ($PSBoundParameters.ContainsKey("Org")){ - $orgs = Get-VMCOrg -Name $Org - } else { - $orgs = Get-VMCOrg - } - - foreach ($org in $orgs) { - $orgID = $org.ID - $sddcService = Get-VMCService com.vmware.vmc.orgs.sddcs - if ($PSBoundParameters.ContainsKey("Name")){ - ($sddcService.list($OrgID) | Where {$_.name -match $Name}).resource_config.sddc_manifest | Select *version - } Else { - ($sddcService.list($OrgID)).resource_config.sddc_manifest | Select *version - } - } - } -} - -Function Get-VMCFirewallRule { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 11/19/2017 - Organization: VMware - Blog: https://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Retruns VMC Firewall Rules for a given Gateway (MGW or CGW) - .DESCRIPTION - Retruns VMC Firewall Rules for a given Gateway (MGW or CGW) - .EXAMPLE - Get-VMCFirewallRule -OrgName -SDDCName -GatewayType - .EXAMPLE - Get-VMCFirewallRule -OrgName -SDDCName -GatewayType -ShowAll - #> - param( - [Parameter(Mandatory=$false)][String]$SDDCName, - [Parameter(Mandatory=$false)][String]$OrgName, - [Parameter(Mandatory=$false)][Switch]$ShowAll, - [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType - ) - - if($GatewayType -eq "MGW") { - $EdgeId = "edge-1" - } else { - $EdgeId = "edge-2" - } - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config - - $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules - if(-not $ShowAll) { - $firewallRules = $firewallRules | where { $_.rule_type -ne "default_policy" -and $_.rule_type -ne "internal_high" -and $_.name -ne "vSphere Cluster HA" -and $_.name -ne "Outbound Access" } | Sort-Object -Property rule_tag - } else { - $firewallRules = $firewallRules | Sort-Object -Property rule_tag - } - - $results = @() - foreach ($firewallRule in $firewallRules) { - if($firewallRule.source.ip_address.Count -ne 0) { - $source = $firewallRule.source.ip_address - } else { $source = "ANY" } - - if($firewallRule.application.service.protocol -ne $null) { - $protocol = $firewallRule.application.service.protocol - } else { $protocol = "ANY" } - - if($firewallRule.application.service.port -ne $null) { - $port = $firewallRule.application.service.port - } else { $port = "ANY" } - - $tmp = [pscustomobject] @{ - ID = $firewallRule.rule_id; - Name = $firewallRule.name; - Type = $firewallRule.rule_type; - Action = $firewallRule.action; - Protocol = $protocol; - Port = $port; - SourceAddress = $source - DestinationAddress = $firewallRule.destination.ip_address; - } - $results+=$tmp - } - $results - } - - Function Export-VMCFirewallRule { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 11/19/2017 - Organization: VMware - Blog: https://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Exports all "customer" created VMC Firewall Rules to JSON file - .DESCRIPTION - Exports all "customer" created VMC Firewall Rules to JSON file - .EXAMPLE - Export-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" - #> - param( - [Parameter(Mandatory=$false)][String]$SDDCName, - [Parameter(Mandatory=$false)][String]$OrgName, - [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, - [Parameter(Mandatory=$false)][String]$Path - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - if($GatewayType -eq "MGW") { - $EdgeId = "edge-1" - } else { - $EdgeId = "edge-2" - } - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config - - $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules - if(-not $ShowAll) { - $firewallRules = $firewallRules | where { $_.rule_type -ne "default_policy" -and $_.rule_type -ne "internal_high" -and $_.name -ne "vSphere Cluster HA" -and $_.name -ne "Outbound Access" } | Sort-Object -Property rule_tag - } else { - $firewallRules = $firewallRules | Sort-Object -Property rule_tag - } - - $results = @() - $count = 0 - foreach ($firewallRule in $firewallRules) { - if($firewallRule.source.ip_address.Count -ne 0) { - $source = $firewallRule.source.ip_address - } else { - $source = "ANY" - } - - $tmp = [pscustomobject] @{ - Name = $firewallRule.name; - Action = $firewallRule.action; - Protocol = $firewallRule.application.service.protocol; - Port = $firewallRule.application.service.port; - SourcePort = $firewallRule.application.service.source_port; - ICMPType = $firewallRule.application.service.icmp_type; - SourceAddress = $firewallRule.source.ip_address; - DestinationAddress = $firewallRule.destination.ip_address; - Enabled = $firewallRule.enabled; - Logging = $firewallRule.logging_enabled; - } - $count+=1 - $results+=$tmp - } - if($Path) { - Write-Host -ForegroundColor Green "Exporting $count VMC Firewall Rules to $Path ..." - $results | ConvertTo-Json | Out-File $Path - } else { - $results | ConvertTo-Json - } - } - - Function Import-VMCFirewallRule { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 11/19/2017 - Organization: VMware - Blog: https://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Imports VMC Firewall Rules from exported JSON configuration file - .DESCRIPTION - Imports VMC Firewall Rules from exported JSON configuration file - .EXAMPLE - Import-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" - #> - param( - [Parameter(Mandatory=$false)][String]$SDDCName, - [Parameter(Mandatory=$false)][String]$OrgName, - [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, - [Parameter(Mandatory=$false)][String]$Path - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - if($GatewayType -eq "MGW") { - $EdgeId = "edge-1" - } else { - $EdgeId = "edge-2" - } - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules - - $vmcFirewallRulesJSON = Get-Content -Raw $Path | ConvertFrom-Json - - # Create top level Firewall Rules Object - $firewallRules = $firewallService.Help.add.firewall_rules.Create() - # Create top top level Firewall Rule Spec which will be an array of individual Firewall rules as we process them in next section - $ruleSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Create() - - foreach ($vmcFirewallRule in $vmcFirewallRulesJSON) { - # Create Individual Firewall Rule Element Spec - $ruleElementSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.Create() - - # AppSpec - $appSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.application.Create() - # ServiceSpec - $serviceSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.application.service.Element.Create() - - $protocol = $null - if($vmcFirewallRule.Protocol -ne $null) { - $protocol = $vmcFirewallRule.Protocol - } - $serviceSpec.protocol = $protocol - - # Process ICMP Type from JSON - $icmpType = $null - if($vmcFirewallRule.ICMPType -ne $null) { - $icmpType = $vmcFirewallRule.ICMPType - } - $serviceSpec.icmp_type = $icmpType - - # Process Source Ports from JSON - $sourcePorts = @() - if($vmcFirewallRule.SourcePort -eq "any" -or $vmcFirewallRule.SourcePort -ne $null) { - foreach ($port in $vmcFirewallRule.SourcePort) { - $sourcePorts+=$port - } - } else { - $sourcePorts = @("any") - } - $serviceSpec.source_port = $sourcePorts - - # Process Ports from JSON - $ports = @() - if($vmcFirewallRule.Port -ne "null") { - foreach ($port in $vmcFirewallRule.Port) { - $ports+=$port - } - } - $serviceSpec.port = $ports - $addSpec = $appSpec.service.Add($serviceSpec) - - # Create Source Spec - $srcSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.source.Create() - $srcSpec.exclude = $false - # Process Source Address from JSON - $sourceAddess = @() - if($vmcFirewallRule.SourceAddress -ne "null") { - foreach ($address in $vmcFirewallRule.SourceAddress) { - $sourceAddess+=$address - } - } - $srcSpec.ip_address = $sourceAddess; - - # Create Destination Spec - $destSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.destination.Create() - $destSpec.exclude = $false - # Process Destination Address from JSON - $destinationAddess = @() - if($vmcFirewallRule.DestinationAddress -ne "null") { - foreach ($address in $vmcFirewallRule.DestinationAddress) { - $destinationAddess+=$address - } - } - $destSpec.ip_address = $destinationAddess - - # Add various specs - if($vmcFirewallRule.Protocol -ne $null -and $vmcFirewallRule.port -ne $null) { - $ruleElementSpec.application = $appSpec - } - - $ruleElementSpec.source = $srcSpec - $ruleElementSpec.destination = $destSpec - $ruleElementSpec.rule_type = "user" - - # Process Enabled from JSON - $fwEnabled = $false - if($vmcFirewallRule.Enabled -eq "true") { - $fwEnabled = $true - } - $ruleElementSpec.enabled = $fwEnabled - - # Process Logging from JSON - $loggingEnabled = $false - if($vmcFirewallRule.Logging -eq "true") { - $loggingEnabled = $true - } - $ruleElementSpec.logging_enabled = $loggingEnabled - - $ruleElementSpec.action = $vmcFirewallRule.Action - $ruleElementSpec.name = $vmcFirewallRule.Name - - # Add the individual FW rule spec into our overall firewall rules array - Write-host "Creating VMC Firewall Rule Spec:" $vmcFirewallRule.Name "..." - $ruleSpecAdd = $ruleSpec.Add($ruleElementSpec) - } - $firewallRules.firewall_rules = $ruleSpec - - Write-host "Adding VMC Firewall Rules ..." - $firewallRuleAdd = $firewallService.add($orgId,$sddcId,$EdgeId,$firewallRules) - } - - Function Remove-VMCFirewallRule { - <# - .NOTES - =========================================================================== - Created by: William Lam - Date: 11/19/2017 - Organization: VMware - Blog: https://www.virtuallyghetto.com - Twitter: @lamw - =========================================================================== - - .SYNOPSIS - Removes VMC Firewall Rule given Rule Id - .DESCRIPTION - Removes VMC Firewall Rule given Rule Id - .EXAMPLE - Remove-VMCFirewallRule -OrgName -SDDCName -GatewayType -RuleId - #> - param( - [Parameter(Mandatory=$false)][String]$SDDCName, - [Parameter(Mandatory=$false)][String]$OrgName, - [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, - [Parameter(Mandatory=$false)][String]$RuleId - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - if($GatewayType -eq "MGW") { - $EdgeId = "edge-1" - } else { - $EdgeId = "edge-2" - } - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules - Write-Host "Removing VMC Firewall Rule Id $RuleId ..." - $firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId) - } - -Function Get-VMCLogicalNetwork { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/06/2018 - Organization: VMware - Blog: https://thatcouldbeaproblem.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Retruns VMC Logical Networks for a given SDDC - .DESCRIPTION - Retruns VMC Logical Networks for a given SDDC - .EXAMPLE - Get-VMCLogicalNetwork -OrgName -SDDCName - .EXAMPLE - Get-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName - #> - param( - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$false)][String]$LogicalNetworkName - - ) - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical - - $logicalNetworks = ($logicalNetworkService.get_0($orgId, $sddcId)).data | Sort-Object -Property id - - if($LogicalNetworkName) { - $logicalNetworks = $logicalNetworks | Where-Object {$_.Name -eq $LogicalNetworkName} - } - - $results = @() - foreach ($logicalNetwork in $logicalNetworks) { - $tmp = [pscustomobject] @{ - ID = $logicalNetwork.id; - Name = $logicalNetwork.name; - SubnetMask = $logicalNetwork.subnets.address_groups.prefix_length; - Gateway = $logicalNetwork.subnets.address_groups.primary_address; - DHCPipRange = $logicalNetwork.dhcp_configs.ip_pools.ip_range; - DHCPdomain = $logicalNetwork.dhcp_configs.ip_pools.domain_name; - CGatewayID = $logicalNetwork.cgw_id; - CGateway = $logicalNetwork.cgw_name; - } - $results+=$tmp - } - $results -} - -Function Remove-VMCLogicalNetwork { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/06/2018 - Organization: VMware - Blog: https://thatcouldbeaproblem.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Removes Logical Network given ID - .DESCRIPTION - Removes Logical Network given ID - .EXAMPLE - Remove-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$LogicalNetworkName - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - $lsId = (Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName).Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - if(-not $lsId) { - Write-Host -ForegroundColor red "Unable to find SDDC $LogicalNetworkName, please verify input" - break - } - - $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical - $logicalNetworkService.delete($orgId,$sddcId,$lsId) -} - -Function New-VMCLogicalNetwork { - <# - .NOTES - =========================================================================== - Created by: Kyle Ruddy - Date: 03/06/2018 - Organization: VMware - Blog: https://thatcouldbeaproblem.com - Twitter: @kmruddy - =========================================================================== - - .SYNOPSIS - Creates a new Logical Network - .DESCRIPTION - Creates a new Logical Network - .EXAMPLE - New-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName -SubnetMask -Gateway - #> - [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] - param( - [Parameter(Mandatory=$true)][String]$SDDCName, - [Parameter(Mandatory=$true)][String]$OrgName, - [Parameter(Mandatory=$true)][String]$LogicalNetworkName, - [Parameter(Mandatory=$true)][String]$SubnetMask, - [Parameter(Mandatory=$true)][String]$Gateway - ) - - if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } - - $orgId = (Get-VMCOrg -Name $OrgName).Id - $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id - - if(-not $orgId) { - Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" - break - } - if(-not $sddcId) { - Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" - break - } - - $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical - $logicalNetworkSpec = $logicalNetworkService.Help.create.sddc_network.Create() - $logicalNetworkSpec.name = $LogicalNetworkName - $logicalNetworkSpec.cgw_id = "edge-2" - $logicalNetworkSpec.cgw_name = "SDDC-CGW-1" - $logicalNetworkAddressGroupSpec = $logicalNetworkService.Help.create.sddc_network.subnets.address_groups.Element.Create() - $logicalNetworkAddressGroupSpec.prefix_length = $SubnetMask - $logicalNetworkAddressGroupSpec.primary_address = $Gateway - - $logicalNetworkSpec.subnets.address_groups.Add($logicalNetworkAddressGroupSpec) | Out-Null - $logicalNetworkService.create($orgId, $sddcId, $logicalNetworkSpec) - Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName -} - -Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork' \ No newline at end of file From 2c79a86531df8c20a51041185db34d68fd42cb85 Mon Sep 17 00:00:00 2001 From: seanpmassey Date: Wed, 7 Aug 2019 15:22:51 -0500 Subject: [PATCH 128/175] Create VMware.VMC.psm1 --- Modules/VMware.VMC/VMware.VMC.psm1 | 1629 ++++++++++++++++++++++++++++ 1 file changed, 1629 insertions(+) create mode 100644 Modules/VMware.VMC/VMware.VMC.psm1 diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 new file mode 100644 index 0000000..dd74f2a --- /dev/null +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -0,0 +1,1629 @@ +Function Get-VMCCommand { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Returns all cmdlets for VMware Cloud on AWS + .DESCRIPTION + This cmdlet will allow you to return all cmdlets included in the VMC module + .EXAMPLE + Get-VMCCommand + .EXAMPLE + Get-Command -Module VMware.VMC + .NOTES + You can either use this cmdlet or the Get-Command cmdlet as seen in Example 2 +#> + Get-command -Module VMware.VimAutomation.Vmc + Get-Command -Module VMware.VMC + +} +Function Connect-VMCVIServer { + <# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Cmdlet to connect to your VMC vCenter Server + .DESCRIPTION + This will connect you to both the VMC ViServer as well as the CiSServer at the same time. + .EXAMPLE + Connect-VMCVIServer -Server -User -Password + .NOTES + Easiest way is to pipe through your credentials from Get-VMCSDDCDefaultCredential + #> + Param ( + [Parameter(Mandatory=$true)]$Org, + [Parameter(Mandatory=$true)]$Sddc, + [switch]$Autologin, + [switch]$UseManagementIP + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $creds = Get-VMCSDDCDefaultCredential -Org $Org -Sddc $Sddc + If($UseManagementIP){ + $Server = $creds.vc_management_ip + }Else{ + $Server = $creds.vc_public_ip + } + + Write-Host "Connecting to VMC vCenter Server" $Server + Connect-VIServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" + Write-Host "Connecting to VMC CIS Endpoint" $Server + Connect-CisServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" + } + } +Function Get-VMCOrg { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Return the Orgs that you are a part of + .DESCRIPTION + Depending on what you've purchased, you may be a part of one or more VMC Orgs. This will return your orgs + .EXAMPLE + Get-VMCOrg + .EXAMPLE + Get-VMCOrg -Name + .NOTES + Return all the info about the orgs you are a part of +#> + Param ( + [Parameter(Mandatory=$false)]$Name + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use Connect-VMC to connect" } Else { + $orgService = Get-VMCService com.vmware.vmc.orgs + if ($PSBoundParameters.ContainsKey("Name")){ + $orgs = $orgService.list() | Where {$_.display_name -eq $Name} + } Else { + $orgs = $orgService.list() + } + $Orgs | Select display_name, name, user_name, created, id + } +} +Function Get-VMCSDDC { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Returns all of the SDDCs you are associated to + .DESCRIPTION + Returns all of the SDDCs ayou are associated to + .EXAMPLE + Get-VMCSDDC -Org + .EXAMPLE + Get-VMCSDDC -Name -Org +#> + Param ( + [Parameter(Mandatory=$True)]$Org, + [Parameter(Mandatory=$false)]$Name + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + if ($PSBoundParameters.ContainsKey("Org")){ + $orgs = Get-VMCOrg -Name $Org + } else { + $orgs = Get-VMCOrg + } + + foreach ($org in $orgs) { + $orgID = $org.ID + $sddcService = Get-VMCService com.vmware.vmc.orgs.sddcs + if ($PSBoundParameters.ContainsKey("Name")){ + $sddcService.list($OrgID) | Where {$_.name -eq $Name} + } Else { + $sddcService.list($OrgID) + } + } + } +} +Function Get-VMCTask { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Returns all of the VMC Tasks + .DESCRIPTION + Returns all of the VMC Tasks that have either occurred or are in process + .EXAMPLE + Get-VMCTask +#> + Param ( + [Parameter(Mandatory=$True)]$Org + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + if ($PSBoundParameters.ContainsKey("Org")){ + $orgs = Get-VMCOrg -Name $Org + } else { + $orgs = Get-VMCOrg + } + + foreach ($org in $orgs) { + $orgID = $org.ID + $taskService = Get-VMCService com.vmware.vmc.orgs.tasks + $taskService.list($OrgID) | Select * -ExcludeProperty Help + } + } +} +Function Get-VMCSDDCDefaultCredential { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Returns the default credential for the SDDC + .DESCRIPTION + Returns the default credential for the sddc + .EXAMPLE + Get-VMCSDDCDefaultCredential -Org + .EXAMPLE + Get-VMCSDDCDefaultCredential -Sddc -Org +#> + Param ( + [Parameter(Mandatory=$true)]$Org, + [Parameter(Mandatory=$false)]$Sddc + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + if ($PSBoundParameters.ContainsKey("Sddc")){ + $sddcs = Get-VMCSDDC -Name $Sddc -Org $Org + } else { + $sddcs = Get-VMCSDDC -Org $Org + } + + foreach ($sddc in $sddcs) { + $sddc.resource_config | Select-object vc_url, vc_management_ip, vc_public_ip, cloud_username, cloud_password + } + } +} +Function Get-VMCSDDCPublicIP { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Returns your Public IPs + .DESCRIPTION + Returns your Public IPs + .EXAMPLE + Get-VMCSDDCPublicIP -Org + .EXAMPLE + Get-VMCSDDCPublicIP -Sddc -Org + .NOTES + Return your Public IPs that you have assigned to your account +#> + Param ( + [Parameter(Mandatory=$true)]$Org, + [Parameter(Mandatory=$false)]$Sddc + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + if ($PSBoundParameters.ContainsKey("Sddc")){ + $sddcs = Get-VMCSDDC -Name $Sddc -Org $Org + } else { + $sddcs = Get-VMCSDDC -Org $Org + } + + foreach ($sddc in $sddcs) { + $sddc.resource_config.Public_ip_pool + } + } +} +Function Get-VMCVMHost { + Param ( + [Parameter(Mandatory=$false)]$Sddc, + [Parameter(Mandatory=$true)]$Org + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + if ($PSBoundParameters.ContainsKey("Sddc")){ + $sddcs = Get-VMCSDDC -Name $Sddc -Org $Org + } else { + $sddcs = Get-VMCSDDC -Org $Org + } + + $results = @() + foreach ($sddc in $sddcs) { + foreach ($vmhost in $sddc.resource_config.esx_hosts) { + $tmp = [pscustomobject] @{ + esx_id = $vmhost.esx_id; + name = $vmhost.name; + hostname = $vmhost.hostname; + esx_state = $vmhost.esx_state; + sddc_id = $sddc.id; + org_id = $sddc.org_id; + } + $results += $tmp + } + $results + } + } +} +Function Get-VMCSDDCVersion { +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== + + .SYNOPSIS + Returns SDDC Version + .DESCRIPTION + Returns Version of the SDDC + .EXAMPLE + Get-VMCSDDCVersion -Name -Org +#> + Param ( + [Parameter(Mandatory=$True)]$Org, + [Parameter(Mandatory=$false)]$Name + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + if ($PSBoundParameters.ContainsKey("Org")){ + $orgs = Get-VMCOrg -Name $Org + } else { + $orgs = Get-VMCOrg + } + + foreach ($org in $orgs) { + $orgID = $org.ID + $sddcService = Get-VMCService com.vmware.vmc.orgs.sddcs + if ($PSBoundParameters.ContainsKey("Name")){ + ($sddcService.list($OrgID) | Where {$_.name -match $Name}).resource_config.sddc_manifest | Select *version + } Else { + ($sddcService.list($OrgID)).resource_config.sddc_manifest | Select *version + } + } + } +} +Function Get-VMCFirewallRule { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 11/19/2017 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retruns VMC Firewall Rules for a given Gateway (MGW or CGW) + .DESCRIPTION + Retruns VMC Firewall Rules for a given Gateway (MGW or CGW) + .EXAMPLE + Get-VMCFirewallRule -OrgName -SDDCName -GatewayType + .EXAMPLE + Get-VMCFirewallRule -OrgName -SDDCName -GatewayType -ShowAll + #> + param( + [Parameter(Mandatory=$false)][String]$SDDCName, + [Parameter(Mandatory=$false)][String]$OrgName, + [Parameter(Mandatory=$false)][Switch]$ShowAll, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType + ) + + if($GatewayType -eq "MGW") { + $EdgeId = "edge-1" + } else { + $EdgeId = "edge-2" + } + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config + + $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules + if(-not $ShowAll) { + $firewallRules = $firewallRules | where { $_.rule_type -ne "default_policy" -and $_.rule_type -ne "internal_high" -and $_.name -ne "vSphere Cluster HA" -and $_.name -ne "Outbound Access" } | Sort-Object -Property rule_tag + } else { + $firewallRules = $firewallRules | Sort-Object -Property rule_tag + } + + $results = @() + foreach ($firewallRule in $firewallRules) { + if($firewallRule.source.ip_address.Count -ne 0) { + $source = $firewallRule.source.ip_address + } else { $source = "ANY" } + + if($firewallRule.application.service.protocol -ne $null) { + $protocol = $firewallRule.application.service.protocol + } else { $protocol = "ANY" } + + if($firewallRule.application.service.port -ne $null) { + $port = $firewallRule.application.service.port + } else { $port = "ANY" } + + $tmp = [pscustomobject] @{ + ID = $firewallRule.rule_id; + Name = $firewallRule.name; + Type = $firewallRule.rule_type; + Action = $firewallRule.action; + Protocol = $protocol; + Port = $port; + SourceAddress = $source + DestinationAddress = $firewallRule.destination.ip_address; + } + $results+=$tmp + } + $results + } +Function Export-VMCFirewallRule { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 11/19/2017 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Exports all "customer" created VMC Firewall Rules to JSON file + .DESCRIPTION + Exports all "customer" created VMC Firewall Rules to JSON file + .EXAMPLE + Export-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" + #> + param( + [Parameter(Mandatory=$false)][String]$SDDCName, + [Parameter(Mandatory=$false)][String]$OrgName, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Parameter(Mandatory=$false)][String]$Path + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + if($GatewayType -eq "MGW") { + $EdgeId = "edge-1" + } else { + $EdgeId = "edge-2" + } + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $firewallConfigService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config + + $firewallRules = ($firewallConfigService.get($orgId, $sddcId, $EdgeId)).firewall_rules.firewall_rules + if(-not $ShowAll) { + $firewallRules = $firewallRules | where { $_.rule_type -ne "default_policy" -and $_.rule_type -ne "internal_high" -and $_.name -ne "vSphere Cluster HA" -and $_.name -ne "Outbound Access" } | Sort-Object -Property rule_tag + } else { + $firewallRules = $firewallRules | Sort-Object -Property rule_tag + } + + $results = @() + $count = 0 + foreach ($firewallRule in $firewallRules) { + if($firewallRule.source.ip_address.Count -ne 0) { + $source = $firewallRule.source.ip_address + } else { + $source = "ANY" + } + + $tmp = [pscustomobject] @{ + Name = $firewallRule.name; + Action = $firewallRule.action; + Protocol = $firewallRule.application.service.protocol; + Port = $firewallRule.application.service.port; + SourcePort = $firewallRule.application.service.source_port; + ICMPType = $firewallRule.application.service.icmp_type; + SourceAddress = $firewallRule.source.ip_address; + DestinationAddress = $firewallRule.destination.ip_address; + Enabled = $firewallRule.enabled; + Logging = $firewallRule.logging_enabled; + } + $count+=1 + $results+=$tmp + } + if($Path) { + Write-Host -ForegroundColor Green "Exporting $count VMC Firewall Rules to $Path ..." + $results | ConvertTo-Json | Out-File $Path + } else { + $results | ConvertTo-Json + } +} +Function Import-VMCFirewallRule { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 11/19/2017 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Imports VMC Firewall Rules from exported JSON configuration file + .DESCRIPTION + Imports VMC Firewall Rules from exported JSON configuration file + .EXAMPLE + Import-VMCFirewallRule -OrgName -SDDCName -GatewayType -Path "C:\Users\lamw\Desktop\VMCFirewallRules.json" + #> + param( + [Parameter(Mandatory=$false)][String]$SDDCName, + [Parameter(Mandatory=$false)][String]$OrgName, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Parameter(Mandatory=$false)][String]$Path + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + if($GatewayType -eq "MGW") { + $EdgeId = "edge-1" + } else { + $EdgeId = "edge-2" + } + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + + $vmcFirewallRulesJSON = Get-Content -Raw $Path | ConvertFrom-Json + + # Create top level Firewall Rules Object + $firewallRules = $firewallService.Help.add.firewall_rules.Create() + # Create top top level Firewall Rule Spec which will be an array of individual Firewall rules as we process them in next section + $ruleSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Create() + + foreach ($vmcFirewallRule in $vmcFirewallRulesJSON) { + # Create Individual Firewall Rule Element Spec + $ruleElementSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.Create() + + # AppSpec + $appSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.application.Create() + # ServiceSpec + $serviceSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.application.service.Element.Create() + + $protocol = $null + if($vmcFirewallRule.Protocol -ne $null) { + $protocol = $vmcFirewallRule.Protocol + } + $serviceSpec.protocol = $protocol + + # Process ICMP Type from JSON + $icmpType = $null + if($vmcFirewallRule.ICMPType -ne $null) { + $icmpType = $vmcFirewallRule.ICMPType + } + $serviceSpec.icmp_type = $icmpType + + # Process Source Ports from JSON + $sourcePorts = @() + if($vmcFirewallRule.SourcePort -eq "any" -or $vmcFirewallRule.SourcePort -ne $null) { + foreach ($port in $vmcFirewallRule.SourcePort) { + $sourcePorts+=$port + } + } else { + $sourcePorts = @("any") + } + $serviceSpec.source_port = $sourcePorts + + # Process Ports from JSON + $ports = @() + if($vmcFirewallRule.Port -ne "null") { + foreach ($port in $vmcFirewallRule.Port) { + $ports+=$port + } + } + $serviceSpec.port = $ports + $addSpec = $appSpec.service.Add($serviceSpec) + + # Create Source Spec + $srcSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.source.Create() + $srcSpec.exclude = $false + # Process Source Address from JSON + $sourceAddess = @() + if($vmcFirewallRule.SourceAddress -ne "null") { + foreach ($address in $vmcFirewallRule.SourceAddress) { + $sourceAddess+=$address + } + } + $srcSpec.ip_address = $sourceAddess; + + # Create Destination Spec + $destSpec = $firewallService.Help.add.firewall_rules.firewall_rules.Element.destination.Create() + $destSpec.exclude = $false + # Process Destination Address from JSON + $destinationAddess = @() + if($vmcFirewallRule.DestinationAddress -ne "null") { + foreach ($address in $vmcFirewallRule.DestinationAddress) { + $destinationAddess+=$address + } + } + $destSpec.ip_address = $destinationAddess + + # Add various specs + if($vmcFirewallRule.Protocol -ne $null -and $vmcFirewallRule.port -ne $null) { + $ruleElementSpec.application = $appSpec + } + + $ruleElementSpec.source = $srcSpec + $ruleElementSpec.destination = $destSpec + $ruleElementSpec.rule_type = "user" + + # Process Enabled from JSON + $fwEnabled = $false + if($vmcFirewallRule.Enabled -eq "true") { + $fwEnabled = $true + } + $ruleElementSpec.enabled = $fwEnabled + + # Process Logging from JSON + $loggingEnabled = $false + if($vmcFirewallRule.Logging -eq "true") { + $loggingEnabled = $true + } + $ruleElementSpec.logging_enabled = $loggingEnabled + + $ruleElementSpec.action = $vmcFirewallRule.Action + $ruleElementSpec.name = $vmcFirewallRule.Name + + # Add the individual FW rule spec into our overall firewall rules array + Write-host "Creating VMC Firewall Rule Spec:" $vmcFirewallRule.Name "..." + $ruleSpecAdd = $ruleSpec.Add($ruleElementSpec) + } + $firewallRules.firewall_rules = $ruleSpec + + Write-host "Adding VMC Firewall Rules ..." + $firewallRuleAdd = $firewallService.add($orgId,$sddcId,$EdgeId,$firewallRules) +} +Function Remove-VMCFirewallRule { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 11/19/2017 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes VMC Firewall Rule given Rule Id + .DESCRIPTION + Removes VMC Firewall Rule given Rule Id + .EXAMPLE + Remove-VMCFirewallRule -OrgName -SDDCName -GatewayType -RuleId + #> + param( + [Parameter(Mandatory=$false)][String]$SDDCName, + [Parameter(Mandatory=$false)][String]$OrgName, + [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, + [Parameter(Mandatory=$false)][String]$RuleId + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + if($GatewayType -eq "MGW") { + $EdgeId = "edge-1" + } else { + $EdgeId = "edge-2" + } + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $firewallService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.edges.firewall.config.rules + Write-Host "Removing VMC Firewall Rule Id $RuleId ..." + $firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId) +} +Function Get-VMCLogicalNetwork { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/06/2018 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Retruns VMC Logical Networks for a given SDDC + .DESCRIPTION + Retruns VMC Logical Networks for a given SDDC + .EXAMPLE + Get-VMCLogicalNetwork -OrgName -SDDCName + .EXAMPLE + Get-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName + #> + param( + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$false)][String]$LogicalNetworkName + + ) + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + # @LucD22 - 21/10/18 - Fix for issue #176 VMware.VMC module only lists firts 20 Logical networks + # Loop until entries (total_count) are returned + + $index = [long]0 + + $logicalNetworks = do{ + $netData = $logicalNetworkService.get_0($orgId,$sddcId,$pagesize,$index) + $netData.data | Sort-Object -Property id + $index = $index + $netdata.paging_info.page_size + } + until($index -ge $netData.paging_info.total_count) + + if($LogicalNetworkName) { + $logicalNetworks = $logicalNetworks | Where-Object {$_.Name -eq $LogicalNetworkName} + } + + $results = @() + foreach ($logicalNetwork in $logicalNetworks) { + $tmp = [pscustomobject] @{ + ID = $logicalNetwork.id; + Name = $logicalNetwork.name; + SubnetMask = $logicalNetwork.subnets.address_groups.prefix_length; + Gateway = $logicalNetwork.subnets.address_groups.primary_address; + DHCPipRange = $logicalNetwork.dhcp_configs.ip_pools.ip_range; + DHCPdomain = $logicalNetwork.dhcp_configs.ip_pools.domain_name; + CGatewayID = $logicalNetwork.cgw_id; + CGateway = $logicalNetwork.cgw_name; + } + $results+=$tmp + } + $results +} +Function Remove-VMCLogicalNetwork { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/06/2018 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Removes Logical Network given ID + .DESCRIPTION + Removes Logical Network given ID + .EXAMPLE + Remove-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$LogicalNetworkName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $lsId = (Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName).Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + if(-not $lsId) { + Write-Host -ForegroundColor red "Unable to find SDDC $LogicalNetworkName, please verify input" + break + } + + $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical + $logicalNetworkService.delete($orgId,$sddcId,$lsId) +} +Function New-VMCLogicalNetwork { +<# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/06/2018 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new Logical Network + .DESCRIPTION + Creates a new Logical Network + .EXAMPLE + New-VMCLogicalNetwork -OrgName -SDDCName -LogicalNetworkName -SubnetMask -Gateway +#> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$LogicalNetworkName, + [Parameter(Mandatory=$true)][String]$SubnetMask, + [Parameter(Mandatory=$true)][String]$Gateway + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical + $logicalNetworkSpec = $logicalNetworkService.Help.create.sddc_network.Create() + $logicalNetworkSpec.name = $LogicalNetworkName + $logicalNetworkSpec.cgw_id = "edge-2" + $logicalNetworkSpec.cgw_name = "SDDC-CGW-1" + $logicalNetworkAddressGroupSpec = $logicalNetworkService.Help.create.sddc_network.subnets.address_groups.Element.Create() + $logicalNetworkAddressGroupSpec.prefix_length = $SubnetMask + $logicalNetworkAddressGroupSpec.primary_address = $Gateway + + $logicalNetworkSpec.subnets.address_groups.Add($logicalNetworkAddressGroupSpec) | Out-Null + $logicalNetworkService.create($orgId, $sddcId, $logicalNetworkSpec) + Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName +} +Function Get-VMCSDDCSummary { + <# + .NOTES + =========================================================================== + Created by: VMware + Date: 09/04/18 + Organization: VMware + Blog: https://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Returns a number of useful informational data about a given SDDC within VMC Org + .DESCRIPTION + Returns Version, Create/Expiration Date, Deployment Type, Region, AZ, Instance Type, VPC CIDR & NSX-T + .EXAMPLE + Get-VMCSDDCSummary -Name -Org + #> + Param ( + [Parameter(Mandatory=$True)]$Org, + [Parameter(Mandatory=$True)]$Name + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $Org).Id + $sddcId = (Get-VMCSDDC -Name $Name -Org $Org).Id + + $sddcService = Get-VmcService "com.vmware.vmc.orgs.sddcs" + $sddc = $sddcService.get($orgId,$sddcId) + + $results = [pscustomobject] @{ + Version = $sddc.resource_config.sddc_manifest.vmc_version; + CreateDate = $sddc.created; + ExpirationDate = $sddc.expiration_date; + DeploymentType = $sddc.resource_config.deployment_type; + Region = $sddc.resource_config.region; + AvailabilityZone = $sddc.resource_config.availability_zones; + InstanceType = $sddc.resource_config.sddc_manifest.esx_ami.instance_type; + VpcCIDR = $sddc.resource_config.vpc_info.vpc_cidr; + NSXT = $sddc.resource_config.nsxt; + VPC_VGW = $sddc.resource_config.vpc_info.vgw_id; + } + $results + } +} +Function Get-VMCPublicIP { + <# + .NOTES + =========================================================================== + Created by: William LamVPC_VGW + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves all public IP Addresses for a given SDDC + .DESCRIPTION + This cmdlet retrieves all public IP Address for a given SDDC + .EXAMPLE + Get-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + $publicIPs = $publicIPService.list($orgId,$sddcId) + + $publicIPs | select public_ip, name, allocation_id + } +} + +Function New-VMCPublicIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Request a new public IP Address for a given SDDC + .DESCRIPTION + This cmdlet requests a new public IP Address for a given SDDC + .EXAMPLE + New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$False)]$Description + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + $publicIPSpec = $publicIPService.Help.create.spec.Create() + $publicIPSpec.count = 1 + $publicIPSpec.names = @($Description) + + Write-Host "Requesting a new public IP Address for your SDDC ..." + $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) + } +} + +Function Remove-VMCPublicIP { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes a specific public IP Addresses for a given SDDC + .DESCRIPTION + This cmdlet removes a specific public IP Address for a given SDDC + .EXAMPLE + Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" + #> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$AllocationId + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + Write-Host "Deleting public IP Address with ID $AllocationId ..." + $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + } +} + +Function Set-VMCSDDC { + <# + .NOTES + =========================================================================== + Created by: William Lam + Date: 01/12/2019 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Rename an SDDC + .DESCRIPTION + This cmdlet renames an SDDC + .EXAMPLE + Set-VMCSDDC -SDDC $SDDCName -OrgName $OrgName -Name $NewSDDCName + #> + Param ( + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$Name + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $sddc = Get-VMCSDDC -Org $OrgName -Name $SDDCName + if($sddc) { + $sddcService = Get-VmcService com.vmware.vmc.orgs.sddcs + $renameSpec = $sddcService.help.patch.sddc_patch_request.Create() + $renameSpec.name = $Name + + Write-Host "`nRenaming SDDC `'$SDDCName`' to `'$Name`' ...`n" + $results = $sddcService.patch($sddc.org_id,$sddc.id,$renameSpec) + } + } +} + +Function New-VMCPublicIP { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Request a new public IP Address for a given SDDC + .DESCRIPTION + This cmdlet requests a new public IP Address for a given SDDC + .EXAMPLE + New-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -Description "Test for Randy" +#> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$False)]$Description + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + $publicIPSpec = $publicIPService.Help.create.spec.Create() + $publicIPSpec.count = 1 + $publicIPSpec.names = @($Description) + + Write-Host "Requesting a new public IP Address for your SDDC ..." + $results = $publicIPService.create($orgId,$sddcId,$publicIPSpec) + } +} + +Function Remove-VMCPublicIP { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 09/12/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Removes a specific public IP Addresses for a given SDDC + .DESCRIPTION + This cmdlet removes a specific public IP Address for a given SDDC + .EXAMPLE + Remove-VMCPublicIP -OrgName $OrgName -SDDCName $SDDCName -AllocationId "eipalloc-0567acf34e436c01f" +#> + Param ( + [Parameter(Mandatory=$True)]$OrgName, + [Parameter(Mandatory=$True)]$SDDCName, + [Parameter(Mandatory=$True)]$AllocationId + ) + + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $publicIPService = Get-VmcService "com.vmware.vmc.orgs.sddcs.publicips" + + Write-Host "Deleting public IP Address with ID $AllocationId ..." + $results = $publicIPService.delete($orgId,$sddcId,$AllocationId) + } +} + +Function Get-VMCEdge { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns all the VMC Edges +.DESCRIPTION + Returns all the VMC Edges +.EXAMPLE + Get-VMCEdge -OrgName $orgName -SddcName $SDDCName -EdgeType gatewayServices +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [ValidateSet('gatewayServices','distributedRouter')] + [string]$EdgeType = '' + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + + $edgeService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges' + $index = [long]0 + $edges = do{ + $edgeData = $edgeService.get($orgId,$sddcId,$EdgeType,'',$index) + $edgeData.edge_page.data | Sort-Object -Property id + $index = $index + $edgeData.edge_page.paging_info.page_size + } + until($index -ge $edgeData.paging_info.total_count) + $edges | %{ + [pscustomobject]@{ + Name = $_.Name + Id = $_.id + Type = $_.edge_type + State = $_.state + Status = $_.edge_status + VNics = $_.number_of_connected_vnics + TenantId = $_.tenant_id + } + } + } +} + +Function Get-VMCEdgeStatus { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns the status of the gateway +.DESCRIPTION + Retrieve the status of the specified management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeStatus -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + + $statusService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.status' + $status = $statusService.get($orgId,$sddcId,$edgeId) + + $vmStatus = $status.edge_vm_status | %{ + [pscustomobject]@{ + Name = $_.name + State = $_.edge_VM_status + HAState = $_.ha_state + Index = $_.index + } + } + $featureStatus = $status.feature_statuses | %{ + [pscustomobject]@{ + Service = $_.service + Status = $_.status + } + } + [pscustomobject]@{ + Time = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($status.timestamp/1000)) + Status = $status.edge_status + PublishStatus = $status.publish_status + SystemStatus = $_.system_status + NicInUse = $status.ha_vnic_in_use + } + } +} + +Function Get-VMCEdgeNic { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns all interfaces for the gateway +.DESCRIPTION + Retrieve all interfaces for the specified management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeNic -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + + $vnicService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.vnics' + $vnicService.get($orgId,$sddcId,$edgeId) | select -ExpandProperty vnics | %{ + [pscustomobject]@{ + Label = $_.label + Name = $_.Name + Type = $_.type + Index = $_.index + IsConnected = $_.is_connected + Portgroup = $_.portgroup_name + } + } + } +} + +Function Get-VMCEdgeNicStat { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns statistics for the gateway interfaces +.DESCRIPTION + Retrieve interface statistics for a management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeNicStat -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + [CmdletBinding(DefaultParameterSetName='Default')] + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName +# [DateTime]$Start, +# [DateTime]$Finish + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + +# $epoch = Get-Date 01/01/1970 +# +# if($start){ +# $startEpoch = (New-TimeSpan -Start $epoch -End $Start.ToUniversalTime()).TotalMilliseconds +# } +# if($Finish){ +# $finishEpoch = (New-TimeSpan -Start $epoch -End $Finish.ToUniversalTime()).TotalMilliseconds +# } + + $vnicStatService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.statistics.interfaces' +# $stats = $vnicStatService.get($orgId,$sddcId,$edgeId,[long]$startEpoch,[long]$finishEpoch) + $stats = $vnicStatService.get($orgId,$sddcId,$edgeId) + + $stats.data_dto | Get-Member -MemberType NoteProperty | where{$_.Name -ne 'Help'} | %{$_.Name} | %{ + $stats.data_dto."$_" | %{ + [pscustomobject]@{ + vNIC = $_.vnic + Timestamp = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.timestamp)) + In = $_.in + Out = $_.out + Unit = 'Kbps' + Interval = $stats.meta_dto.interval + } + } + } + } +} + +Function Get-VMCEdgeUplinkStat { +<# +.NOTES +=========================================================================== +Created by: Luc Dekens +Date: 23/10/2018 +Organization: Community +Blog: http://lucd.info +Twitter: @LucD22 +=========================================================================== + +.SYNOPSIS + Returns statistics for the uplink interfaces +.DESCRIPTION + Retrieve uplink interface statistics for a management or compute gateway (NSX Edge). +.EXAMPLE + Get-VMCEdgeUplinkStat -OrgName $orgName -SddcName $SDDCName -Edge $EdgeName +#> + Param ( + [Parameter(Mandatory=$True)] + [string]$OrgName, + [Parameter(Mandatory=$True)] + [string]$SDDCName, + [Parameter(Mandatory=$True)] + [string]$EdgeName +# [DateTime]$Start, +# [DateTime]$Finish + ) + + If (-Not $global:DefaultVMCServers) { + Write-error "No VMC Connection found, please use the Connect-VMC to connect" + } + Else { + $orgId = (Get-VMCOrg -Name $OrgName).Id + $sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id + $edgeId = Get-VMCEdge -SDDCName $SDDCName -Org $OrgName | where{$_.Name -eq $EdgeName} | select -ExpandProperty Id + +# $epoch = Get-Date 01/01/1970 +# +# if($start){ +# $startEpoch = (New-TimeSpan -Start $epoch -End $Start.ToUniversalTime()).TotalMilliseconds +# } +# if($Finish){ +# $finishEpoch = (New-TimeSpan -Start $epoch -End $Finish.ToUniversalTime()).TotalMilliseconds +# } + + $uplinkStatService = Get-VmcService -Name 'com.vmware.vmc.orgs.sddcs.networks.edges.statistics.interfaces.uplink' +# $stats = $uplinkStatService.get($orgId,$sddcId,$edgeId,[long]$startEpoch,[long]$finishEpoch) + $stats = $uplinkStatService.get($orgId,$sddcId,$edgeId) + + $stats.data_dto | Get-Member -MemberType NoteProperty | where{$_.Name -ne 'Help'} | %{$_.Name} | %{ + if($stats.data_dto."$_".Count -ne 0){ + $stats.data_dto."$_" | %{ + [pscustomobject]@{ + vNIC = $_.vnic + Timestamp = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.timestamp)) + In = $_.in + Out = $_.out + Unit = 'Kbps' + Interval = $stats.meta_dto.interval + } + } + } + } + } +} +Function New-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new cluster for the designated SDDC + .DESCRIPTION + Creates a new cluster + .EXAMPLE + New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][Int]$HostCount, + [Parameter(Mandatory=$true)][ValidateSet("8","16","32")]$CPUCoreCount + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters + + $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() + $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount + $sddcClusterCreateSpec.num_hosts = $HostCount + + $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} +Function Get-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Retreives cluster information for the designated SDDC + .DESCRIPTION + Lists cluster information for an SDDC + .EXAMPLE + Get-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='Low')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SddcName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $clusterOutput = @() + $sddcClusters = Get-VMCSDDC -Org $OrgName -Name $SDDCName | Select-Object -ExpandProperty resource_config | Select-Object -ExpandProperty clusters + foreach ($c in $sddcClusters) { + $tempCluster = "" | Select-Object Id, Name, State + $tempCluster.Id = $c.cluster_id + $tempCluster.Name = $c.cluster_name + $tempCluster.State = $c.cluster_state + $clusterOutput += $tempCluster + } + return $clusterOutput +} +Function New-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Creates a new cluster for the designated SDDC + .DESCRIPTION + Creates a new cluster + .EXAMPLE + New-VMCSDDCCluster -OrgName -SDDCName -HostCount 1 -CPUCoreCount 8 + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SddcName, + [Parameter(Mandatory=$true)][Int]$HostCount, + [Parameter(Mandatory=$false)][ValidateSet("8","16","36","48")]$CPUCoreCount + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + + $sddcClusterSvc = Get-VmcService -Name com.vmware.vmc.orgs.sddcs.clusters + + $sddcClusterCreateSpec = $sddcClusterSvc.Help.create.cluster_config.Create() + $sddcClusterCreateSpec.host_cpu_cores_count = $CPUCoreCount + $sddcClusterCreateSpec.num_hosts = $HostCount + + $sddcClusterTask = $sddcClusterSvc.Create($org.Id, $sddc.Id, $sddcClusterCreateSpec) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} +Function Remove-VMCSDDCCluster { + <# + .NOTES + =========================================================================== + Created by: Kyle Ruddy + Date: 03/16/2019 + Organization: VMware + Blog: https://www.kmruddy.com + Twitter: @kmruddy + =========================================================================== + + .SYNOPSIS + Removes a specified cluster from the designated SDDC + .DESCRIPTION + Deletes a cluster from an SDDC + .EXAMPLE + Remove-VMCSDDCCluster -OrgName -SDDCName -Cluster + #> + [cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')] + param( + [Parameter(Mandatory=$true)][String]$OrgName, + [Parameter(Mandatory=$true)][String]$SDDCName, + [Parameter(Mandatory=$true)][String]$ClusterName + ) + + if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break } + + $orgId = Get-VMCOrg -Name $OrgName | Select-Object -ExpandProperty Id + $sddcId = Get-VMCSDDC -Name $SDDCName -Org $OrgName | Select-Object -ExpandProperty Id + $clusterId = Get-VMCSDDCCluster -SddcName $SDDCName -OrgName $OrgName | Where-Object {$_.Name -eq $ClusterName} | Select-Object -ExpandProperty Id + + if(-not $orgId) { + Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input" + break + } + if(-not $sddcId) { + Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input" + break + } + if(-not $clusterId) { + Write-Host -ForegroundColor red "Unable to find cluster $ClusterName, please verify input" + break + } + + $sddcClusterTask = $sddcClusterSvc.Delete($orgId, $sddcId, $clusterId) + $sddcClusterTask | Select-Object Id,Task_Type,Status,Created | Format-Table +} + +Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', + 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', + 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', + 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork', + 'Get-VMCSDDCSummary', 'Get-VMCPublicIP', 'New-VMCPublicIP', 'Remove-VMCPublicIP', 'Set-VMCSDDC', + 'Get-VMCEdge', 'Get-VMCEdgeNic', 'Get-VMCEdgeStatus', 'Get-VMCEdgeNicStat', 'Get-VMCEdgeUplinkStat', + 'Get-VMCSDDCCluster', 'New-VMCSDDCCluster', 'Remove-VMCSDDCCluster' \ No newline at end of file From 0ba0b870afcadecfaeb0baa5fd8fc20cb55f5c8c Mon Sep 17 00:00:00 2001 From: seanpmassey Date: Wed, 7 Aug 2019 15:27:37 -0500 Subject: [PATCH 129/175] Update VMware.VMC.psm1 --- Modules/VMware.VMC/VMware.VMC.psm1 | 73 +++++++++++++++--------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/Modules/VMware.VMC/VMware.VMC.psm1 b/Modules/VMware.VMC/VMware.VMC.psm1 index dd74f2a..7914c64 100644 --- a/Modules/VMware.VMC/VMware.VMC.psm1 +++ b/Modules/VMware.VMC/VMware.VMC.psm1 @@ -25,46 +25,47 @@ Function Get-VMCCommand { } Function Connect-VMCVIServer { - <# - .NOTES - =========================================================================== - Created by: VMware - Date: 11/17/2017 - Organization: VMware - Blog: http://vmware.com/go/powercli - Twitter: @powercli - =========================================================================== +<# + .NOTES + =========================================================================== + Created by: VMware + Date: 11/17/2017 + Organization: VMware + Blog: http://vmware.com/go/powercli + Twitter: @powercli + =========================================================================== - .SYNOPSIS - Cmdlet to connect to your VMC vCenter Server - .DESCRIPTION - This will connect you to both the VMC ViServer as well as the CiSServer at the same time. - .EXAMPLE - Connect-VMCVIServer -Server -User -Password - .NOTES - Easiest way is to pipe through your credentials from Get-VMCSDDCDefaultCredential - #> - Param ( - [Parameter(Mandatory=$true)]$Org, - [Parameter(Mandatory=$true)]$Sddc, - [switch]$Autologin, - [switch]$UseManagementIP - ) + .SYNOPSIS + Cmdlet to connect to your VMC vCenter Server + .DESCRIPTION + This will connect you to both the VMC ViServer as well as the CiSServer at the same time. + .EXAMPLE + Connect-VMCVIServer -Server -User -Password + .NOTES + Easiest way is to pipe through your credentials from Get-VMCSDDCDefaultCredential +#> + Param ( + [Parameter(Mandatory=$true)]$Org, + [Parameter(Mandatory=$true)]$Sddc, + [switch]$Autologin, + [switch]$UseManagementIP + ) - If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { - $creds = Get-VMCSDDCDefaultCredential -Org $Org -Sddc $Sddc - If($UseManagementIP){ - $Server = $creds.vc_management_ip - }Else{ - $Server = $creds.vc_public_ip - } - - Write-Host "Connecting to VMC vCenter Server" $Server - Connect-VIServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" - Write-Host "Connecting to VMC CIS Endpoint" $Server - Connect-CisServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" + If (-Not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect" } Else { + $creds = Get-VMCSDDCDefaultCredential -Org $Org -Sddc $Sddc + If($UseManagementIP){ + $Server = $creds.vc_management_ip + }Else{ + $Server = $creds.vc_public_ip } + + Write-Host "Connecting to VMC vCenter Server" $Server + Connect-VIServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" + Write-Host "Connecting to VMC CIS Endpoint" $Server + Connect-CisServer -Server $Server -User $creds.cloud_username -Password $creds.cloud_password | Add-Member -MemberType Noteproperty -Name Location -Value "VMC" } +} + Function Get-VMCOrg { <# .NOTES From 9de3195b324620ca15725c1b0aca56d32199c30c Mon Sep 17 00:00:00 2001 From: Bill Wall Date: Thu, 8 Aug 2019 09:30:43 -0500 Subject: [PATCH 130/175] Add Tag Assigments option Added the optional ability to export/import tag assignments. --- Scripts/ExportImportTags.ps1 | 40 +++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/Scripts/ExportImportTags.ps1 b/Scripts/ExportImportTags.ps1 index e6a1ec7..27b8ae1 100644 --- a/Scripts/ExportImportTags.ps1 +++ b/Scripts/ExportImportTags.ps1 @@ -5,15 +5,23 @@ function Export-Tag { [VMware.VimAutomation.ViCore.Types.V1.VIServer]$Server, [Parameter(Mandatory = $True, Position = 2)] - [string]$Destination + [string]$Destination, + + [Parameter(Mandatory = $False, Position = 3)] + [boolean]$ExportAssignments ) # Retrieve all categories $categoryList = Get-TagCategory -Server $server # Retrieve all tags $tagList = Get-Tag -Server $server - # Store the tags and categories in a list to export them at once - $export = @($categoryList, $tagList) + # Store the tags, categories and assignments (if selected) in a list to export them at once + If ($ExportAssignments) { + $tagAssignments = Get-TagAssignment -Server $server + $export = @($categoryList, $tagList, $tagAssignments) + } else { + $export = @($categoryList, $tagList) + } # Export the tags and categories to the specified destination Export-Clixml -InputObject $export -Path $destination } @@ -25,7 +33,10 @@ function Import-Tag { [VMware.VimAutomation.ViCore.Types.V1.VIServer]$Server, [Parameter(Mandatory = $True, Position = 2)] - [string]$Source + [string]$Source, + + [Parameter(Mandatory = $False, Position = 3)] + [boolean]$ImportAssignments ) # Import the tags and categories from the specified source @@ -62,4 +73,23 @@ function Import-Tag { -Server $server ` | Out-Null } -} \ No newline at end of file + + # Restore the assignments if selected + If ($ImportAssignments) { + # Check for assignments in the file + If ($import[2]) { + # If tags were found, assign them + $tagAssignments = $import[2] + ForEach ($assignment in $tagAssignments) { + New-TagAssignment ` + -Tag (Get-Tag -Server $server -Name $assignment.Tag.Name -Category $assignment.Tag.Category) ` + -Entity (Get-VIObjectByVIView -MORef $assignment.Entity.id) ` + -Server $server ` + | Out-Null + } + } else { + # If no assignments were found, output warning + Write-Warning "Source file does not contain tag assignments." + } + } +} From fef2f32adfe53dc9069728be2d92f2e7834dc8d5 Mon Sep 17 00:00:00 2001 From: Thibaut Noben Date: Mon, 26 Aug 2019 11:42:01 +0200 Subject: [PATCH 131/175] Added vgpu support to new-hvfarm --- .../Farm/AutomatedLinkedCloneFarm vGPU.json | 97 +++++++++++++++++++ .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 26 +++++ 2 files changed, 123 insertions(+) create mode 100644 Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm vGPU.json diff --git a/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm vGPU.json b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm vGPU.json new file mode 100644 index 0000000..ecec6ea --- /dev/null +++ b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm vGPU.json @@ -0,0 +1,97 @@ +{ + "Type": "AUTOMATED", + "Data": { + "Name": "LCFarmJson", + "DisplayName": "FarmJsonTest", + "AccessGroup": "Root", + "Description": "created LC Farm from PS via JSON with NVIDIA GRID VGPU", + "Enabled": null, + "Deleting": false, + "Settings": { + "DisconnectedSessionTimeoutPolicy": "NEVER", + "DisconnectedSessionTimeoutMinutes": 1, + "EmptySessionTimeoutPolicy": "AFTER", + "EmptySessionTimeoutMinutes": 1, + "LogoffAfterTimeout": false + }, + "Desktop": null, + "DisplayProtocolSettings": { + "DefaultDisplayProtocol": "PCOIP", + "AllowDisplayProtocolOverride": false, + "EnableHTMLAccess": false, + "EnableCollaboration": false, + "EnableGRIDvGPUs": true, + "VGPUGridProfile": "grid_m10-8a" + }, + "ServerErrorThreshold": null, + "MirageConfigurationOverrides": { + "OverrideGlobalSetting": false, + "Enabled": false, + "Url": null + } + }, + "AutomatedFarmSpec": { + "ProvisioningType": "VIEW_COMPOSER", + "VirtualCenter": null, + "RdsServerNamingSpec": { + "NamingMethod": "PATTERN", + "PatternNamingSettings": { + "NamingPattern": "LCFarmVMPS", + "MaxNumberOfRDSServers": 1 + } + }, + "VirtualCenterProvisioningSettings": { + "EnableProvisioning": true, + "StopProvisioningOnError": true, + "MinReadyVMsOnVComposerMaintenance": 0, + "VirtualCenterProvisioningData": { + "ParentVm": "RDSServer", + "Snapshot": "RDS_SNAP1", + "Datacenter": null, + "VmFolder": "Praveen", + "HostOrCluster": "CS-1", + "ResourcePool": "CS-1" + }, + "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": "SYS_PREP", + "DomainAdministrator": null, + "AdContainer": "CN=Computers", + "ReusePreExistingAccounts": false, + "SysprepCustomizationSettings": { + "CustomizationSpec": "PraveenCust" + } + }, + "RdsServerMaxSessionsData": { + "MaxSessionsType": "UNLIMITED", + "MaxSessions": null + } + }, + "ManualFarmSpec": null, + "NetBiosName": "adviewdev" +} \ No newline at end of file diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index f5921d6..67a99cd 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -2243,6 +2243,21 @@ function New-HVFarm { [boolean] $EnableHTMLAccess = $false, + #farmSpec.data.displayProtocolSettings.EnableCollaboration + [Parameter(Mandatory = $false)] + [boolean] + $EnableCollaboration = $false, + + #farmSpec.data.displayProtocolSettings.EnableGRIDvGPUs + [Parameter(Mandatory = $false)] + [boolean] + $EnableGRIDvGPUs = $false, + + #farmSpec.data.displayProtocolSettings.VGPUGridProfile + [Parameter(Mandatory = $false)] + [string] + $VGPUGridProfile, + #farmSpec.data.serverErrorThreshold [Parameter(Mandatory = $false)] [ValidateRange(0,[Int]::MaxValue)] @@ -2659,6 +2674,12 @@ function New-HVFarm { $defaultDisplayProtocol = $jsonObject.Data.DisplayProtocolSettings.DefaultDisplayProtocol $allowDisplayProtocolOverride = $jsonObject.Data.DisplayProtocolSettings.AllowDisplayProtocolOverride $enableHTMLAccess = $jsonObject.Data.DisplayProtocolSettings.EnableHTMLAccess + $EnableCollaboration = $jsonObject.Data.DisplayProtocolSettings.EnableCollaboration + + if ($null -ne $jsonObject.Data.DisplayProtocolSettings.VGPUGridProfile) { + $EnableGRIDvGPUs = $jsonObject.Data.DisplayProtocolSettings.EnableGRIDvGPUs + $VGPUGridProfile = $jsonObject.Data.DisplayProtocolSettings.VGPUGridProfile + } } if ($null -ne $jsonObject.Data.serverErrorThreshold) { $serverErrorThreshold = $jsonObject.Data.serverErrorThreshold @@ -2802,6 +2823,11 @@ function New-HVFarm { $farmData.DisplayProtocolSettings.DefaultDisplayProtocol = $defaultDisplayProtocol $farmData.DisplayProtocolSettings.AllowDisplayProtocolOverride = $AllowDisplayProtocolOverride $farmData.DisplayProtocolSettings.EnableHTMLAccess = $enableHTMLAccess + $farmData.DisplayProtocolSettings.EnableCollaboration = $EnableCollaboration + if($VGPUGridProfile -ne $false){ + $farmData.DisplayProtocolSettings.EnableGRIDvGPUs = $EnableGRIDvGPUs + $farmData.DisplayProtocolSettings.VGPUGridProfile = $VGPUGridProfile + } } if ($farmData.MirageConfigurationOverrides){ $farmData.MirageConfigurationOverrides.OverrideGlobalSetting = $overrideGlobalSetting From 3653dd09bc6c44c87be79fcdb1d453ab81a9b635 Mon Sep 17 00:00:00 2001 From: Thibaut Noben Date: Tue, 27 Aug 2019 12:14:00 +0200 Subject: [PATCH 132/175] Removed spaces from name json file --- ...inkedCloneFarm vGPU.json => AutomatedLinkedCloneFarmVGPU.json} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Modules/VMware.Hv.Helper/Json/Farm/{AutomatedLinkedCloneFarm vGPU.json => AutomatedLinkedCloneFarmVGPU.json} (100%) diff --git a/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm vGPU.json b/Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarmVGPU.json similarity index 100% rename from Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarm vGPU.json rename to Modules/VMware.Hv.Helper/Json/Farm/AutomatedLinkedCloneFarmVGPU.json From c49cf2f7218a5dc72fe164e8c565b530c3338dc5 Mon Sep 17 00:00:00 2001 From: LucD Date: Thu, 5 Sep 2019 13:24:34 +0200 Subject: [PATCH 133/175] PS Profile As documented in http://www.lucd.info/2019/09/05/at-your-fingertips/ Signed-off-by: Luc Dekens --- Scripts/At_Your_Fingertips/NewProfile.ps1 | 117 ++++++++++++++++++ .../At_Your_Fingertips/install-profile.ps1 | 60 +++++++++ 2 files changed, 177 insertions(+) create mode 100644 Scripts/At_Your_Fingertips/NewProfile.ps1 create mode 100644 Scripts/At_Your_Fingertips/install-profile.ps1 diff --git a/Scripts/At_Your_Fingertips/NewProfile.ps1 b/Scripts/At_Your_Fingertips/NewProfile.ps1 new file mode 100644 index 0000000..7d92e09 --- /dev/null +++ b/Scripts/At_Your_Fingertips/NewProfile.ps1 @@ -0,0 +1,117 @@ +# +# Provide environment information in the PS Console +# +# History: +# 1.0 - August 4th 2019 - LucD +# Initial version (for session HBI1729BU VMworld US 2019) +# +# 1) PS prompt +# - current (local) time +# - execution time of the previous command +# - shortened PWD +# 2) Window title +# - User/Admin +# - PS-32/54-Edition-Version +# - PCLI version +# - git repo/branch +# - VC/ESXi:defaultServer-User [# connections] + +function prompt +{ + # Current time + $date = (Get-Date).ToString('HH:mm:ss') + Write-Host -Object '[' -NoNewline + Write-Host -Object $date -ForegroundColor Cyan -BackgroundColor DarkBlue -NoNewline + Write-Host -Object ']' -NoNewline + + # Execution time previous command + $history = Get-History -ErrorAction Ignore -Count 1 + if ($history) + { + $time = ([DateTime](New-TimeSpan -Start $history.StartExecutionTime -End $history.EndExecutionTime).Ticks).ToString('HH:mm:ss.ffff') + Write-host -Object '[' -NoNewLine + Write-Host -Object "$time" -ForegroundColor Yellow -BackgroundColor DarkBlue -NoNewline + Write-host -Object '] ' -NoNewLine + } + + # Shorted PWD + $path = $pwd.Path.Split('\') + if ($path.Count -gt 3) + { + $path = $path[0], '..', $path[-2], $path[-1] + } + Write-Host -Object "$($path -join '\')" -NoNewline + + # Prompt function needs to return something, + # otherwise the default 'PS>' will be added + "> " + + # Refresh the window's title + Set-Title +} + +function Set-Title +{ + # Running as Administrator or a regular user + $userInfo = [Security.Principal.WindowsIdentity]::GetCurrent() + if ((New-Object Security.Principal.WindowsPrincipal $userInfo).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) + { + $role = 'Admin' + } + else + { + $role = 'User' + } + + # Usertype user@hostname + $user = "$role $($userInfo.Name)@$($env:computername)" + + # PowerShell environment/PS version + $bits = 32 + if ([Environment]::Is64BitProcess) + { + $bits = 64 + } + $ps = " - PS-$($bits): $PSEdition/$($PSVersionTable.PSVersion.ToString())" + + # PowerCLI version (derived from module VMware.PowerCLI) + $pcliModule = Get-Module -Name VMware.PowerCLI -ListAvailable | + Sort-Object -Property Version -Descending | + Select-Object -First 1 + $pcli = " - PCLI: $($pcliModule.Version.ToString())" + + # If git is present and if in a git controlled folder, display repositoryname/current_branch + $gitStr = '' + if ((Get-Command -Name 'git' -CommandType Application -ErrorAction SilentlyContinue).Count -gt 0) + { + $gitTopLevel = & { git rev-parse --show-toplevel 2> $null } + if ($gitTopLevel.Length -ne 0) + { + $gitRepo = Split-Path -Path $gitTopLevel -Leaf + $gitBranch = (git branch | Where-Object { $_ -match "\*" }).Trimstart('* ') + $gitStr = " - git: $gitRepo/$gitBranch" + } + } + + # If there is an open vSphere Server connection + # display [VC|ESXi] last_connected_server-connected_user [number of open server connections] + if ($global:defaultviserver) + { + $vcObj = (Get-Variable -Scope global -Name 'DefaultVIServer').Value + if ($vcObj.ProductLine -eq 'vpx') + { + $vcSrv = 'VC' + } + else + { + $vcSrv = 'ESXi' + } + $vc = " - $($vcSrv): $($vcObj.Name)-$($vcObj.User) [$($global:DefaultVIServers.Count)]" + } + + # Update the Window's title + $host.ui.RawUI.WindowTitle = "$user$ps$pcli$vc$gitStr" +} + +# Set title after starting session +Set-Title diff --git a/Scripts/At_Your_Fingertips/install-profile.ps1 b/Scripts/At_Your_Fingertips/install-profile.ps1 new file mode 100644 index 0000000..0d7919f --- /dev/null +++ b/Scripts/At_Your_Fingertips/install-profile.ps1 @@ -0,0 +1,60 @@ +[cmdletbinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + # [Parameter(Mandatory = $true)] + [ValidateSet('CurrentUserCurrentHost', 'CurrentUserAllHosts', + 'AllUsersCurrentHost', 'AllUsersAllHosts')] + [string]$Scope, + [switch]$NoClobber, + [switch]$Backup, + [string]$NewProfile = '.\NewProfile.ps1' +) + +if ($PSCmdlet.ShouldProcess("$($Profile.$Scope)", "Create $Scope profile")) +{ + $profilePath = $Profile."$Scope" + Write-Verbose -Message "Target is $profilePath" + $createProfile = $true + if (Test-Path -Path $profilePath) + { + Write-Verbose -Message "Target exists" + if ($NoClobber) + { + Write-Verbose -Message "Cannot overwrite target due to NoClobber" + $createProfile = $false + } + elseif ($Backup) + { + Write-Verbose -Message "Create a backup as $profilePath.bak" + Copy-Item -Path $profilePath -Destination "$profilePath.bak" -Confirm:$false -Force + } + elseif (-not $NoClobber) + { + Write-Verbose -Message "Target will be overwritten" + } + else + { + Write-Verbose -Message "Use -NoClobber:$false or -Backup" + } + } + if ($createProfile) + { + if (-not $NewProfile) + { + $script:MyInvocation.MyCommand | select * + $folder = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Path + $folder = Get-Location + $NewProfile = "$folder\NewProfile.ps1" + } + Write-Verbose -Message "New profile expected at $NewProfile" + if (Test-Path -Path $NewProfile) + { + Write-Verbose -Message "Copy $NewProfile to $profilePath" + Copy-Item -Path $NewProfile -Destination $profilePath -Confirm:$false + } + else + { + Write-Warning -Message "Could not find the new profile file!" + Write-Warning -Message "Use the NewProfile parameter or store a NewProfile.ps1 file in folder $folder." + } + } +} \ No newline at end of file From 44fbae8d0822774dfd464068244c423bcd8c00b1 Mon Sep 17 00:00:00 2001 From: Alex Lopez Date: Mon, 9 Sep 2019 17:49:16 -0400 Subject: [PATCH 134/175] PS Profile - Update Added PowerShell-Core compatibility for multi-OS support --- Scripts/At_Your_Fingertips/NewProfile.ps1 | 48 +++++++++++++++-------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/Scripts/At_Your_Fingertips/NewProfile.ps1 b/Scripts/At_Your_Fingertips/NewProfile.ps1 index 7d92e09..d4f2608 100644 --- a/Scripts/At_Your_Fingertips/NewProfile.ps1 +++ b/Scripts/At_Your_Fingertips/NewProfile.ps1 @@ -4,43 +4,50 @@ # History: # 1.0 - August 4th 2019 - LucD # Initial version (for session HBI1729BU VMworld US 2019) +# 2.0 - September 9th 2019 - virtualex +# Added PowerShell-Core compatibility # # 1) PS prompt +# - detect pwsh-core # - current (local) time # - execution time of the previous command # - shortened PWD # 2) Window title # - User/Admin -# - PS-32/54-Edition-Version +# - PS-32/64-Edition-Version # - PCLI version # - git repo/branch # - VC/ESXi:defaultServer-User [# connections] function prompt { + # Detect PS-Core + If ($PSVersionTable.PSEdition -eq 'Core') { + Write-Host '(Core) ' -NoNewLine + } # Current time $date = (Get-Date).ToString('HH:mm:ss') - Write-Host -Object '[' -NoNewline + Write-Host -Object '[' -NoNewLine Write-Host -Object $date -ForegroundColor Cyan -BackgroundColor DarkBlue -NoNewline - Write-Host -Object ']' -NoNewline + Write-Host -Object ']' -NoNewLine # Execution time previous command $history = Get-History -ErrorAction Ignore -Count 1 if ($history) { $time = ([DateTime](New-TimeSpan -Start $history.StartExecutionTime -End $history.EndExecutionTime).Ticks).ToString('HH:mm:ss.ffff') - Write-host -Object '[' -NoNewLine - Write-Host -Object "$time" -ForegroundColor Yellow -BackgroundColor DarkBlue -NoNewline - Write-host -Object '] ' -NoNewLine + Write-Host -Object '[' -NoNewLine + Write-Host -Object "$time" -ForegroundColor Yellow -BackgroundColor DarkBlue -NoNewLine + Write-Host -Object '] ' -NoNewLine } - # Shorted PWD + # Shortened PWD $path = $pwd.Path.Split('\') if ($path.Count -gt 3) { $path = $path[0], '..', $path[-2], $path[-1] } - Write-Host -Object "$($path -join '\')" -NoNewline + Write-Host -Object "$($path -join '\')" -NoNewLine # Prompt function needs to return something, # otherwise the default 'PS>' will be added @@ -53,18 +60,27 @@ function prompt function Set-Title { # Running as Administrator or a regular user - $userInfo = [Security.Principal.WindowsIdentity]::GetCurrent() - if ((New-Object Security.Principal.WindowsPrincipal $userInfo).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) - { - $role = 'Admin' - } - else - { - $role = 'User' + If (($PSVersionTable.PSEdition -eq 'Core') -and ($IsWindows -eq 'True') -or ($PSVersionTable.PSEdition -ine 'Core')) + { + $userInfo = [Security.Principal.WindowsIdentity]::GetCurrent() + if ((New-Object Security.Principal.WindowsPrincipal $userInfo).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) + { + $role = 'Admin' + } + else + { + $role = 'User' + } } # Usertype user@hostname + If (($PSVersionTable.PSEdition -eq 'Core') -and ($IsWindows -ine 'True')) { + $env:computername = hostname + $user = "$($env:user)@$($env:computername)" + } + Else { $user = "$role $($userInfo.Name)@$($env:computername)" + } # PowerShell environment/PS version $bits = 32 From 323b9e88f7ea5e03b5c6ea3893ad4cd45b6324f5 Mon Sep 17 00:00:00 2001 From: Alex Lopez Date: Tue, 10 Sep 2019 21:35:12 -0400 Subject: [PATCH 135/175] Update NewProfile.ps1 Removed redundant display (Core) in the console as it's displayed in the Title --- Scripts/At_Your_Fingertips/NewProfile.ps1 | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Scripts/At_Your_Fingertips/NewProfile.ps1 b/Scripts/At_Your_Fingertips/NewProfile.ps1 index d4f2608..7fc2f05 100644 --- a/Scripts/At_Your_Fingertips/NewProfile.ps1 +++ b/Scripts/At_Your_Fingertips/NewProfile.ps1 @@ -8,7 +8,6 @@ # Added PowerShell-Core compatibility # # 1) PS prompt -# - detect pwsh-core # - current (local) time # - execution time of the previous command # - shortened PWD @@ -21,10 +20,6 @@ function prompt { - # Detect PS-Core - If ($PSVersionTable.PSEdition -eq 'Core') { - Write-Host '(Core) ' -NoNewLine - } # Current time $date = (Get-Date).ToString('HH:mm:ss') Write-Host -Object '[' -NoNewLine From 46db5d0f50aed4e76e41f9595a0d59b3548fdaee Mon Sep 17 00:00:00 2001 From: Alex Lopez Date: Tue, 10 Sep 2019 21:42:15 -0400 Subject: [PATCH 136/175] Revert "Update NewProfile.ps1" This reverts commit 323b9e88f7ea5e03b5c6ea3893ad4cd45b6324f5. --- Scripts/At_Your_Fingertips/NewProfile.ps1 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Scripts/At_Your_Fingertips/NewProfile.ps1 b/Scripts/At_Your_Fingertips/NewProfile.ps1 index 7fc2f05..d4f2608 100644 --- a/Scripts/At_Your_Fingertips/NewProfile.ps1 +++ b/Scripts/At_Your_Fingertips/NewProfile.ps1 @@ -8,6 +8,7 @@ # Added PowerShell-Core compatibility # # 1) PS prompt +# - detect pwsh-core # - current (local) time # - execution time of the previous command # - shortened PWD @@ -20,6 +21,10 @@ function prompt { + # Detect PS-Core + If ($PSVersionTable.PSEdition -eq 'Core') { + Write-Host '(Core) ' -NoNewLine + } # Current time $date = (Get-Date).ToString('HH:mm:ss') Write-Host -Object '[' -NoNewLine From 35095fbea71bc09aebe0ad2c31f9055f956dcfb5 Mon Sep 17 00:00:00 2001 From: Alex Lopez Date: Tue, 10 Sep 2019 21:46:44 -0400 Subject: [PATCH 137/175] Update NewProfile.ps1 Removed redundant display of (Core) in the console as it's displayed in the Title; minor cleanup. --- Scripts/At_Your_Fingertips/NewProfile.ps1 | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/Scripts/At_Your_Fingertips/NewProfile.ps1 b/Scripts/At_Your_Fingertips/NewProfile.ps1 index d4f2608..a4b9f8d 100644 --- a/Scripts/At_Your_Fingertips/NewProfile.ps1 +++ b/Scripts/At_Your_Fingertips/NewProfile.ps1 @@ -8,7 +8,6 @@ # Added PowerShell-Core compatibility # # 1) PS prompt -# - detect pwsh-core # - current (local) time # - execution time of the previous command # - shortened PWD @@ -21,10 +20,6 @@ function prompt { - # Detect PS-Core - If ($PSVersionTable.PSEdition -eq 'Core') { - Write-Host '(Core) ' -NoNewLine - } # Current time $date = (Get-Date).ToString('HH:mm:ss') Write-Host -Object '[' -NoNewLine @@ -60,7 +55,7 @@ function prompt function Set-Title { # Running as Administrator or a regular user - If (($PSVersionTable.PSEdition -eq 'Core') -and ($IsWindows -eq 'True') -or ($PSVersionTable.PSEdition -ine 'Core')) + If (($PSEdition -eq 'Core') -and ($IsWindows -eq 'True') -or ($PSEdition -ine 'Core')) { $userInfo = [Security.Principal.WindowsIdentity]::GetCurrent() if ((New-Object Security.Principal.WindowsPrincipal $userInfo).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) @@ -74,7 +69,7 @@ function Set-Title } # Usertype user@hostname - If (($PSVersionTable.PSEdition -eq 'Core') -and ($IsWindows -ine 'True')) { + If (($PSEdition -eq 'Core') -and ($IsWindows -ine 'True')) { $env:computername = hostname $user = "$($env:user)@$($env:computername)" } From c506bf400aad8359e27cfa87cfd5ebff5f82c0f3 Mon Sep 17 00:00:00 2001 From: Sander <28297121+servisan@users.noreply.github.com> Date: Mon, 30 Sep 2019 21:12:56 +0200 Subject: [PATCH 138/175] Rearranged notes section Tabs and spaces cleaned up --- Scripts/NVME Info.ps1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Scripts/NVME Info.ps1 b/Scripts/NVME Info.ps1 index 415b298..dd38a10 100644 --- a/Scripts/NVME Info.ps1 +++ b/Scripts/NVME Info.ps1 @@ -1,11 +1,11 @@ <# .NOTES =========================================================================== - Created by: Alan Renouf - Organization: VMware - Blog: http://virtu-al.net - Twitter: @alanrenouf - =========================================================================== + Created by: Alan Renouf + Organization: VMware + Blog: http://virtu-al.net + Twitter: @alanrenouf + =========================================================================== #> Foreach ($vmhost in Get-VMHost) { @@ -24,4 +24,4 @@ Foreach ($vmhost in Get-VMHost) { $esxcli.nvme.device.feature.$feature.get.Invoke($currentfeature) } } -} \ No newline at end of file +} From 1b7ea8034219008f6eff8072276b6ba2e020abb1 Mon Sep 17 00:00:00 2001 From: Doug Taliaferro Date: Fri, 11 Oct 2019 09:30:38 -0400 Subject: [PATCH 139/175] Create Set-ClusterDpm.ps1 Configures Distributed Power Managment (DPM) --- Scripts/Set-ClusterDpm.ps1 | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Scripts/Set-ClusterDpm.ps1 diff --git a/Scripts/Set-ClusterDpm.ps1 b/Scripts/Set-ClusterDpm.ps1 new file mode 100644 index 0000000..82292c2 --- /dev/null +++ b/Scripts/Set-ClusterDpm.ps1 @@ -0,0 +1,63 @@ +<# +.NOTES + Script name: Set-ClusterDpm.ps1 + Created on: 10/10/2019 + Author: Doug Taliaferro, @virtually_doug + Description: Configures Distributed Power Management (DPM) on a cluster. + Dependencies: None known + + ===Tested Against Environment==== + vSphere Version: 6.7 + PowerCLI Version: 11.3.0 + PowerShell Version: 5.1 + OS Version: Windows 7, 10 + Keyword: Cluster, DPM +.SYNOPSIS + Configures Distributed Power Management (DPM). + +.DESCRIPTION + Enables/disables Distributed Power Management (DPM) for one or more clusters and optionally sets the automation level. + +.PARAMETER Clusters + Specifies the name of the cluster(s) you want to configure. + +.PARAMETER DpmEnabled + Indicates whether Distributed Power Management (DPM) should be enabled/disabled. + +.PARAMETER DpmAutomationLevel + Specifies the Distributed Power Management (DPM) automation level. The valid values are 'automated' and 'manual'. + +.EXAMPLE + Set-ClusterDpm -Cluster 'Cluster01' -DpmEnabled:$true + +.EXAMPLE + Get-Cluster | Set-ClusterDpm -DpmEnabled:$true -DpmAutomationLevel 'automated' +#> +[CmdletBinding()] +param ( + [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] + [Alias('Name')] + [string[]]$Clusters, + + [Parameter(Mandatory=$true)] + [bool]$DpmEnabled, + + [Parameter(Mandatory = $false)] + [ValidateSet('automated','manual')] + [string]$DpmAutomationLevel +) +Begin { + # Create a configuration spec + $spec = New-Object VMware.Vim.ClusterConfigSpecEx + $spec.dpmConfig = New-Object VMware.Vim.ClusterDpmConfigInfo + $spec.dpmConfig.enabled = $DpmEnabled + if ($DpmAutomationLevel) { + $spec.dpmConfig.defaultDpmBehavior = $DpmAutomationLevel + } +} +Process { + ForEach ($cluster in $Clusters) { + # Configure the cluster + (Get-Cluster $cluster).ExtensionData.ReconfigureComputeResource_Task($spec, $true) + } +} From ae16ef6e52059558691775930341dfcd07c7f49a Mon Sep 17 00:00:00 2001 From: Troy Lindsay Date: Fri, 25 Oct 2019 15:23:06 -0500 Subject: [PATCH 140/175] #320: Add DomainName param to New-NSXTSegment Allows end user to specify the DNS domain name for the network segment --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index b8c9c9a..e74fc61 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -159,6 +159,7 @@ Function New-NSXTSegment { [Parameter(Mandatory=$True)]$Name, [Parameter(Mandatory=$True)]$Gateway, [Parameter(Mandatory=$False)]$DHCPRange, + [Parameter(Mandatory=$False)]$DomainName, [Switch]$DHCP, [Switch]$Troubleshoot ) @@ -179,6 +180,11 @@ Function New-NSXTSegment { display_name = $Name; subnets = @($subnets) } + + if($DomainName) { + $payload.domain_name = $DomainName + } + $body = $payload | ConvertTo-Json -depth 4 $method = "PUT" From 39a8539d978e64d72056138622cd8568c2853150 Mon Sep 17 00:00:00 2001 From: Troy Lindsay Date: Fri, 25 Oct 2019 16:26:26 -0500 Subject: [PATCH 141/175] #320: Add example for New-NSXTSegment -DomainName --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index e74fc61..8e372a0 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -152,6 +152,8 @@ Function New-NSXTSegment { This cmdlet creates a new NSX-T Segment (Logical Networks) .EXAMPLE New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" + .EXAMPLE + New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" -DomainName 'vmc.local' .EXAMPLE New-NSXTSegment -Name "sddc-cgw-network-5" -Gateway "192.168.5.1/24" #> From 49c0b44beb3683b7394b22e280152b31c843837c Mon Sep 17 00:00:00 2001 From: Troy Lindsay Date: Fri, 25 Oct 2019 22:08:36 -0500 Subject: [PATCH 142/175] #322: New-NSXTFirewall fix action --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index b8c9c9a..e250676 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -469,7 +469,7 @@ Function New-NSXTFirewall { [Parameter(Mandatory=$False)]$SourceGroup, [Parameter(Mandatory=$False)]$DestinationGroup, [Parameter(Mandatory=$True)]$Service, - [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DENY")]$Action, + [Parameter(Mandatory=$True)][ValidateSet("ALLOW","DROP")]$Action, [Parameter(Mandatory=$false)]$InfraScope, [Parameter(Mandatory=$false)]$SourceInfraGroup, [Parameter(Mandatory=$false)]$DestinationInfraGroup, From c7fcb1b18601783ca33a05a75636e078091c033e Mon Sep 17 00:00:00 2001 From: Akeem Jenkins Date: Tue, 12 Nov 2019 13:46:23 -0700 Subject: [PATCH 143/175] Fixing the authorize request to use the recently updated API change. Refresh tokens visa the query param were deprecated. https://console.cloud.vmware.com/csp/gateway/am/api/swagger-ui.html#/Authentication/getAccessTokenByApiRefreshTokenUsingPOST --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 6a55445..95b5612 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -37,7 +37,7 @@ Function Connect-NSXTProxy { } } - $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -Method POST -Headers @{accept='application/json'} -Body "refresh_token=$RefreshToken" if($results.StatusCode -ne 200) { Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" break @@ -2896,4 +2896,4 @@ Function Remove-NSXTNatRule { Write-Host "Successfully deleted NAT Rule $Name" } } -} \ No newline at end of file +} From 478d913779a404fb52faebfdf45654d2b722ee16 Mon Sep 17 00:00:00 2001 From: Troy Lindsay Date: Thu, 14 Nov 2019 10:44:55 -0600 Subject: [PATCH 144/175] #326: Add New-NSXTGroup matching support --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 36 +++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 6a55445..b48351b 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -754,18 +754,46 @@ Function New-NSXTGroup { This cmdlet creates a new NSX-T Firewall Rule on MGW or CGW .EXAMPLE New-NSXTGroup -GatewayType MGW -Name Foo -IPAddress @("172.31.0.0/24") + .EXAMPLE + New-NSXTGroup -GatewayType CGW -Name Foo -Tag Bar + .EXAMPLE + New-NSXTGroup -GatewayType CGW -Name Foo -VmName Bar -Operator CONTAINS + .EXAMPLE + New-NSXTGroup -GatewayType CGW -Name Foo -VmName Bar -Operator STARTSWITH #> + [CmdletBinding(DefaultParameterSetName = 'IPAddress')] Param ( [Parameter(Mandatory=$True)]$Name, [Parameter(Mandatory=$true)][ValidateSet("MGW","CGW")][String]$GatewayType, - [Parameter(Mandatory=$True)][String[]]$IPAddress, + [Parameter(Mandatory=$true, ParameterSetName='IPAddress')][String[]]$IPAddress, + [Parameter(Mandatory=$true, ParameterSetName='Tag')][String]$Tag, + [Parameter(Mandatory=$true, ParameterSetName='VmName')][String]$VmName, + [Parameter(Mandatory=$true, ParameterSetName='VmName')][ValidateSet('CONTAINS','STARTSWITH')][String]$Operator, [Switch]$Troubleshoot ) If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { - $expression = @{ - resource_type = "IPAddressExpression"; - ip_addresses = $IPAddress; + if ($PSCmdlet.ParameterSetName -eq 'Tag') { + $expression = @{ + resource_type = 'Condition' + member_type = 'VirtualMachine' + value = $Tag + key = 'Tag' + operator = 'EQUALS' + } + } elseif ($PSCmdlet.ParameterSetName -eq 'VmName') { + $expression = @{ + resource_type = 'Condition' + member_type = 'VirtualMachine' + value = $VmName + key = 'Name' + operator = $Operator.ToUpper() + } + } else { + $expression = @{ + resource_type = "IPAddressExpression"; + ip_addresses = $IPAddress; + } } $payload = @{ From c1e181ea1152453527f73971c93921487c046146 Mon Sep 17 00:00:00 2001 From: LucD Date: Mon, 18 Nov 2019 13:34:04 +0100 Subject: [PATCH 145/175] On the off chance someone does not have PowerCLI installed Handle ToString() error when PCLI is not present Signed-off-by: Luc Dekens --- Scripts/At_Your_Fingertips/NewProfile.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Scripts/At_Your_Fingertips/NewProfile.ps1 b/Scripts/At_Your_Fingertips/NewProfile.ps1 index a4b9f8d..66ea5aa 100644 --- a/Scripts/At_Your_Fingertips/NewProfile.ps1 +++ b/Scripts/At_Your_Fingertips/NewProfile.ps1 @@ -89,7 +89,7 @@ function Set-Title $pcliModule = Get-Module -Name VMware.PowerCLI -ListAvailable | Sort-Object -Property Version -Descending | Select-Object -First 1 - $pcli = " - PCLI: $($pcliModule.Version.ToString())" + $pcli = " - PCLI: $(if($pcliModule){$pcliModule.Version.ToString()}else{'na'})" # If git is present and if in a git controlled folder, display repositoryname/current_branch $gitStr = '' From a7ff78fee0f8a7d1d24ac7b04f0dc7ee70dec522 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Mon, 18 Nov 2019 19:09:41 -0500 Subject: [PATCH 146/175] Create Get-TriggeredAlarm.ps1 Adding a new function to view triggered alarms for vSphere objects --- Scripts/Get-TriggeredAlarm.ps1 | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Scripts/Get-TriggeredAlarm.ps1 diff --git a/Scripts/Get-TriggeredAlarm.ps1 b/Scripts/Get-TriggeredAlarm.ps1 new file mode 100644 index 0000000..a5d8dc6 --- /dev/null +++ b/Scripts/Get-TriggeredAlarm.ps1 @@ -0,0 +1,62 @@ +function Get-TriggeredAlarm { +<# + .SYNOPSIS + This function lists the triggered alarms for the specified entity in vCenter + .DESCRIPTION + List the triggered alarms for the given object + .NOTES + Author: Kyle Ruddy, @kmruddy, kmruddy.com + .PARAMETER VM + Specifies the name of the VM + .PARAMETER VMHost + Specifies the name of the VMHost + .PARAMETER Datacenter + Specifies the name of the Datacenter + .PARAMETER Datastore + Specifies the name of the Datastore + .EXAMPLE + Get-TriggeredAlarm -VM VMname + + Entity Alarm AlarmStatus AlarmMoRef EntityMoRef + ---- ---- ---- ---- ---- + VMname Name Yellow Alarm-MoRef Entity-MoRef +#> + + [CmdletBinding()] + param( + [string]$VM, + [string]$VMHost, + [string]$Datacenter, + [string]$Datastore + ) + BEGIN { + switch ($PSBoundParameters.Keys) { + 'VM' {$entity = Get-VM -Name $vm -ErrorAction SilentlyContinue} + 'VMHost' {$entity = Get-VMHost -Name $VMHost -ErrorAction SilentlyContinue} + 'Datacenter' {$entity = Get-Datacenter -Name $Datacenter -ErrorAction SilentlyContinue} + 'Datastore' {$entity = Get-Datastore -Name $Datastore -ErrorAction SilentlyContinue} + default {$entity = $null} + } + + if ($null -eq $entity) { + Write-Warning "No vSphere object found." + break + } + } + PROCESS { + if ($entity.ExtensionData.TriggeredAlarmState -ne "") { + $alarmOutput = @() + foreach ($alarm in $entity.ExtensionData.TriggeredAlarmState) { + $tempObj = "" | Select-Object -Property Entity, Alarm, AlarmStatus, AlarmMoRef, EntityMoRef + $tempObj.Entity = Get-View $alarm.Entity | Select-Object -ExpandProperty Name + $tempObj.Alarm = Get-View $alarm.Alarm | Select-Object -ExpandProperty Info | Select-Object -ExpandProperty Name + $tempObj.AlarmStatus = $alarm.OverallStatus + $tempObj.AlarmMoRef = $alarm.Alarm + $tempObj.EntityMoRef = $alarm.Entity + $alarmOutput += $tempObj + } + $alarmOutput | Format-Table -AutoSize + } + } + +} \ No newline at end of file From 31e3accfe1ab4c26fe93deeb8fcfcf0002c8d478 Mon Sep 17 00:00:00 2001 From: Troy Lindsay Date: Tue, 19 Nov 2019 09:51:20 -0600 Subject: [PATCH 147/175] #328: New-NSXTDistFirewall use first section match --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index b48351b..a56c2d6 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1473,7 +1473,7 @@ Function New-NSXTDistFirewall { If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { - $sectionId = (Get-NSXTDistFirewallSection -Name $Section).Id + $sectionId = (Get-NSXTDistFirewallSection -Name $Section)[0].Id $destinationGroups = @() foreach ($group in $DestinationGroup) { From 5c210f3839248612116bd49ef4fda10a5412ffec Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Tue, 19 Nov 2019 16:50:57 -0500 Subject: [PATCH 148/175] Update ContentLibrary.psm1 Updating per Issue 319 --- Modules/ContentLibrary/ContentLibrary.psm1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/ContentLibrary/ContentLibrary.psm1 b/Modules/ContentLibrary/ContentLibrary.psm1 index 5729445..25e6a58 100644 --- a/Modules/ContentLibrary/ContentLibrary.psm1 +++ b/Modules/ContentLibrary/ContentLibrary.psm1 @@ -344,8 +344,8 @@ Function New-ExtReplicatedContentLibrary { $createSpec = $subscribeLibraryService.Help.create.create_spec.Create() $createSpec.name = $LibraryName $addResults = $createSpec.storage_backings.Add($StorageSpec) - $createSpec.subscription_info.automatic_sync_enabled = $false - $createSpec.subscription_info.on_demand = $true + $createSpec.subscription_info.automatic_sync_enabled = $AutoSync + $createSpec.subscription_info.on_demand = $OnDemand $createSpec.subscription_info.subscription_url = $subscribeUrl $createSpec.subscription_info.authentication_method = "NONE" $createSpec.type = "SUBSCRIBED" From a8a98e098ea752e50a3dcb560a007680e3fb009f Mon Sep 17 00:00:00 2001 From: Troy Lindsay Date: Thu, 21 Nov 2019 03:19:02 -0600 Subject: [PATCH 149/175] #333: New-NSXTDistFirewall force action uppercase --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index b48351b..f6fe0aa 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -1513,7 +1513,7 @@ Function New-NSXTDistFirewall { logged = $Logged; scope = @("ANY"); services = $services; - action = $Action; + action = $Action.ToUpper(); } $body = $payload | ConvertTo-Json -depth 5 From 6797eb81568ac66039418ac32f3efe35209173b4 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 30 Nov 2019 07:43:08 -0800 Subject: [PATCH 150/175] Updating to latest CSP Auth API --- Modules/VMware.CSP/VMware.CSP.psm1 | 3 +-- Modules/VMware.DRaaS/VMware.DRaaS.psm1 | 2 +- Modules/VMware.HCX/VMware.HCX.psm1 | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Modules/VMware.CSP/VMware.CSP.psm1 b/Modules/VMware.CSP/VMware.CSP.psm1 index 0562950..469bcad 100644 --- a/Modules/VMware.CSP/VMware.CSP.psm1 +++ b/Modules/VMware.CSP/VMware.CSP.psm1 @@ -21,8 +21,7 @@ [Parameter(Mandatory=$true)][String]$RefreshToken ) - $body = "refresh_token=$RefreshToken" - $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -Method POST -ContentType "application/x-www-form-urlencoded" -UseBasicParsing -Body $body + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -Method POST -Headers @{accept='application/json'} -Body "refresh_token=$RefreshToken" if($results.StatusCode -ne 200) { Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" break diff --git a/Modules/VMware.DRaaS/VMware.DRaaS.psm1 b/Modules/VMware.DRaaS/VMware.DRaaS.psm1 index 3028c8c..7067d49 100644 --- a/Modules/VMware.DRaaS/VMware.DRaaS.psm1 +++ b/Modules/VMware.DRaaS/VMware.DRaaS.psm1 @@ -32,7 +32,7 @@ Function Connect-DRaas { } - $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -Method POST -Headers @{accept='application/json'} -Body "refresh_token=$RefreshToken" if($results.StatusCode -ne 200) { Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" break diff --git a/Modules/VMware.HCX/VMware.HCX.psm1 b/Modules/VMware.HCX/VMware.HCX.psm1 index 9bfcc18..d869ea1 100644 --- a/Modules/VMware.HCX/VMware.HCX.psm1 +++ b/Modules/VMware.HCX/VMware.HCX.psm1 @@ -1382,7 +1382,7 @@ Function Connect-HcxCloudServer { [Switch]$Troubleshoot ) - $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=$RefreshToken" -Method POST -ContentType "application/json" -UseBasicParsing -Headers @{"csp-auth-token"="$RefreshToken"} + $results = Invoke-WebRequest -Uri "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -Method POST -Headers @{accept='application/json'} -Body "refresh_token=$RefreshToken" if($results.StatusCode -ne 200) { Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your VMC Refresh Token is valid and try again" break From ab266189c28cb5ccceb796ba9af49083ad804ebb Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Mon, 19 Aug 2019 13:30:22 -0500 Subject: [PATCH 151/175] Fix for Get-HVInternalName and GlobalEntitlementId --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 67a99cd..8e8b1c5 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -7767,7 +7767,7 @@ function Get-HVPoolSpec { if (! $DesktopInfoPsObj.GlobalEntitlementData.GlobalEntitlement) { $DesktopPsObj.GlobalEntitlementData = $null } else { - $entityId.Id = $DesktopInfoPsObj.GlobalEntitlementData.GlobalEntitlement.Id + $entityId = $DesktopInfoPsObj.GlobalEntitlementData.GlobalEntitlement $DesktopPsObj.GlobalEntitlementData = Get-HVInternalName -EntityId $entityId } @@ -8025,7 +8025,13 @@ function Get-HVInternalName { } 'GlobalApplicationEntitlement' { $info = $services.GlobalApplicationEntitlement.GlobalApplicationEntitlement_Get($EntityId) - return $info.Base.displayName + return $info.base.displayName + } + 'GlobalEntitlement' { + $GlobalEntitlementID = New-Object VMware.Hv.GlobalEntitlementId + $GlobalEntitlementID.Id = $EntityID.Id + $info = $services.GlobalEntitlement.GlobalEntitlement_Get($GlobalEntitlementID) + return $info.base.displayname } default { $base64String = $tokens[$tokens.Length-1] @@ -12776,4 +12782,4 @@ Export-ModuleMember -Function Get-HVEventDatabase, Set-HVEventDatabase, Clear-HV # vCenter Server related Export-ModuleMember -Function Get-HVvCenterServer, Get-HVvCenterServerHealth # Misc/other related -Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot +Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot \ No newline at end of file From 7a39d2831487a0ba6f813a3efcdfc029d1642874 Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Fri, 20 Dec 2019 10:39:42 -0600 Subject: [PATCH 152/175] Fix issue with manual parameterset on new-hvpool --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 8e8b1c5..6931a0d 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -3746,6 +3746,7 @@ function New-HVPool { #desktopSpec.desktopSettings.logoffSettings.allowUsersToResetMachines [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [boolean]$allowUsersToResetMachines = $false, #desktopSpec.desktopSettings.logoffSettings.allowMultipleSessionsPerUser @@ -3777,23 +3778,27 @@ function New-HVPool { #desktopSpec.desktopSettings.logoffSettings.supportedDisplayProtocols [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [ValidateSet('RDP', 'PCOIP', 'BLAST')] [string[]]$supportedDisplayProtocols = @('RDP', 'PCOIP', 'BLAST'), #desktopSpec.desktopSettings.logoffSettings.defaultDisplayProtocol [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] - [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'LINKED_CLONE')] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [ValidateSet('RDP', 'PCOIP', 'BLAST')] [string]$defaultDisplayProtocol = 'PCOIP', #desktopSpec.desktopSettings.logoffSettings.allowUsersToChooseProtocol [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [int]$allowUsersToChooseProtocol = $true, #desktopSpec.desktopSettings.logoffSettings.enableHTMLAccess [Parameter(Mandatory = $false,ParameterSetName = 'INSTANT_CLONE')] [Parameter(Mandatory = $false,ParameterSetName = "LINKED_CLONE")] + [Parameter(Mandatory = $false,ParameterSetName = 'MANUAL')] [boolean]$enableHTMLAccess = $false, # DesktopPCoIPDisplaySettings From fa9a3c502662348859169b208bd3ca618babf6fb Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Fri, 20 Dec 2019 10:47:06 -0600 Subject: [PATCH 153/175] Iterate version number to 1.3.1 --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 6931a0d..a140dd0 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -1,5 +1,5 @@ #Script Module : VMware.Hv.Helper -#Version : 1.3 +#Version : 1.3.1 #Copyright © 2016 VMware, Inc. All Rights Reserved. From adfe78f236a43ad48a5829f4d9c6442790a3b2ce Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Fri, 20 Dec 2019 10:49:26 -0600 Subject: [PATCH 154/175] One more place to iterate version number --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psd1 index 7edd3bc..91e9943 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.3' +ModuleVersion = '1.3.1' # ID used to uniquely identify this module GUID = '6d3f7fb5-4e52-43d8-91e1-f65f72532a1d' From 0d4ba8b4dc9d8a3efdb7834e99b46fe10d18a856 Mon Sep 17 00:00:00 2001 From: Baoyin Qiao Date: Mon, 23 Dec 2019 17:34:19 +0800 Subject: [PATCH 155/175] Update VMware.VMEncryption.psm1 Update the Set-VMHostCryptoKey to make the RemoveKeys() only apply to vSphere 6.5 and not remove host key when it is in use. --- .../VMware.VMEncryption/VMware.VMEncryption.psm1 | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 b/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 index df37e98..21df608 100644 --- a/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 +++ b/Modules/VMware.VMEncryption/VMware.VMEncryption.psm1 @@ -224,11 +224,19 @@ Function Set-VMHostCryptoKey { Write-Error "Change Crypto Key on VMHost: $VMHost failed.$_!`n" return } + # Remove the old host key only when connected to vSphere 6.5 to ensure any coredumps are recrypted with the new host key; + # For vSphere 6.7 and above, the ConfigureCryptoKey() will automatically remove the old host key when successfully changed + # the host key. + # Adding below condition to avoid misunderstanding when running against vSphere 6.7 and above. - # 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) + $VCVersion = ($global:DefaultVIServer).Version + $MajorVersion = $VCVersion.split('.')[0] + $MinorVersion = $VCVersion.split('.')[1] + if ($MajorVersion -eq 6 -And $MinorVersion -eq 5) { + Write-Verbose "Removing the old hostKey: $($OldKey.KeyId) on $VMHost...`n" + $VMHostCM = Get-View $VMHostView.ConfigManager.CryptoManager + $VMHostCM.RemoveKeys($OldKey, $false) + } } } From 39cc775d25470dc3f1b60a7301e65269d150a296 Mon Sep 17 00:00:00 2001 From: mtelvers Date: Fri, 3 Jan 2020 09:33:42 +0000 Subject: [PATCH 156/175] Update VMware.HV.Helper.psm1 Add -clearGlobalEntitlement to Set-HVPool --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 67a99cd..98baa80 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -6207,6 +6207,9 @@ function Set-HVPool { [string] $ResourcePool, + [Parameter(Mandatory = $false)] + [switch]$clearGlobalEntitlement, + [Parameter(Mandatory = $false)] [boolean]$allowUsersToChooseProtocol, @@ -6319,6 +6322,12 @@ function Set-HVPool { } } + if ($clearGlobalEntitlement) { + $update = New-Object VMware.Hv.MapEntry + $update.key = 'globalEntitlementData.globalEntitlement' + $updates += $update + } + $info = $services.PodFederation.PodFederation_get() if ($globalEntitlement -and ("ENABLED" -eq $info.localPodStatus.status)) { $QueryFilterEquals = New-Object VMware.Hv.QueryFilterEquals From 254e062e52d2fc919b3a5301a81fd143897a83b8 Mon Sep 17 00:00:00 2001 From: Joshua Grall Date: Fri, 10 Jan 2020 14:00:27 -0600 Subject: [PATCH 157/175] Fixing path --- Modules/ContentLibrary/ContentLibrary.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/ContentLibrary/ContentLibrary.psm1 b/Modules/ContentLibrary/ContentLibrary.psm1 index 25e6a58..3443897 100644 --- a/Modules/ContentLibrary/ContentLibrary.psm1 +++ b/Modules/ContentLibrary/ContentLibrary.psm1 @@ -199,7 +199,7 @@ Function Get-ContentLibraryItemFiles { foreach($file in $files) { if($contentLibraryItemStorageService.get($itemId, $($file.name)).storage_backing.type -eq "DATASTORE"){ - $filepath = $contentLibraryItemStorageService.get($itemId, $($file.name)).storage_uris.AbsolutePath.split("/")[5..7] -join "/" + $filepath = $contentLibraryItemStorageService.get($itemId, $($file.name)).storage_uris.segments -notmatch '(^/$|^vmfs$*|^volumes$*|vsan:.*)' -join '' $fullfilepath = "[$($datastore.name)] $filepath" } else{ From 3f430900cf68465a6b8068721db7749e7e7c7ae3 Mon Sep 17 00:00:00 2001 From: Rob Nelson Date: Thu, 23 Jan 2020 16:33:43 -0500 Subject: [PATCH 158/175] Make `-StartTime` argument to `Start-HVPool` take effect --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index dbf144c..67ffef3 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -7010,7 +7010,8 @@ 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 - if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { + if ($startTime) { $spec.Settings.startTime = $startTime } + if (!$confirmFlag -OR $pscmdlet.ShouldProcess($poolList.$item)) { $desktop_helper.Desktop_Update($services,$item,$updates) } Write-Host "Performed recompose task on Pool: " $PoolList.$item @@ -12796,4 +12797,4 @@ Export-ModuleMember -Function Get-HVEventDatabase, Set-HVEventDatabase, Clear-HV # vCenter Server related Export-ModuleMember -Function Get-HVvCenterServer, Get-HVvCenterServerHealth # Misc/other related -Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot \ No newline at end of file +Export-ModuleMember -Function Get-HVlicense, Set-HVlicense, Get-HVHealth, Set-HVInstantCloneMaintenance, Get-HVBaseImageVM, Get-HVBaseImageVMSnapshot From 1b0dd9f42e13490bc5ce89c5bd80f0cc5920951f Mon Sep 17 00:00:00 2001 From: William Lam Date: Wed, 5 Feb 2020 05:48:12 -0800 Subject: [PATCH 159/175] Workspace One Access PS Module --- .../VMware.WorkspaceOneAccess.psd1 | 90 +++ .../VMware.WorkspaceOneAccess.psm1 | 572 ++++++++++++++++++ 2 files changed, 662 insertions(+) create mode 100644 Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 create mode 100644 Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 diff --git a/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 new file mode 100644 index 0000000..b25bf20 --- /dev/null +++ b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 @@ -0,0 +1,90 @@ +# +# Module manifest for module 'VMware.HCX' +# +# Generated by: wlam@vmware.com +# +# Generated on: 09/11/18 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'VMware.WorkspaceOneAccess.psm1' + +# Version number of this module. +ModuleVersion = '1.0.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = 'VMware.WorkspaceOneAccess' + +# Author of this module +Author = 'William Lam' + +# Company or vendor of this module +CompanyName = 'VMware' + +# Copyright statement for this module +Copyright = '(c) 2020 VMware. All rights reserved.' + +# Description of the functionality provided by this module +Description = 'PowerShell Module for Workspace One Access' + +# Minimum version of the Windows PowerShell engine required by this module +PowerShellVersion = '6.0' + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. + +FunctionsToExport = 'Connect-WorkspaceOneAccess','Get-WSDirectory','Get-WSIdentityProvider','Get-WSOrgNetwork','New-WS3rdPartyIdentityProvider','New-WSJitDirectory','Remove-WS3rdPartyIdentityProvider','Remove-WSDirectory' + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() + +# Variables to export from this module +VariablesToExport = '*' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} \ No newline at end of file diff --git a/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 new file mode 100644 index 0000000..9e2e978 --- /dev/null +++ b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 @@ -0,0 +1,572 @@ +Function Connect-WorkspaceOneAccess { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Log into Workspace One Access (formally VMware Identity Manager) + .DESCRIPTION + This cmdlet creates $global:workspaceOneAccessConnection object containing valid refresh token to vIDM/Workspace One Access + .EXAMPLE + Connect-WorkspaceOneAccess -Tenant $Tenant -ClientId $ClientId -ClientSecret $ClientSecret +#> + Param ( + [Parameter(Mandatory=$true)][String]$Tenant, + [Parameter(Mandatory=$true)][String]$ClientId, + [Parameter(Mandatory=$true)][String]$ClientSecret, + [Switch]$Troubleshoot + ) + + $text = "${ClientId}:${ClientSecret}" + $base64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($text)) + + $headers = @{ + "Authorization"="Basic $base64"; + "Content-Type"="application/x-www-form-urlencoded"; + } + + $oauthUrl = "https://${Tenant}/SAAS/auth/oauthtoken?grant_type=client_credentials" + $method = "POST" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$oauthUrl`n" + } + + $results = Invoke-WebRequest -Uri $oauthUrl -Method $method -Headers $headers + if($results.StatusCode -ne 200) { + Write-Host -ForegroundColor Red "Failed to retrieve Access Token, please ensure your ClientId and Client Secret is valid" + break + } + $accessToken = ($results.Content | ConvertFrom-Json).access_token + + $authHeader = @{ + "Authorization"="Bearer $accessToken"; + } + + $global:workspaceOneAccessConnection = new-object PSObject -Property @{ + 'Server' = "https://$Tenant" + 'headers' = $authHeader + } + $global:workspaceOneAccessConnection +} + +Function Get-WSDirectory { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retrieves all Directories within Workspace One Access + .DESCRIPTION + This cmdlet retrieves all Directories within Workspace One Access + .EXAMPLE + Get-WSDirectory + .EXAMPLE + Get-WSDirectory -Name +#> + Param ( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + $directoryHeaders = @{ + "Accept"="application/vnd.vmware.horizon.manager.connector.management.directory.list+json"; + "Content-Type"="application/vnd.vmware.horizon.manager.connector.management.directory.list+json"; + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $directoryUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/connectormanagement/directoryconfigs?includeJitDirectories=true" + $method = "GET" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$directoryUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving Directory" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + $directories = ([System.Text.Encoding]::ASCII.GetString($results.Content) | ConvertFrom-Json).items + + if ($PSBoundParameters.ContainsKey("Name")){ + $directories = $directories | where {$_.name -eq $Name} + } + + $directories + } +} + +Function Remove-WSDirectory { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Deletes a specific Workspace One Access Directory + .DESCRIPTION + This cmdlet deletes a specific directory within Workspace One Access + .EXAMPLE + Remove-WSDirectory -Name +#> + Param ( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + $directory = Get-WSDirectory -Name $Name + + if($directory) { + + $directoryHeaders = @{ + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $directoryUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/connectormanagement/directoryconfigs/$($directory.directoryId)?asyncDelete=true" + $method = "DELETE" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$directoryUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in deleting new Directory" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + Write-Host "`nSuccessfully deleted Directory $Name ..." + } + } else { + Write-Host "`nUnable to find Directory $Name" + } +} + +Function New-WSJitDirectory { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a Just-in-Time (Jit) Directory in Workspace One Access + .DESCRIPTION + This cmdlet creates a Just-in-Time (Jit) Directory in Workspace One Access + .EXAMPLE + New-WSJitDirectory -Name +#> + Param ( + [Parameter(Mandatory=$false)][String]$Name, + [Parameter(Mandatory=$false)][String]$Domain, + [Switch]$Troubleshoot + ) + + $directoryHeaders = @{ + "Accept"="application/vnd.vmware.horizon.manager.connector.management.directory.jit+json"; + "Content-Type"="application/vnd.vmware.horizon.manager.connector.management.directory.jit+json" + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $directoryUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/connectormanagement/directoryconfigs" + $method = "POST" + + $json = @{ + name = $Name + domains = @($Domain) + } + + $body = $json | ConvertTo-Json + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$directoryUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders -Body $body -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders -Body $body + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new Jit Directory" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 201) { + Write-Host "`nSuccessfully created Jit Directory $Name ..." + ([System.Text.Encoding]::ASCII.GetString($results.Content) | ConvertFrom-Json) + } +} + +Function Get-WSOrgNetwork { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retreives all Org Networks within Workspace One Access + .DESCRIPTION + This cmdlet retreives all Org Networks within Workspace One Access + .EXAMPLE + Get-WSOrgNetwork + .EXAMPLE + Get-WSOrgNetwork -Name +#> + Param ( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + $listOrgNetworkHeaders = @{ + "Accept"="application/vnd.vmware.horizon.manager.orgnetwork.list+json"; + "Content-Type"="application/vnd.vmware.horizon.manager.orgnetwork.list+json" + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $orgNetworkUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/orgnetworks" + $method = "GET" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$orgNetworkUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $orgNetworkUrl -Method $method -UseBasicParsing -Headers $listOrgNetworkHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $orgNetworkUrl -Method $method -UseBasicParsing -Headers $listOrgNetworkHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new Directory" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + $networks = ([System.Text.Encoding]::ASCII.GetString($results.Content) | ConvertFrom-Json).items + + if ($PSBoundParameters.ContainsKey("Name")){ + $networks = $networks | where {$_.name -eq $Name} + } + + $networks + } +} + +Function Get-WSIdentityProvider { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Retreives all Identity Providers within Workspace One Access + .DESCRIPTION + This cmdlet retreives all Identity Providers within Workspace One Access + .EXAMPLE + Get-WSIdentityProvider + .EXAMPLE + Get-WSIdentityProvider -Name +#> + Param ( + [Parameter(Mandatory=$false)][String]$Name, + [Switch]$Troubleshoot + ) + + $listOrgNetworkHeaders = @{ + "Accept"="application/vnd.vmware.horizon.manager.identityprovider.summary.list+json"; + "Content-Type"="application/vnd.vmware.horizon.manager.identityprovider.summary.list+json" + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $providerUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/identityProviders?onlyEnabledAdapters=true" + $method = "GET" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$providerUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $providerUrl -Method $method -UseBasicParsing -Headers $listOrgNetworkHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $providerUrl -Method $method -UseBasicParsing -Headers $listOrgNetworkHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving Directory" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + $providers = ([System.Text.Encoding]::ASCII.GetString($results.Content) | ConvertFrom-Json).items + + if ($PSBoundParameters.ContainsKey("Name")){ + $providers = $providers | where {$_.name -eq $Name} + } + + $providers + } +} + +Function New-WS3rdPartyIdentityProvider { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Creates a new 3rd Party Identity Providers within Workspace One Access + .DESCRIPTION + This cmdlet creates a new 3rd party Identity Provider within Workspace One Access + .EXAMPLE + New-WS3rdPartyIdentityProvider + .EXAMPLE + New-WS3rdPartyIdentityProvider -Name "AWS Directory Service" -DirectoryName "VMware" -NetworkName "ALL RANGES" -MetadataFile FederationMetadata.xml +#> + Param ( + [Parameter(Mandatory=$true)][String]$Name, + [Parameter(Mandatory=$true)][String]$DirectoryName, + [Parameter(Mandatory=$true)][String]$NetworkName, + [Parameter(Mandatory=$true)][String]$MetadataFile, + [Switch]$Troubleshoot + ) + + $idpDirectory = Get-WSDirectory -Name $DirectoryName + $network = Get-WSOrgNetwork -Name $NetworkName + $metadataXML = Get-Content -Raw $MetadataFile + + $idpBody = [pscustomobject] @{ + "authMethods" = @( + @{ + "authMethodId" = 1; + "authScore" = 1; + "defaultMethod" = $false; + "authMethodOrder" = 0; + "authMethodName" = "adfsPassword"; + "samlAuthnContext" = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"; + } + ); + "identityProviderType" = "MANUAL"; + "nameIdFormatType" = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"; + "identityFromSamlAttribute" = $false; + "friendlyName" = $Name; + "metaData" = "$metadataXML"; + "preferredBinding" = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"; + "jitEnabled" = "true"; + "saml2IdPSLOConfiguration" = @{ + "sendSLORequest" = $true; + } + "directoryConfigurations" = @( + [pscustomobject] @{ + "type" = $idpDirectory.type; + "name" = $idpDirectory.name; + "directoryId" = $idpDirectory.directoryId; + "userstoreId" = $idpDirectory.userstoreId; + "countDomains" = $idpDirectory.countDomains; + "deleteInProgress" = $false; + "migratedToEnterpriseService" = $false; + "syncConfigurationEnabled" = $false; + } + ); + "nameIdFormatAttributeMappings" = [pscustomobject] @{ + "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" = "emails"; + "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" = "id"; + "urn:oasis:names:tc:SAML:2.0:nameid-format:transient" = "userName"; + }; + "orgNetworks" = @( + [pscustomobject] @{ + "name" = $network.name; + "ipAddressRanges" = $network.ipAddressRanges; + "uuid" = $network.uuid; + "description" = $network.description; + "defaultNetwork" = $network.defaultNetwork; + } + ); + "description" = ""; + "nIDPStatus" = 1; + "idpUrl" = $null; + "name" = $Name; + } + + $idpHeaders = @{ + "Accept"="application/vnd.vmware.horizon.manager.external.identityprovider+json"; + "Content-Type"="application/vnd.vmware.horizon.manager.external.identityprovider+json"; + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $body = $idpBody | ConvertTo-Json -Depth 10 + + $identityProviderUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/identityProviders" + $method = "POST" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$directoryUrl`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $identityProviderUrl -Method $method -UseBasicParsing -Headers $idpHeaders -Body $body -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $identityProviderUrl -Method $method -UseBasicParsing -Headers $idpHeaders -Body $body + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in creating new Identity Provider" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 201) { + Write-Host "`nSuccessfully created new Identity Provider $Name ..." + ([System.Text.Encoding]::ASCII.GetString($results.Content) | ConvertFrom-Json) | Select Name, Id + } +} + +Function Remove-WS3rdPartyIdentityProvider { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 02/04/2020 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Deletes a specific 3rd Party Identity Provider within Workspace One Access + .DESCRIPTION + This cmdlet deletes a specific 3rd Party Identity Provider within Workspace One Access + .EXAMPLE + Remove-WS3rdPartyIdentityProvider -Name +#> + Param ( + [Parameter(Mandatory=$true)][String]$Name, + [Switch]$Troubleshoot + ) + + $idp = Get-WSIdentityProvider -Name $Name + + if($idp) { + $identityProviderHeaders = @{ + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $identityProviderURL = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/identityProviders/$($idp.id)" + $method = "DELETE" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$identityProviderURL`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $identityProviderURL -Method $method -UseBasicParsing -Headers $identityProviderHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $identityProviderURL -Method $method -UseBasicParsing -Headers $identityProviderHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in deleting Identity Provider" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + Write-Host "`nSuccessfully deleted Identity Provider $Name ..." + } + } else { + Write-Host "`nUnable to find Identity Provider $Name" + } +} \ No newline at end of file From 118739b8fba376e4d437e0647ead4c7e9aed977b Mon Sep 17 00:00:00 2001 From: Matt Frey Date: Thu, 6 Feb 2020 13:49:04 -0600 Subject: [PATCH 160/175] Minor cleanup and platyPS help --- Modules/VMware.Hv.Helper/README.md | 13 +- .../VMware.Hv.Helper/VMware.HV.Helper.psm1 | 81 +- .../VMware.Hv.Helper/docs/Add-HVDesktop.md | 188 ++ .../VMware.Hv.Helper/docs/Add-HVRDSServer.md | 138 ++ .../docs/Clear-HVEventDatabase.md | 100 + .../VMware.Hv.Helper/docs/Connect-HVEvent.md | 127 ++ .../docs/Disconnect-HVEvent.md | 71 + .../docs/Get-HVApplication.md | 110 + .../docs/Get-HVBaseImageVM.md | 143 ++ .../docs/Get-HVEntitlement.md | 154 ++ Modules/VMware.Hv.Helper/docs/Get-HVEvent.md | 201 ++ .../docs/Get-HVEventDatabase.md | 69 + Modules/VMware.Hv.Helper/docs/Get-HVFarm.md | 179 ++ .../docs/Get-HVFarmSummary.md | 179 ++ .../docs/Get-HVGlobalEntitlement.md | 118 ++ .../docs/Get-HVGlobalSession.md | 69 + .../docs/Get-HVGlobalSettings.md | 70 + Modules/VMware.Hv.Helper/docs/Get-HVHealth.md | 95 + .../VMware.Hv.Helper/docs/Get-HVHomeSite.md | 89 + .../docs/Get-HVInternalName.md | 120 ++ .../docs/Get-HVLocalSession.md | 69 + .../VMware.Hv.Helper/docs/Get-HVMachine.md | 180 ++ .../docs/Get-HVMachineSummary.md | 195 ++ .../docs/Get-HVPodFederation.md | 71 + Modules/VMware.Hv.Helper/docs/Get-HVPool.md | 218 ++ .../VMware.Hv.Helper/docs/Get-HVPoolSpec.md | 142 ++ .../docs/Get-HVPoolSummary.md | 218 ++ .../docs/Get-HVPreInstalledApplication.md | 85 + .../docs/Get-HVQueryFilter.md | 308 +++ .../docs/Get-HVQueryResult.md | 181 ++ .../docs/Get-HVResourceStructure.md | 70 + Modules/VMware.Hv.Helper/docs/Get-HVSite.md | 71 + .../VMware.Hv.Helper/docs/Get-HVlicense.md | 69 + .../docs/Get-HVvCenterServer.md | 90 + .../docs/Get-HVvCenterServerHealth.md | 97 + .../docs/New-HVEntitlement.md | 221 ++ Modules/VMware.Hv.Helper/docs/New-HVFarm.md | 1133 ++++++++++ .../docs/New-HVGlobalEntitlement.md | 329 +++ .../VMware.Hv.Helper/docs/New-HVHomeSite.md | 178 ++ .../docs/New-HVManualApplication.md | 383 ++++ .../docs/New-HVPodFederation.md | 72 + Modules/VMware.Hv.Helper/docs/New-HVPool.md | 1830 +++++++++++++++++ .../docs/New-HVPreInstalledApplication.md | 215 ++ Modules/VMware.Hv.Helper/docs/New-HVSite.md | 101 + .../VMware.Hv.Helper/docs/Register-HVPod.md | 127 ++ .../docs/Remove-HVApplication.md | 118 ++ .../docs/Remove-HVApplicationIcon.md | 119 ++ .../docs/Remove-HVEntitlement.md | 178 ++ .../VMware.Hv.Helper/docs/Remove-HVFarm.md | 158 ++ .../docs/Remove-HVGlobalEntitlement.md | 147 ++ .../VMware.Hv.Helper/docs/Remove-HVMachine.md | 154 ++ .../docs/Remove-HVPodFederation.md | 72 + .../VMware.Hv.Helper/docs/Remove-HVPool.md | 186 ++ .../VMware.Hv.Helper/docs/Remove-HVSite.md | 86 + .../VMware.Hv.Helper/docs/Reset-HVMachine.md | 129 ++ .../docs/Set-HVApplication.md | 340 +++ .../docs/Set-HVApplicationIcon.md | 134 ++ .../docs/Set-HVEventDatabase.md | 212 ++ Modules/VMware.Hv.Helper/docs/Set-HVFarm.md | 279 +++ .../docs/Set-HVGlobalEntitlement.md | 253 +++ .../docs/Set-HVGlobalSettings.md | 520 +++++ .../docs/Set-HVInstantCloneMaintenance.md | 147 ++ .../VMware.Hv.Helper/docs/Set-HVMachine.md | 221 ++ .../docs/Set-HVPodFederation.md | 86 + Modules/VMware.Hv.Helper/docs/Set-HVPool.md | 361 ++++ Modules/VMware.Hv.Helper/docs/Set-HVSite.md | 117 ++ .../VMware.Hv.Helper/docs/Set-HVlicense.md | 86 + Modules/VMware.Hv.Helper/docs/Start-HVFarm.md | 465 +++++ Modules/VMware.Hv.Helper/docs/Start-HVPool.md | 399 ++++ .../VMware.Hv.Helper/docs/Unregister-HVPod.md | 110 + 70 files changed, 14002 insertions(+), 42 deletions(-) create mode 100755 Modules/VMware.Hv.Helper/docs/Add-HVDesktop.md create mode 100755 Modules/VMware.Hv.Helper/docs/Add-HVRDSServer.md create mode 100755 Modules/VMware.Hv.Helper/docs/Clear-HVEventDatabase.md create mode 100755 Modules/VMware.Hv.Helper/docs/Connect-HVEvent.md create mode 100755 Modules/VMware.Hv.Helper/docs/Disconnect-HVEvent.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVApplication.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVBaseImageVM.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVEvent.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVEventDatabase.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVFarm.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVFarmSummary.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVGlobalEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVGlobalSession.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVGlobalSettings.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVHealth.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVHomeSite.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVInternalName.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVLocalSession.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVMachine.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVMachineSummary.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVPodFederation.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVPool.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVPoolSpec.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVPoolSummary.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVPreInstalledApplication.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVQueryFilter.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVQueryResult.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVResourceStructure.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVSite.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVlicense.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVvCenterServer.md create mode 100755 Modules/VMware.Hv.Helper/docs/Get-HVvCenterServerHealth.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVFarm.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVGlobalEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVHomeSite.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVManualApplication.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVPodFederation.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVPool.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVPreInstalledApplication.md create mode 100755 Modules/VMware.Hv.Helper/docs/New-HVSite.md create mode 100755 Modules/VMware.Hv.Helper/docs/Register-HVPod.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVApplication.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVApplicationIcon.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVFarm.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVGlobalEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVMachine.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVPodFederation.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVPool.md create mode 100755 Modules/VMware.Hv.Helper/docs/Remove-HVSite.md create mode 100755 Modules/VMware.Hv.Helper/docs/Reset-HVMachine.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVApplication.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVApplicationIcon.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVEventDatabase.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVFarm.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVGlobalEntitlement.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVGlobalSettings.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVInstantCloneMaintenance.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVMachine.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVPodFederation.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVPool.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVSite.md create mode 100755 Modules/VMware.Hv.Helper/docs/Set-HVlicense.md create mode 100755 Modules/VMware.Hv.Helper/docs/Start-HVFarm.md create mode 100755 Modules/VMware.Hv.Helper/docs/Start-HVPool.md create mode 100755 Modules/VMware.Hv.Helper/docs/Unregister-HVPod.md diff --git a/Modules/VMware.Hv.Helper/README.md b/Modules/VMware.Hv.Helper/README.md index fe87153..bce3072 100644 --- a/Modules/VMware.Hv.Helper/README.md +++ b/Modules/VMware.Hv.Helper/README.md @@ -1,4 +1,4 @@ -Prerequisites/Steps to use this module: +# 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). @@ -6,15 +6,24 @@ Prerequisites/Steps to use this module: 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: +# Example script to connect ViewAPI service +``` Import-Module VMware.VimAutomation.HorizonView + # Connection to view API service $hvServer = Connect-HVServer -server $hvServices = $hvserver.ExtensionData + +# List Connection Servers $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.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 67ffef3..89e3dfc 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -647,8 +647,8 @@ function Connect-HVEvent { 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 + $password = Read-Host 'Database Password' -AsSecureString + $hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' -DbPassword $password Connecting to the database with customised user name and password, with password being a SecureString. .OUTPUTS @@ -854,13 +854,13 @@ function Get-HVEvent { String that can applied in filtering on 'Message' column. .EXAMPLE - C:\PS>$e = Get-HVEvent -hvDbServer $hvDbServer - C:\PS>$e.Events + $e = Get-HVEvent -hvDbServer $hvDbServer + $e.Events Querying all the database events on database $hvDbServer. .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 + $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 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'. @@ -1729,20 +1729,21 @@ function Get-HVQueryFilter { Creates queryFilterStartsWith with given parameters memberName and memberValue .EXAMPLE - C:\PS>$filter = Get-HVQueryFilter data.name -Startswith vmware - C:\PS>Get-HVQueryFilter -Not $filter + $filter = Get-HVQueryFilter data.name -Startswith vmware + Get-HVQueryFilter -Not $filter Creates queryFilterNot with given parameter filter .EXAMPLE - 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) + $filter1 = Get-HVQueryFilter data.name -Startswith vmware + $filter2 = Get-HVQueryFilter data.name -Contains pool + Get-HVQueryFilter -And @($filter1, $filter2) + Creates queryFilterAnd with given parameter filters array .EXAMPLE - 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) + $filter1 = Get-HVQueryFilter data.name -Startswith vmware + $filter2 = Get-HVQueryFilter data.name -Contains pool + Get-HVQueryFilter -Or @($filter1, $filter2) Creates queryFilterOr with given parameter filters array .OUTPUTS @@ -1881,8 +1882,8 @@ function Get-HVQueryResult { Returns query results of entityType DesktopSummaryView with given filter .EXAMPLE - C:\PS>$myFilter = Get-HVQueryFilter data.name -Contains vmware - C:\PS>Get-HVQueryResult -EntityType DesktopSummaryView -Filter $myFilter -SortBy desktopSummaryData.displayName -SortDescending $false + $myFilter = Get-HVQueryFilter data.name -Contains vmware + 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 @@ -3587,17 +3588,17 @@ function New-HVPool { 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 -StopProvisioningOnError $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 -StopProvisioningOnError $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 .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 -Confirm:$false + Create new automated linked clone pool by using JSON spec file .EXAMPLE - C:\PS>Get-HVPool -PoolName 'vmwarepool' | New-HVPool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; + Get-HVPool -PoolName 'vmwarepool' | New-HVPool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; (OR) - C:\PS>$vmwarepool = Get-HVPool -PoolName 'vmwarepool'; New-HVPool -ClonePool $vmwarepool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; + $vmwarepool = Get-HVPool -PoolName 'vmwarepool'; New-HVPool -ClonePool $vmwarepool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; Clones new pool by using existing pool configuration .EXAMPLE @@ -5660,8 +5661,8 @@ function Remove-HVFarm { 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 - C:\PS>$farm1 = Get-HVFarm -FarmName 'Farm-01' - C:\PS>Remove-HVFarm -Farm $farm1 + $farm1 = Get-HVFarm -FarmName 'Farm-01' + 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 @@ -6444,8 +6445,8 @@ function Start-HVFarm { Requests a recompose of RDS Servers in the specified automated farm .EXAMPLE - 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 + $myTime = Get-Date '10/03/2016 12:30:00' + 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 @@ -6828,8 +6829,8 @@ function Start-HVPool { Requests a refresh of machines in the specified pool .EXAMPLE - C:\PS>$myTime = Get-Date '10/03/2016 12:30:00' - C:\PS>Start-HVPool -Rebalance -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -StartTime $myTime + $myTime = Get-Date '10/03/2016 12:30:00' + Start-HVPool -Rebalance -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -StartTime $myTime Requests a rebalance of machines in a pool with specified time .EXAMPLE @@ -10700,7 +10701,7 @@ function Get-HVHealth { [System.gc]::collect() } -function new-hvpodfederation { +function New-HVPodFederation { <# .Synopsis Initiates a Horizon View Pod Federation (Cloud Pod Architecture) @@ -10751,7 +10752,7 @@ function new-hvpodfederation { [System.gc]::collect() } -function remove-hvpodfederation { +function Remove-HVPodFederation { <# .Synopsis Uninitiates a Horizon View Pod Federation (Cloud Pod Architecture) @@ -10852,7 +10853,7 @@ function Get-HVPodFederation { [System.gc]::collect() } -function register-hvpod { +function Register-HVPod { <# .Synopsis Registers a pod in a Horizon View Pod Federation (Cloud Pod Architecture) @@ -10875,8 +10876,8 @@ function register-hvpod { first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE - C:\PS>$adpassword = Read-Host 'Domain Password' -AsSecureString - C:\PS>register-hvpod -remoteconnectionserver "servername" -username "user\domain" -password $adpassword + $adpassword = Read-Host 'Domain Password' -AsSecureString + register-hvpod -remoteconnectionserver "servername" -username "user\domain" -password $adpassword .EXAMPLE register-hvpod -remoteconnectionserver "servername" -username "user\domain" @@ -10939,7 +10940,7 @@ function register-hvpod { [System.gc]::collect() } -function unregister-hvpod { +function Unregister-HVPod { <# .Synopsis Removes a pod from a podfederation @@ -11029,7 +11030,7 @@ function unregister-hvpod { [System.gc]::collect() } -function set-hvpodfederation { +function Set-HVPodFederation { <# .Synopsis Used to change the name of a Horizon View Pod Federation (Cloud Pod Architecture) @@ -11088,7 +11089,7 @@ function set-hvpodfederation { [System.gc]::collect() } -function get-hvsite { +function Get-HVSite { <# .Synopsis Returns information about the sites within a Horizon View Pod Federation (Cloud Pod Architecture) @@ -11138,7 +11139,7 @@ function get-hvsite { [System.gc]::collect() } -function new-hvsite { +function New-HVSite { <# .Synopsis Creates a new site within a Horizon View Pod Federation (Cloud Pod Architecture) @@ -11203,7 +11204,7 @@ function new-hvsite { [System.gc]::collect() } -function set-hvsite { +function Set-HVSite { <# .Synopsis renames a new site within a Horizon View Pod Federation (Cloud Pod Architecture) @@ -11277,7 +11278,7 @@ function set-hvsite { [System.gc]::collect() } -function remove-hvsite { +function Remove-HVSite { <# .Synopsis renames a new site within a Horizon View Pod Federation (Cloud Pod Architecture) @@ -11803,7 +11804,7 @@ function Set-HVlicense { first element from global:DefaultHVServers would be considered in-place of hvServer .EXAMPLE - set-hvlicense -license "LICENSE-KEY" + Set-HVlicense -license "LICENSE-KEY" Returns information about the sites within a Horizon View Pod Federation. .NOTES diff --git a/Modules/VMware.Hv.Helper/docs/Add-HVDesktop.md b/Modules/VMware.Hv.Helper/docs/Add-HVDesktop.md new file mode 100755 index 0000000..54353ce --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Add-HVDesktop.md @@ -0,0 +1,188 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Add-HVDesktop + +## SYNOPSIS +Adds virtual machine to existing pool + +## SYNTAX + +``` +Add-HVDesktop [-PoolName] [-Machines] [[-Users] ] [[-Vcenter] ] + [[-HvServer] ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +The Add-HVDesktop adds virtual machines to already exiting pools by using view API service object(hvServer) of Connect-HVServer cmdlet. +VMs can be added to any of unmanaged manual, managed manual or Specified name. +This advanced function do basic checks for pool and view API service connection existance, hvServer object is bound to specific connection server. + +## EXAMPLES + +### EXAMPLE 1 +``` +Add-HVDesktop -PoolName 'ManualPool' -Machines 'manualPool1', 'manualPool2' -Confirm:$false +``` + +Add managed manual VMs to existing manual pool + +### EXAMPLE 2 +``` +Add-HVDesktop -PoolName 'SpecificNamed' -Machines 'vm-01', 'vm-02' -Users 'user1', 'user2' +``` + +Add virtual machines to automated specific named dedicated pool + +### EXAMPLE 3 +``` +Add-HVDesktop -PoolName 'SpecificNamed' -Machines 'vm-03', 'vm-04' +``` + +Add machines to automated specific named Floating pool + +### EXAMPLE 4 +``` +Add-HVDesktop -PoolName 'Unmanaged' -Machines 'desktop-1.eng.vmware.com' +``` + +Add machines to unmanged manual pool + +## PARAMETERS + +### -PoolName +Pool name to which new VMs are to be added. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Machines +List of virtual machine names which need to be added to the given pool. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Users +List of virtual machine users for given machines. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Vcenter +Virtual Center server-address (IP or FQDN) of the given pool. +This should be same as provided to the Connection Server while adding the vCenter server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +| | | +|-|-| +| Author | Praveen Mathamsetty | +| Author email | pmathamsetty@vmware.com | +| Version | 1.1 | +| Dependencies | Make sure pool already exists before adding VMs to it. | + + +### 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Add-HVRDSServer.md b/Modules/VMware.Hv.Helper/docs/Add-HVRDSServer.md new file mode 100755 index 0000000..6018ad7 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Add-HVRDSServer.md @@ -0,0 +1,138 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Add-HVRDSServer + +## SYNOPSIS +Add RDS Servers to an existing farm. + +## SYNTAX + +``` +Add-HVRDSServer [-FarmName] [-RdsServers] [[-HvServer] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +The Add-HVRDSServer adds RDS Servers to already exiting farms by using view API service object(hvServer) of Connect-HVServer cmdlet. +We can add RDSServers to manual farm type only. +This advanced function do basic checks for farm and view API service connection existance. +This hvServer is bound to specific connection server. + +## EXAMPLES + +### EXAMPLE 1 +``` +Add-HVRDSServer -Farm "manualFarmTest" -RdsServers "vm-for-rds","vm-for-rds-2" -Confirm:$false +``` + +Add RDSServers to manual farm + +## PARAMETERS + +### -FarmName +farm name to which new RDSServers are to be added. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -RdsServers +RDS servers names which need to be added to the given farm. +Provide a comma separated list for multiple names. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### None + +## NOTES +| | | +|-|-| +| 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, 7.1.0 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Clear-HVEventDatabase.md b/Modules/VMware.Hv.Helper/docs/Clear-HVEventDatabase.md new file mode 100755 index 0000000..c3adf9e --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Clear-HVEventDatabase.md @@ -0,0 +1,100 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Clear-HVEventDatabase + +## SYNOPSIS +Clears configurationof the configured Event Database + +## SYNTAX + +``` +Clear-HVEventDatabase [[-HvServer] ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Clears configurationof the configured Event Database + +## EXAMPLES + +### EXAMPLE 1 +``` +Clear-HVEventDatabase +``` + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4 | +| PowerCLI Version | PowerCLI 10 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Connect-HVEvent.md b/Modules/VMware.Hv.Helper/docs/Connect-HVEvent.md new file mode 100755 index 0000000..b1bd759 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Connect-HVEvent.md @@ -0,0 +1,127 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Connect-HVEvent + +## SYNOPSIS +This function is used to connect to the event database configured on Connection Server. + +## SYNTAX + +``` +Connect-HVEvent [[-DbPassword] ] [[-HvServer] ] [[-DbUserName] ] + [] +``` + +## DESCRIPTION +This function queries the specified Connection Server for event database configuration and returns the connection object to it. +If event database is not configured on specified connection server, it will return null. +Currently, Horizon 7 is supporting SQL server and Oracle 12c as event database servers. +To configure event database, goto 'Event Database Configuration' tab in Horizon admin UI. + +## EXAMPLES + +### EXAMPLE 1 +``` +Connect-HVEvent -HvServer $hvServer +``` + +Connecting to the database with default username configured on Connection Server $hvServer. + +### EXAMPLE 2 +``` +$hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' +``` + +Connecting to the database configured on Connection Server $hvServer with customised user name 'system'. + +### EXAMPLE 3 +``` +$hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' -DbPassword 'censored' +``` + +Connecting to the database with customised user name and password. + +### EXAMPLE 4 +``` +$password = Read-Host 'Database Password' -AsSecureString +``` + +$hvDbServer = Connect-HVEvent -HvServer $hvServer -DbUserName 'system' -DbPassword $password +Connecting to the database with customised user name and password, with password being a SecureString. + +## PARAMETERS + +### -DbPassword +Password corresponds to 'dbUserName' user. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DbUserName +User name to be used in database connection. +If not passed, default database user name on the Connection Server will be used. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns a custom object that has database connection as 'dbConnection' property. +## NOTES +| | | +|-|-| +| Author | Paramesh Oddepally. | +| Author email | poddepally@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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Disconnect-HVEvent.md b/Modules/VMware.Hv.Helper/docs/Disconnect-HVEvent.md new file mode 100755 index 0000000..6be94f4 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Disconnect-HVEvent.md @@ -0,0 +1,71 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Disconnect-HVEvent + +## SYNOPSIS +This function is used to disconnect the database connection. + +## SYNTAX + +``` +Disconnect-HVEvent [-HvDbServer] [] +``` + +## DESCRIPTION +This function will disconnect the database connection made earlier during Connect-HVEvent function. + +## EXAMPLES + +### EXAMPLE 1 +``` +Disconnect-HVEvent -HvDbServer $hvDbServer +``` + +Disconnecting the database connection on $hvDbServer. + +## PARAMETERS + +### -HvDbServer +Connection object returned by Connect-HVEvent advanced function. +This is a mandatory input. + +```yaml +Type: PSObject +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### None +## NOTES +| | | +|-|-| +| Author | Paramesh Oddepally. | +| Author email | poddepally@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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVApplication.md b/Modules/VMware.Hv.Helper/docs/Get-HVApplication.md new file mode 100755 index 0000000..0d521cb --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVApplication.md @@ -0,0 +1,110 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVApplication + +## SYNOPSIS +Gets the application information. + +## SYNTAX + +``` +Get-HVApplication [[-ApplicationName] ] [[-HvServer] ] [[-FormatList] ] + [] +``` + +## DESCRIPTION +Gets the application information. +This will be useful to find out whether the specified application exists or not. +If the application name is not specified, this will lists all the applications in the Pod. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVApplication -ApplicationName 'App1' -HvServer $HvServer +``` + +Queries and returns 'App1' information. + +### EXAMPLE 2 +``` +Get-HVApplication -HvServer $HvServer -FormatList:$True +``` + +Lists all the applications in the Pod. + +## PARAMETERS + +### -ApplicationName +Name of the application. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -FormatList +Displays the list of the available applications in Table Format if this parameter is set to True. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns the information of the specified application if it specified, else displays all the available applications. +## NOTES +| | | +|-|-| +| Author | Samiullasha S | +| Author email | ssami@vmware.com | +| Version | 1.2 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.8.0 | +| PowerCLI Version | PowerCLI 11.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVBaseImageVM.md b/Modules/VMware.Hv.Helper/docs/Get-HVBaseImageVM.md new file mode 100755 index 0000000..b534b24 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVBaseImageVM.md @@ -0,0 +1,143 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVBaseImageVM + +## SYNOPSIS +Gets a list of compatible base image virtual machines. + +## SYNTAX + +### Type (Default) +``` +Get-HVBaseImageVM [-HvServer ] [-VirtualCenter ] [-Type ] [] +``` + +### Name +``` +Get-HVBaseImageVM [-HvServer ] [-VirtualCenter ] [-Name ] [] +``` + +## DESCRIPTION +Queries and returns BaseImageVmInfo for the specified vCenter Server. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVBaseImageVM -VirtualCenter 'vCenter1' -Type VDI +``` + +### EXAMPLE 2 +``` +Get-HVBaseImageVM -VirtualCenter $vCenter1 -Type ALL +``` + +### EXAMPLE 3 +``` +Get-HVBaseImageVM -Name '*WIN10*' +``` + +## PARAMETERS + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VirtualCenter +A parameter to specify which vCenter Server to check base image VMs for. +It can be specified as a String, +containing the name of the vCenter, or as a vCenter object as returned by Get-HVvCenterServer. +If the value is +not passed or null then first element returned from Get-HVvCenterServer would be considered in place of VirtualCenter. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type +A parameter to define the type of compatability to check the base image VM list against. +Valid options are 'VDI', 'RDS', or 'ALL' +'VDI' will return all desktop compatible Base Image VMs. +'RDS' will return all RDSH compatible Base Image VMs. +'ALL' will return all Base Image VMs, regardless of compatibility. +The default value is 'ALL'. + +```yaml +Type: Object +Parameter Sets: Type +Aliases: + +Required: False +Position: Named +Default value: VDI +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +The name of a virtual machine (if known), to filter Base Image VMs on. +Wildcards are accepted. +If Name is specified, then Type +is not considered for filtering. + +```yaml +Type: String +Parameter Sets: Name +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns array of object type VMware.Hv.BaseImageVmInfo +## NOTES +| | | +|-|-| +| Author | Matt Frey. | +| Author email | mfrey@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.7 | +| PowerCLI Version | PowerCLI 11.2.0 | +| PowerShell Version | 5.1 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVEntitlement.md b/Modules/VMware.Hv.Helper/docs/Get-HVEntitlement.md new file mode 100755 index 0000000..e7747b0 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVEntitlement.md @@ -0,0 +1,154 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVEntitlement + +## SYNOPSIS +Gets association data between a user/group and a resource + +## SYNTAX + +``` +Get-HVEntitlement [[-User] ] [[-Type] ] [[-ResourceName] ] [[-ResourceType] ] + [[-HvServer] ] [] +``` + +## DESCRIPTION +Provides entitlement Info between a single user/group and a resource that they can be assigned. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVEntitlement -ResourceType Application +``` + +Gets all the entitlements related to application pool + +### EXAMPLE 2 +``` +Get-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'calculator' -ResourceType Application +``` + +Gets entitlements specific to user or group name and application resource + +### EXAMPLE 3 +``` +Get-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'UrlSetting1' -ResourceType URLRedirection +``` + +Gets entitlements specific to user or group and URLRedirection resource + +### EXAMPLE 4 +``` +Get-HVEntitlement -User 'administrator@adviewdev.eng.vmware.com' -ResourceName 'GE1' -ResourceType GlobalEntitlement +``` + +Gets entitlements specific to user or group and GlobalEntitlement resource + +## PARAMETERS + +### -User +User principal name of user or group + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type +Whether or not this is a group or a user. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: User +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceName +The resource(Application, Desktop etc.) name. +Supports only wildcard character '*' when resource type is desktop. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceType +Type of Resource(Application, Desktop etc.) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: Desktop +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVEvent.md b/Modules/VMware.Hv.Helper/docs/Get-HVEvent.md new file mode 100755 index 0000000..043e1ec --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVEvent.md @@ -0,0 +1,201 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVEvent + +## SYNOPSIS +Queries the events from event database configured on Connection Server. + +## SYNTAX + +``` +Get-HVEvent [-HvDbServer] [[-TimePeriod] ] [[-FilterType] ] [[-UserFilter] ] + [[-SeverityFilter] ] [[-TimeFilter] ] [[-ModuleFilter] ] [[-MessageFilter] ] + [] +``` + +## DESCRIPTION +This function is used to query the events information from event database. +It returns the object that has events in five columns as UserName, Severity, EventTime, Module and Message. +EventTime will show the exact time when the event got registered in the database and it follows timezone on database server. +User can apply different filters on the event columns using the filter parameters userFilter, severityFilter, timeFilter, moduleFilter, messageFilter. +Mention that when multiple filters are provided then rows which satisify all the filters will be returned. + +## EXAMPLES + +### EXAMPLE 1 +``` +$e = Get-HVEvent -hvDbServer $hvDbServer +``` + +$e.Events +Querying all the database events on database $hvDbServer. + +### EXAMPLE 2 +``` +$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 +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'. + +## PARAMETERS + +### -HvDbServer +Connection object returned by Connect-HVEvent advanced function. + +```yaml +Type: PSObject +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TimePeriod +Timeperiod of the events that user is interested in. +It can take following four values: + 'day' - Lists last one day events from database + 'week' - Lists last 7 days events from database + 'month' - Lists last 30 days events from database + 'all' - Lists all the events stored in database + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: All +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FilterType +Type of filter action to be applied. +The parameters userfilter, severityfilter, timefilter, modulefilter, messagefilter can be used along with this. +It can take following values: + 'contains' - Retrieves the events that contains the string specified in filter parameters + 'startsWith' - Retrieves the events that starts with the string specified in filter parameters + 'isExactly' - Retrieves the events that exactly match with the string specified in filter parameters + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: Contains +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserFilter +String that can applied in filtering on 'UserName' column. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SeverityFilter +String that can applied in filtering on 'Severity' column. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TimeFilter +String that can applied in filtering on 'EventTime' column. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ModuleFilter +String that can applied in filtering on 'Module' column. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MessageFilter +String that can applied in filtering on 'Message' column. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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. +## NOTES +| | | +|-|-| +| Author | Paramesh Oddepally. | +| Author email | poddepally@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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVEventDatabase.md b/Modules/VMware.Hv.Helper/docs/Get-HVEventDatabase.md new file mode 100755 index 0000000..4cb554b --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVEventDatabase.md @@ -0,0 +1,69 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVEventDatabase + +## SYNOPSIS +Retreives information about the configured Event Database + +## SYNTAX + +``` +Get-HVEventDatabase [[-HvServer] ] [] +``` + +## DESCRIPTION +Collects information about the configured event database for aHorizon View pod + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVEventDatabase +``` + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4 | +| PowerCLI Version | PowerCLI 10 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVFarm.md b/Modules/VMware.Hv.Helper/docs/Get-HVFarm.md new file mode 100755 index 0000000..c8b0718 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVFarm.md @@ -0,0 +1,179 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVFarm + +## SYNOPSIS +This function is used to find farms based on the search criteria provided by the user. + +## SYNTAX + +``` +Get-HVFarm [[-FarmName] ] [[-FarmDisplayName] ] [[-FarmType] ] [[-Enabled] ] + [[-SuppressInfo] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVFarm -FarmName 'Farm-01' +``` + +Queries and returns farmInfo based on given parameter farmName + +### EXAMPLE 2 +``` +Get-HVFarm -FarmName 'Farm-01' -FarmDisplayName 'Sales RDS Farm' +``` + +Queries and returns farmInfo based on given parameters farmName, farmDisplayName + +### EXAMPLE 3 +``` +Get-HVFarm -FarmName 'Farm-01' -FarmType 'MANUAL' +``` + +Queries and returns farmInfo based on given parameters farmName, farmType + +### EXAMPLE 4 +``` +Get-HVFarm -FarmName 'Farm-01' -FarmType 'MANUAL' -Enabled $true +``` + +Queries and returns farmInfo based on given parameters farmName, FarmType etc + +### EXAMPLE 5 +``` +Get-HVFarm -FarmName 'Farm-0*' +``` + +Queries and returns farmInfo based on parameter farmName with wild character * + +## PARAMETERS + +### -FarmName +farmName to be searched + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FarmDisplayName +farmDisplayName to be searched + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FarmType +farmType to be searched. +It can take following values: +"AUTOMATED" - search for automated farms only +'MANUAL' - search for manual farms only + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enabled +search for farms which are enabled + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SuppressInfo +Suppress text info, when no farm found with given search parameters + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns the list of FarmInfo object matching the query criteria. +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVFarmSummary.md b/Modules/VMware.Hv.Helper/docs/Get-HVFarmSummary.md new file mode 100755 index 0000000..153bfb9 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVFarmSummary.md @@ -0,0 +1,179 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVFarmSummary + +## SYNOPSIS +This function is used to find farms based on the search criteria provided by the user. + +## SYNTAX + +``` +Get-HVFarmSummary [[-FarmName] ] [[-FarmDisplayName] ] [[-FarmType] ] + [[-Enabled] ] [[-SuppressInfo] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVFarmSummary -FarmName 'Farm-01' +``` + +Queries and returns farmSummary objects based on given parameter farmName + +### EXAMPLE 2 +``` +Get-HVFarmSummary -FarmName 'Farm-01' -FarmDisplayName 'Sales RDS Farm' +``` + +Queries and returns farmSummary objects based on given parameters farmName, farmDisplayName + +### EXAMPLE 3 +``` +Get-HVFarmSummary -FarmName 'Farm-01' -FarmType 'MANUAL' +``` + +Queries and returns farmSummary objects based on given parameters farmName, farmType + +### EXAMPLE 4 +``` +Get-HVFarmSummary -FarmName 'Farm-01' -FarmType 'MANUAL' -Enabled $true +``` + +Queries and returns farmSummary objects based on given parameters farmName, FarmType etc + +### EXAMPLE 5 +``` +Get-HVFarmSummary -FarmName 'Farm-0*' +``` + +Queries and returns farmSummary objects based on given parameter farmName with wild character * + +## PARAMETERS + +### -FarmName +FarmName to be searched + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FarmDisplayName +FarmDisplayName to be searched + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FarmType +FarmType to be searched. +It can take following values: +"AUTOMATED" - search for automated farms only +'MANUAL' - search for manual farms only + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enabled +Search for farms which are enabled + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SuppressInfo +Suppress text info, when no farm found with given search parameters + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns the list of FarmSummary object matching the query criteria. +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVGlobalEntitlement.md b/Modules/VMware.Hv.Helper/docs/Get-HVGlobalEntitlement.md new file mode 100755 index 0000000..4d1ac8d --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVGlobalEntitlement.md @@ -0,0 +1,118 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVGlobalEntitlement + +## SYNOPSIS +Gets Global Entitlement(s) with given search parameters. + +## SYNTAX + +``` +Get-HVGlobalEntitlement [[-DisplayName] ] [[-Description] ] [[-SuppressInfo] ] + [[-HvServer] ] [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVGlobalEntitlement -DisplayName 'GEAPP' +``` + +Retrieves global application/desktop entitlement(s) with displayName 'GEAPP' + +## PARAMETERS + +### -DisplayName +Display Name of Global Entitlement. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +Description of Global Entitlement. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SuppressInfo +Suppress text info, when no global entitlement(s) found with given search parameters + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVGlobalSession.md b/Modules/VMware.Hv.Helper/docs/Get-HVGlobalSession.md new file mode 100755 index 0000000..c4d1963 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVGlobalSession.md @@ -0,0 +1,69 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVGlobalSession + +## SYNOPSIS +Provides a list with all Global sessions in a Cloud Pod Architecture + +## SYNTAX + +``` +Get-HVGlobalSession [[-HvServer] ] [] +``` + +## DESCRIPTION +The get-hvglobalsession gets all local session by using view API service object(hvServer) of Connect-HVServer cmdlet. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-hvglobalsession +``` + +Gets all global sessions + +## PARAMETERS + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten. | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.0.2, 7.1.0, 7.3.2 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVGlobalSettings.md b/Modules/VMware.Hv.Helper/docs/Get-HVGlobalSettings.md new file mode 100755 index 0000000..fa0a7fd --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVGlobalSettings.md @@ -0,0 +1,70 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVGlobalSettings + +## SYNOPSIS +Gets a list of Global Settings + +## SYNTAX + +``` +Get-HVGlobalSettings [[-HvServer] ] [] +``` + +## DESCRIPTION +Queries and returns the Global Settings for the pod of the specified HVServer. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVGlobalSettings +``` + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns list of object type VMware.Hv.GlobalSettingsInfo +## NOTES +| | | +|-|-| +| Author | Matt Frey. | +| Author email | mfrey@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.1 | +| PowerCLI Version | PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVHealth.md b/Modules/VMware.Hv.Helper/docs/Get-HVHealth.md new file mode 100755 index 0000000..cc53349 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVHealth.md @@ -0,0 +1,95 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVHealth + +## SYNOPSIS +Pulls health information from Horizon View + +## SYNTAX + +``` +Get-HVHealth [[-Servicename] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Queries and returns health information from the local Horizon Pod + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVHealth -service connectionserver +``` + +Returns health for the connectionserver(s) + +### EXAMPLE 2 +``` +Get-HVHealth -service ViewComposer +``` + +Returns health for the View composer server(s) + +## PARAMETERS + +### -Servicename +The name of the service to query the health for. + This will default to Connection server health. + Available services are ADDomain,CertificateSSOConnector,ConnectionServer,EventDatabase,SAMLAuthenticator,SecurityServer,ViewComposer,VirtualCenter,Pod + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: ConnectionServer +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVHomeSite.md b/Modules/VMware.Hv.Helper/docs/Get-HVHomeSite.md new file mode 100755 index 0000000..3d75693 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVHomeSite.md @@ -0,0 +1,89 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVHomeSite + +## SYNOPSIS +Gets the configured Horizon View Homesites + +## SYNTAX + +``` +Get-HVHomeSite [[-Group] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Gets the configured Horizon View Homesites + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVHomeSite +``` + +### EXAMPLE 2 +``` +Get-HVHomeSite -group group@domain +``` + +## PARAMETERS + +### -Group +User principal name of a group + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4 | +| PowerCLI Version | PowerCLI 10 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVInternalName.md b/Modules/VMware.Hv.Helper/docs/Get-HVInternalName.md new file mode 100755 index 0000000..fc8efaf --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVInternalName.md @@ -0,0 +1,120 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVInternalName + +## SYNOPSIS +Gets human readable name + +## SYNTAX + +``` +Get-HVInternalName [-EntityId] [[-VcId] ] [[-BaseImageVmId] ] + [[-HvServer] ] [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVInternalName -EntityId $entityId +``` + +Decodes Horizon API Id and returns human readable name + +## PARAMETERS + +### -EntityId +Representation of a manageable entity id. + +```yaml +Type: EntityId +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VcId +{{ Fill VcId Description }} + +```yaml +Type: VirtualCenterId +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BaseImageVmId +{{ Fill BaseImageVmId Description }} + +```yaml +Type: BaseImageVmId +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVLocalSession.md b/Modules/VMware.Hv.Helper/docs/Get-HVLocalSession.md new file mode 100755 index 0000000..0b1dcd3 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVLocalSession.md @@ -0,0 +1,69 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVLocalSession + +## SYNOPSIS +Provides a list with all sessions on the local pod (works in CPA and non-CPA) + +## SYNTAX + +``` +Get-HVLocalSession [[-HvServer] ] [] +``` + +## DESCRIPTION +The Get-HVLocalSession gets all local session by using view API service object(hvServer) of Connect-HVServer cmdlet. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVLocalSession +``` + +Get all local sessions + +## PARAMETERS + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +Author : Wouter Kursten. +Author email : wouter@retouw.nl +Version : 1.0 + +===Tested Against Environment==== +| | | +|-|-| +Horizon View Server Version : 7.0.2, 7.1.0, 7.3.2 +PowerCLI Version : PowerCLI 6.5, PowerCLI 6.5.1 +PowerShell Version : 5.0 + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVMachine.md b/Modules/VMware.Hv.Helper/docs/Get-HVMachine.md new file mode 100755 index 0000000..ac20ec1 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVMachine.md @@ -0,0 +1,180 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVMachine + +## SYNOPSIS +Gets virtual Machine(s) information with given search parameters. + +## SYNTAX + +``` +Get-HVMachine [[-PoolName] ] [[-MachineName] ] [[-DnsName] ] [[-State] ] + [[-JsonFilePath] ] [[-HvServer] ] [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVMachine -PoolName 'ManualPool' +``` + +Queries VM(s) with given parameter poolName + +### EXAMPLE 2 +``` +Get-HVMachine -MachineName 'PowerCLIVM' +``` + +Queries VM(s) with given parameter machineName + +### EXAMPLE 3 +``` +Get-HVMachine -State CUSTOMIZING +``` + +Queries VM(s) with given parameter vm state + +### EXAMPLE 4 +``` +Get-HVMachine -DnsName 'powercli-*' +``` + +Queries VM(s) with given parameter dnsName with wildcard character * + +## PARAMETERS + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -JsonFilePath +{{ Fill JsonFilePath Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVMachineSummary.md b/Modules/VMware.Hv.Helper/docs/Get-HVMachineSummary.md new file mode 100755 index 0000000..c745752 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVMachineSummary.md @@ -0,0 +1,195 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVMachineSummary + +## SYNOPSIS +Gets virtual Machine(s) summary with given search parameters. + +## SYNTAX + +``` +Get-HVMachineSummary [[-PoolName] ] [[-MachineName] ] [[-DnsName] ] [[-State] ] + [[-JsonFilePath] ] [[-SuppressInfo] ] [[-HvServer] ] [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVMachineSummary -PoolName 'ManualPool' +``` + +Queries VM(s) with given parameter poolName + +### EXAMPLE 2 +``` +Get-HVMachineSummary -MachineName 'PowerCLIVM' +``` + +Queries VM(s) with given parameter machineName + +### EXAMPLE 3 +``` +Get-HVMachineSummary -State CUSTOMIZING +``` + +Queries VM(s) with given parameter vm state + +### EXAMPLE 4 +``` +Get-HVMachineSummary -DnsName 'powercli-*' +``` + +Queries VM(s) with given parameter dnsName with wildcard character * + +## PARAMETERS + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -JsonFilePath +{{ Fill JsonFilePath Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SuppressInfo +Suppress text info, when no machine found with given search parameters + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVPodFederation.md b/Modules/VMware.Hv.Helper/docs/Get-HVPodFederation.md new file mode 100755 index 0000000..e8c4885 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVPodFederation.md @@ -0,0 +1,71 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVPodFederation + +## SYNOPSIS +Returns information about a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Get-HVPodFederation [[-HvServer] ] [] +``` + +## DESCRIPTION +Returns information about a Horizon View Pod Federation (Cloud Pod Architecture) + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVPodFederation +``` + +Returns information about a Horizon View Pod Federation + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVPool.md b/Modules/VMware.Hv.Helper/docs/Get-HVPool.md new file mode 100755 index 0000000..9c7d2b3 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVPool.md @@ -0,0 +1,218 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVPool + +## SYNOPSIS +Gets pool(s) information with given search parameters. + +## SYNTAX + +``` +Get-HVPool [[-PoolName] ] [[-PoolDisplayName] ] [[-PoolType] ] + [[-UserAssignment] ] [[-Enabled] ] [[-ProvisioningEnabled] ] + [[-SuppressInfo] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Queries and returns pools information, the pools list would be determined based on +queryable fields poolName, poolDisplayName, poolType, userAssignment, enabled, +provisioningEnabled. +When more than one fields are used for query the pools which +satisfy all fields criteria would be returned. + +## EXAMPLES + +### EXAMPLE 1 +``` +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 2 +``` +Get-HVPool -PoolType AUTOMATED -UserAssignment FLOATING +``` + +Queries and returns pool object(s) based on given parameters poolType and userAssignment + +### EXAMPLE 3 +``` +Get-HVPool -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false +``` + +Queries and returns pool object(s) based on given parameters poolName, PoolType etc. + +### EXAMPLE 4 +``` +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. + +## PARAMETERS + +### -PoolName +Pool name to query for. +If the value is null or not provided then filter will not be applied, +otherwise the pools which has name same as value will be returned. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PoolDisplayName +Pool display name to query for. +If the value is null or not provided then filter will not be applied, +otherwise the pools which has display name same as value will be returned. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PoolType +Pool type to filter with. +If the value is null or not provided then filter will not be applied. +If the value is MANUAL then only manual pools would be returned. +If the value is AUTOMATED then only automated pools would be returned +If the value is RDS then only Remote Desktop Service Pool pools would be returned + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserAssignment +User Assignment of pool to filter with. +If the value is null or not provided then filter will not be applied. +If the value is DEDICATED then only dedicated pools would be returned. +If the value is FLOATING then only floating pools would be returned + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enabled +Pool enablement to filter with. +If the value is not provided then then filter will not be applied. +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. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProvisioningEnabled +{{ Fill ProvisioningEnabled Description }} + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SuppressInfo +Suppress text info, when no pool found with given search parameters + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 in-place of hvServer + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns list of objects of type DesktopInfo +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVPoolSpec.md b/Modules/VMware.Hv.Helper/docs/Get-HVPoolSpec.md new file mode 100755 index 0000000..3994ae7 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVPoolSpec.md @@ -0,0 +1,142 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVPoolSpec + +## SYNOPSIS +Gets desktop specification + +## SYNTAX + +``` +Get-HVPoolSpec [-DesktopInfo] [[-FilePath] ] [[-HvServer] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Converts DesktopInfo Object to DesktopSpec. +Also Converts view API Ids to human readable names + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVPoolSpec -DesktopInfo $DesktopInfoObj +``` + +Converts DesktopInfo to DesktopSpec + +### EXAMPLE 2 +``` +Get-HVPool -PoolName 'LnkClnJson' | Get-HVPoolSpec -FilePath "C:\temp\LnkClnJson.json" +``` + +Converts DesktopInfo to DesktopSpec and also dumps json object + +## PARAMETERS + +### -DesktopInfo +An object with detailed description of a desktop instance. + +```yaml +Type: DesktopInfo +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -FilePath +{{ Fill FilePath Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVPoolSummary.md b/Modules/VMware.Hv.Helper/docs/Get-HVPoolSummary.md new file mode 100755 index 0000000..f69e88d --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVPoolSummary.md @@ -0,0 +1,218 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVPoolSummary + +## SYNOPSIS +Gets pool summary with given search parameters. + +## SYNTAX + +``` +Get-HVPoolSummary [[-PoolName] ] [[-PoolDisplayName] ] [[-PoolType] ] + [[-UserAssignment] ] [[-Enabled] ] [[-ProvisioningEnabled] ] + [[-SuppressInfo] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Queries and returns pools information, the pools list would be determined based on +queryable fields poolName, poolDisplayName, poolType, userAssignment, enabled, +provisioningEnabled. +When more than one fields are used for query the pools which +satisfy all fields criteria would be returned. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVPoolSummary -PoolName 'mypool' -PoolType MANUAL -UserAssignment FLOATING -Enabled $true -ProvisioningEnabled $true +``` + +Queries and returns desktopSummaryView based on given parameters poolName, poolType etc. + +### EXAMPLE 2 +``` +Get-HVPoolSummary -PoolType AUTOMATED -UserAssignment FLOATING +``` + +Queries and returns desktopSummaryView based on given parameters poolType, userAssignment. + +### EXAMPLE 3 +``` +Get-HVPoolSummary -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false +``` + +Queries and returns desktopSummaryView based on given parameters poolName, poolType, userAssignment etc. + +### EXAMPLE 4 +``` +Get-HVPoolSummary -PoolName 'myrds' -PoolType RDS -UserAssignment DEDICATED -Enabled $false -HvServer $mycs +``` + +Queries and returns desktopSummaryView based on given parameters poolName, HvServer etc. + +## PARAMETERS + +### -PoolName +Pool name to query for. +If the value is null or not provided then filter will not be applied, +otherwise the pools which has name same as value will be returned. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PoolDisplayName +Pool display name to query for. +If the value is null or not provided then filter will not be applied, +otherwise the pools which has display name same as value will be returned. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PoolType +Pool type to filter with. +If the value is null or not provided then filter will not be applied. +If the value is MANUAL then only manual pools would be returned. +If the value is AUTOMATED then only automated pools would be returned +If the value is RDS then only Remote Desktop Service Pool pools would be returned + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserAssignment +User Assignment of pool to filter with. +If the value is null or not provided then filter will not be applied. +If the value is DEDICATED then only dedicated pools would be returned. +If the value is FLOATING then only floating pools would be returned + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enabled +Pool enablement to filter with. +If the value is not provided then then filter will not be applied. +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. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProvisioningEnabled +{{ Fill ProvisioningEnabled Description }} + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SuppressInfo +Suppress text info, when no pool found with given search parameters + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 in-place of hvServer + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns list of DesktopSummaryView +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVPreInstalledApplication.md b/Modules/VMware.Hv.Helper/docs/Get-HVPreInstalledApplication.md new file mode 100755 index 0000000..33bfcab --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVPreInstalledApplication.md @@ -0,0 +1,85 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVPreInstalledApplication + +## SYNOPSIS +Gets the list of Pre-installed Applications from the RDS Server(s). + +## SYNTAX + +``` +Get-HVPreInstalledApplication [-FarmName] [[-HvServer] ] [] +``` + +## DESCRIPTION +Gets the list of Pre-installed Applications from the RDS Server(s). + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVPreInstalledApplication -FarmName 'Farm1' -HvServer $HvServer +``` + +Gets the list of Applications present in 'Farm1', if exists. + +## PARAMETERS + +### -FarmName +Name of the Farm on which to discover installed applications. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Gets the list of Applications from the specified Farm if exists. +## NOTES +| | | +|-|-| +| Author | Samiullasha S | +| Author email | ssami@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.8.0 | +| PowerCLI Version | PowerCLI 11.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVQueryFilter.md b/Modules/VMware.Hv.Helper/docs/Get-HVQueryFilter.md new file mode 100755 index 0000000..764579c --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVQueryFilter.md @@ -0,0 +1,308 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVQueryFilter + +## SYNOPSIS +Creates a VMware.Hv.QueryFilter based on input provided. + +## SYNTAX + +### ne +``` +Get-HVQueryFilter [-MemberName] [-Ne] [-MemberValue] [] +``` + +### startswith +``` +Get-HVQueryFilter [-MemberName] [-Startswith] [-MemberValue] [] +``` + +### contains +``` +Get-HVQueryFilter [-MemberName] [-Contains] [-MemberValue] [] +``` + +### eq +``` +Get-HVQueryFilter [-MemberName] [-Eq] [-MemberValue] [] +``` + +### not +``` +Get-HVQueryFilter [-Not] [-Filter] [] +``` + +### and +``` +Get-HVQueryFilter [-And] [-Filters] [] +``` + +### or +``` +Get-HVQueryFilter [-Or] [-Filters] [] +``` + +## DESCRIPTION +This is a factory method to create a VMware.Hv.QueryFilter. +The type of the QueryFilter would be determined based on switch used. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVQueryFilter data.name -Eq vmware +``` + +Creates queryFilterEquals with given parameters memberName(position 0) and memberValue(position 2) + +### EXAMPLE 2 +``` +Get-HVQueryFilter -MemberName data.name -Eq -MemberValue vmware +``` + +Creates queryFilterEquals with given parameters memberName and memberValue + +### EXAMPLE 3 +``` +Get-HVQueryFilter data.name -Ne vmware +``` + +Creates queryFilterNotEquals filter with given parameters memberName and memberValue + +### EXAMPLE 4 +``` +Get-HVQueryFilter data.name -Contains vmware +``` + +Creates queryFilterContains with given parameters memberName and memberValue + +### EXAMPLE 5 +``` +Get-HVQueryFilter data.name -Startswith vmware +``` + +Creates queryFilterStartsWith with given parameters memberName and memberValue + +### EXAMPLE 6 +``` +$filter = Get-HVQueryFilter data.name -Startswith vmware +``` + +Get-HVQueryFilter -Not $filter +Creates queryFilterNot with given parameter filter + +### EXAMPLE 7 +``` +$filter1 = Get-HVQueryFilter data.name -Startswith vmware +``` + +$filter2 = Get-HVQueryFilter data.name -Contains pool +Get-HVQueryFilter -And @($filter1, $filter2) + +Creates queryFilterAnd with given parameter filters array + +### EXAMPLE 8 +``` +$filter1 = Get-HVQueryFilter data.name -Startswith vmware +``` + +$filter2 = Get-HVQueryFilter data.name -Contains pool +Get-HVQueryFilter -Or @($filter1, $filter2) +Creates queryFilterOr with given parameter filters array + +## PARAMETERS + +### -MemberName +Property path separated by . +(dot) from the root of queryable data object which is being queried for + +```yaml +Type: String +Parameter Sets: ne, startswith, contains, eq +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Eq +Switch to create QueryFilterEquals filter + +```yaml +Type: SwitchParameter +Parameter Sets: eq +Aliases: + +Required: True +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Contains +Switch to create QueryFilterContains filter + +```yaml +Type: SwitchParameter +Parameter Sets: contains +Aliases: + +Required: True +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Startswith +Switch to create QueryFilterStartsWith filter + +```yaml +Type: SwitchParameter +Parameter Sets: startswith +Aliases: + +Required: True +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Ne +Switch to create QueryFilterNotEquals filter + +```yaml +Type: SwitchParameter +Parameter Sets: ne +Aliases: + +Required: True +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MemberValue +Value of property (memberName) which is used for filtering + +```yaml +Type: Object +Parameter Sets: ne, startswith, contains, eq +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Not +Switch to create QueryFilterNot filter, used for negating existing filter + +```yaml +Type: SwitchParameter +Parameter Sets: not +Aliases: + +Required: True +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Filter +Filter to used in QueryFilterNot to negate the result + +```yaml +Type: QueryFilter +Parameter Sets: not +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -And +Switch to create QueryFilterAnd filter, used for joing two or more filters + +```yaml +Type: SwitchParameter +Parameter Sets: and +Aliases: + +Required: True +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Or +Switch to create QueryFilterOr filter, used for joing two or more filters + +```yaml +Type: SwitchParameter +Parameter Sets: or +Aliases: + +Required: True +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Filters +List of filters to join using QueryFilterAnd or QueryFilterOr + +```yaml +Type: QueryFilter[] +Parameter Sets: and, or +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns the QueryFilter object +## NOTES +| | | +|-|-| +| Author | Kummara Ramamohan. | +| Author email | kramamohan@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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVQueryResult.md b/Modules/VMware.Hv.Helper/docs/Get-HVQueryResult.md new file mode 100755 index 0000000..f959cff --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVQueryResult.md @@ -0,0 +1,181 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVQueryResult + +## SYNOPSIS +Returns the query results from ViewApi Query Service + +## SYNTAX + +``` +Get-HVQueryResult [-EntityType] [[-Filter] ] [[-SortBy] ] + [[-SortDescending] ] [[-Limit] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Get-HVQueryResult is a API to query the results using ViewApi. +The filtering of the returned +list would be done based on input parameters filter, sortDescending, sortyBy, limit + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVQueryResult DesktopSummaryView +``` + +Returns query results of entityType DesktopSummaryView(position 0) + +### EXAMPLE 2 +``` +Get-HVQueryResult DesktopSummaryView (Get-HVQueryFilter data.name -Eq vmware) +``` + +Returns query results of entityType DesktopSummaryView(position 0) with given filter(position 1) + +### EXAMPLE 3 +``` +Get-HVQueryResult -EntityType DesktopSummaryView -Filter (Get-HVQueryFilter desktopSummaryData.name -Eq vmware) +``` + +Returns query results of entityType DesktopSummaryView with given filter + +### EXAMPLE 4 +``` +$myFilter = Get-HVQueryFilter data.name -Contains vmware +``` + +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 5 +``` +Get-HVQueryResult DesktopSummaryView -Limit 10 +``` + +Returns query results of entityType DesktopSummaryView, maximum count equal to limit + +## PARAMETERS + +### -EntityType +ViewApi Queryable entity type which is being queried for.The return list would be containing objects of entityType + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Filter +Filter to used for filtering the results, See Get-HVQueryFilter for more information + +```yaml +Type: QueryFilter +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SortBy +Data field path used for sorting the results + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SortDescending +If the value is set to true (default) then the results will be sorted in descending order +If the value is set to false then the results will be sorted in ascending order + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Limit +Max number of objects to retrieve. +Default would be 0 which means retieve all the results + +```yaml +Type: Int16 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns the list of objects of entityType +## NOTES +| | | +|-|-| +| Author | Kummara Ramamohan. | +| Author email | kramamohan@vmware.com | +| Version | 1.1 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.0.2, 7.1.0,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1, PowerCLI 10.1.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVResourceStructure.md b/Modules/VMware.Hv.Helper/docs/Get-HVResourceStructure.md new file mode 100755 index 0000000..6767049 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVResourceStructure.md @@ -0,0 +1,70 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVResourceStructure + +## SYNOPSIS +Output the structure of the resource pools available to a HV. +Primarily this is for debugging + +PS\> Get-HVResourceStructure +vCenter vc.domain.local +Container DC path /DC/host +HostOrCluster Servers path /DC/host/Servers +HostOrCluster VDI path /DC/host/VDI +ResourcePool Servers path /DC/host/Servers/Resources +ResourcePool VDI path /DC/host/VDI/Resources +ResourcePool RP1 path /DC/host/VDI/Resources/RP1 +ResourcePool RP2 path /DC/host/VDI/Resources/RP1/RP2 + +| Author | Mark Elvers \ | + +## SYNTAX + +``` +Get-HVResourceStructure [[-HvServer] ] [] +``` + +## DESCRIPTION +{{ Fill in the Description }} + +## EXAMPLES + +### Example 1 +```powershell +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -HvServer +{{ Fill HvServer Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS \ No newline at end of file diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVSite.md b/Modules/VMware.Hv.Helper/docs/Get-HVSite.md new file mode 100755 index 0000000..de64331 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVSite.md @@ -0,0 +1,71 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVSite + +## SYNOPSIS +Returns information about the sites within a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Get-HVSite [[-HvServer] ] [] +``` + +## DESCRIPTION +Returns information about the sites within a Horizon View Pod Federation (Cloud Pod Architecture) + +## EXAMPLES + +### EXAMPLE 1 +``` +get-hvsite +``` + +Returns information about the sites within a Horizon View Pod Federation. + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVlicense.md b/Modules/VMware.Hv.Helper/docs/Get-HVlicense.md new file mode 100755 index 0000000..97f270a --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVlicense.md @@ -0,0 +1,69 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVlicense + +## SYNOPSIS +Gets the license for Horizon View + +## SYNTAX + +``` +Get-HVlicense [[-HvServer] ] [] +``` + +## DESCRIPTION +Gets the license for Horizon View + +## EXAMPLES + +### EXAMPLE 1 +``` +get-hvlicense +``` + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4,7.5 | +| PowerCLI Version | PowerCLI 10 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVvCenterServer.md b/Modules/VMware.Hv.Helper/docs/Get-HVvCenterServer.md new file mode 100755 index 0000000..1540c41 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVvCenterServer.md @@ -0,0 +1,90 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVvCenterServer + +## SYNOPSIS +Gets a list of all configured vCenter Servers + +## SYNTAX + +``` +Get-HVvCenterServer [[-HvServer] ] [[-Name] ] [] +``` + +## DESCRIPTION +Queries and returns the vCenter Servers configured for the pod of the specified HVServer. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVvCenterServer +``` + +### EXAMPLE 2 +``` +Get-HVvCenterServer -Name 'vCenter1' +``` + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +A string value to query a vCenter Server by Name, if it is known. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns array of object type VMware.Hv.VirtualCenterInfo +## NOTES +| | | +|-|-| +| Author | Matt Frey. | +| Author email | mfrey@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.7 | +| PowerCLI Version | PowerCLI 11.2.0 | +| PowerShell Version | 5.1 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Get-HVvCenterServerHealth.md b/Modules/VMware.Hv.Helper/docs/Get-HVvCenterServerHealth.md new file mode 100755 index 0000000..1226441 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Get-HVvCenterServerHealth.md @@ -0,0 +1,97 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Get-HVvCenterServerHealth + +## SYNOPSIS +Gets a the health info for a given vCenter Server. + +## SYNTAX + +``` +Get-HVvCenterServerHealth [[-HvServer] ] [[-VirtualCenter] ] [] +``` + +## DESCRIPTION +Queries and returns the VirtualCenterHealthInfo specified HVServer. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-HVvCenterServerHealth -VirtualCenter 'vCenter1' +``` + +### EXAMPLE 2 +``` +Get-HVvCenterServerHealth -VirtualCenter $vCenter1 +``` + +### EXAMPLE 3 +``` +Get-HVvCenterServerHealth +``` + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VirtualCenter +A parameter to specify which vCenter Server to check health for. +If not specified, this function will return the +health info for all vCenter Servers. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Returns array of object type VMware.Hv.VirtualCenterInfo +## NOTES +| | | +|-|-| +| Author | Matt Frey. | +| Author email | mfrey@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.7 | +| PowerCLI Version | PowerCLI 11.2.0 | +| PowerShell Version | 5.1 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVEntitlement.md b/Modules/VMware.Hv.Helper/docs/New-HVEntitlement.md new file mode 100755 index 0000000..b86f11b --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVEntitlement.md @@ -0,0 +1,221 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVEntitlement + +## SYNOPSIS +Associates a user/group with a resource + +## SYNTAX + +### Default +``` +New-HVEntitlement -User -ResourceName [-ResourceType ] [-Type ] + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### PipeLine +``` +New-HVEntitlement -User -Resource [-ResourceType ] [-Type ] + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +This represents a simple association between a single user/group and a resource that they can be assigned. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-HVEntitlement -User 'administrator@adviewdev.eng.vmware.com' -ResourceName 'InsClnPol' -Confirm:$false +``` + +Associate a user/group with a pool + +### EXAMPLE 2 +``` +New-HVEntitlement -User 'adviewdev\administrator' -ResourceName 'Calculator' -ResourceType Application +``` + +Associate a user/group with a application + +### EXAMPLE 3 +``` +New-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'UrlSetting1' -ResourceType URLRedirection +``` + +Associate a user/group with a URLRedirection settings + +### EXAMPLE 4 +``` +New-HVEntitlement -User 'adviewdev.eng.vmware.com\administrator' -ResourceName 'GE1' -ResourceType GlobalEntitlement +``` + +Associate a user/group with a desktop entitlement + +### EXAMPLE 5 +``` +New-HVEntitlement -User 'adviewdev\administrator' -ResourceName 'GEAPP1' -ResourceType GlobalApplicationEntitlement +``` + +Associate a user/group with a application entitlement + +### EXAMPLE 6 +``` +$pools = Get-HVPool; $pools | New-HVEntitlement -User 'adviewdev\administrator' -Confirm:$false +``` + +Associate a user/group with list of pools + +## PARAMETERS + +### -User +User principal name of user or group + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceName +The resource(Application, Desktop etc.) name. +Supports only wildcard character '*' when resource type is desktop. + +```yaml +Type: String +Parameter Sets: Default +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Resource +Object(s) of the resource(Application, Desktop etc.) to entitle + +```yaml +Type: Object +Parameter Sets: PipeLine +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ResourceType +Type of Resource(Application, Desktop etc) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Desktop +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type +Whether or not this is a group or a user. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: User +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVFarm.md b/Modules/VMware.Hv.Helper/docs/New-HVFarm.md new file mode 100755 index 0000000..dacc0df --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVFarm.md @@ -0,0 +1,1133 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVFarm + +## SYNOPSIS +Creates a new farm. + +## SYNTAX + +### LINKED_CLONE +``` +New-HVFarm [-LinkedClone] -FarmName [-FarmDisplayName ] [-Description ] + [-AccessGroup ] [-Enable ] [-DisconnectedSessionTimeoutPolicy ] + [-DisconnectedSessionTimeoutMinutes ] [-EmptySessionTimeoutPolicy ] + [-EmptySessionTimeoutMinutes ] [-LogoffAfterTimeout ] [-DefaultDisplayProtocol ] + [-AllowDisplayProtocolOverride ] [-EnableHTMLAccess ] [-EnableCollaboration ] + [-EnableGRIDvGPUs ] [-VGPUGridProfile ] [-ServerErrorThreshold ] + [-OverrideGlobalSetting ] [-MirageServerEnabled ] [-Url ] [-Vcenter ] + -ParentVM -SnapshotVM -VmFolder -HostOrCluster -ResourcePool + [-dataCenter ] -Datastores [-StorageOvercommit ] [-UseVSAN ] + [-EnableProvisioning ] [-StopProvisioningOnError ] [-TransparentPageSharingScope ] + [-NamingMethod ] [-NamingPattern ] [-MinReady ] [-MaximumCount ] + [-UseSeparateDatastoresReplicaAndOSDisks ] [-ReplicaDiskDatastore ] + [-UseNativeSnapshots ] [-ReclaimVmDiskSpace ] [-ReclamationThresholdGB ] + [-BlackoutTimes ] [-AdContainer ] -NetBiosName [-DomainAdmin ] + [-ReusePreExistingAccounts ] -SysPrepName [-MaxSessionsType ] [-MaxSessions ] + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### INSTANT_CLONE +``` +New-HVFarm [-InstantClone] -FarmName [-FarmDisplayName ] [-Description ] + [-AccessGroup ] [-Enable ] [-DisconnectedSessionTimeoutPolicy ] + [-DisconnectedSessionTimeoutMinutes ] [-EmptySessionTimeoutPolicy ] + [-EmptySessionTimeoutMinutes ] [-LogoffAfterTimeout ] [-DefaultDisplayProtocol ] + [-AllowDisplayProtocolOverride ] [-EnableHTMLAccess ] [-EnableCollaboration ] + [-EnableGRIDvGPUs ] [-VGPUGridProfile ] [-ServerErrorThreshold ] + [-OverrideGlobalSetting ] [-MirageServerEnabled ] [-Url ] [-Vcenter ] + -ParentVM -SnapshotVM -VmFolder -HostOrCluster -ResourcePool + [-dataCenter ] -Datastores [-StorageOvercommit ] [-UseVSAN ] + [-EnableProvisioning ] [-StopProvisioningOnError ] [-TransparentPageSharingScope ] + [-NamingMethod ] [-NamingPattern ] [-MinReady ] [-MaximumCount ] + [-UseSeparateDatastoresReplicaAndOSDisks ] [-ReplicaDiskDatastore ] + [-UseNativeSnapshots ] [-ReclaimVmDiskSpace ] [-AdContainer ] -NetBiosName + [-DomainAdmin ] [-PowerOffScriptName ] [-PowerOffScriptParameters ] + [-PostSynchronizationScriptName ] [-PostSynchronizationScriptParameters ] + [-MaxSessionsType ] [-MaxSessions ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +### MANUAL +``` +New-HVFarm [-Manual] -FarmName [-FarmDisplayName ] [-Description ] + [-AccessGroup ] [-Enable ] [-DisconnectedSessionTimeoutPolicy ] + [-DisconnectedSessionTimeoutMinutes ] [-EmptySessionTimeoutPolicy ] + [-EmptySessionTimeoutMinutes ] [-LogoffAfterTimeout ] [-DefaultDisplayProtocol ] + [-AllowDisplayProtocolOverride ] [-EnableHTMLAccess ] [-EnableCollaboration ] + [-EnableGRIDvGPUs ] [-VGPUGridProfile ] [-ServerErrorThreshold ] + [-OverrideGlobalSetting ] [-MirageServerEnabled ] [-Url ] -RdsServers + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### JSON_FILE +``` +New-HVFarm [-FarmName ] [-FarmDisplayName ] [-Description ] [-AccessGroup ] + [-Enable ] [-DisconnectedSessionTimeoutPolicy ] [-DisconnectedSessionTimeoutMinutes ] + [-EmptySessionTimeoutPolicy ] [-EmptySessionTimeoutMinutes ] [-LogoffAfterTimeout ] + [-DefaultDisplayProtocol ] [-AllowDisplayProtocolOverride ] [-EnableHTMLAccess ] + [-EnableCollaboration ] [-EnableGRIDvGPUs ] [-VGPUGridProfile ] + [-ServerErrorThreshold ] [-OverrideGlobalSetting ] [-MirageServerEnabled ] + [-Url ] [-NamingPattern ] [-Spec ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Creates a new farm, the type would be determined based on input parameters. + +## EXAMPLES + +### EXAMPLE 1 +``` +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 -StopProvisioningOnError $false -NamingPattern "LCFarmVM_PS" -MinReady 1 -MaximumCount 1 -SysPrepName "RDSH_Cust2" -NetBiosName "adviewdev" +``` + +Creates new linkedClone farm by using naming pattern + +### EXAMPLE 2 +``` +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 -StopProvisioningOnError $false -NamingPattern "ICFarmCL-" -NetBiosName "ad-vimalg" +``` + +Creates new linkedClone farm by using naming pattern + +### EXAMPLE 3 +``` +New-HVFarm -Spec C:\VMWare\Specs\LinkedClone.json -Confirm:$false +``` + +Creates new linkedClone farm by using json file + +### EXAMPLE 4 +``` +New-HVFarm -Spec C:\VMWare\Specs\InstantCloneFarm.json -Confirm:$false +``` + +Creates new instantClone farm by using json file + +### EXAMPLE 5 +``` +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 6 +``` +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. + +## PARAMETERS + +### -LinkedClone +Switch to Create Automated Linked Clone farm. + +```yaml +Type: SwitchParameter +Parameter Sets: LINKED_CLONE +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InstantClone +Switch to Create Automated Instant Clone farm. + +```yaml +Type: SwitchParameter +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Manual +Switch to Create Manual farm. + +```yaml +Type: SwitchParameter +Parameter Sets: MANUAL +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FarmName +Name of the farm. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE, MANUAL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: JSON_FILE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FarmDisplayName +Display name of the farm. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: $farmName +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +Description of the farm. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AccessGroup +View access group can organize the servers in the farm. +Default Value is 'Root'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Root +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enable +Set true to enable the farm otherwise set to false. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisconnectedSessionTimeoutPolicy +farmSpec.data.settings.disconnectedSessionTimeoutPolicy + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: NEVER +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisconnectedSessionTimeoutMinutes +farmSpec.data.settings.disconnectedSessionTimeoutMinutes + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EmptySessionTimeoutPolicy +farmSpec.data.settings.emptySessionTimeoutPolicy + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: AFTER +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EmptySessionTimeoutMinutes +farmSpec.data.settings.emptySessionTimeoutMinutes + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogoffAfterTimeout +farmSpec.data.settings.logoffAfterTimeout + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultDisplayProtocol +farmSpec.data.displayProtocolSettings.defaultDisplayProtocol + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: PCOIP +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowDisplayProtocolOverride +farmSpec.data.displayProtocolSettings.allowDisplayProtocolOverride + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableHTMLAccess +farmSpec.data.displayProtocolSettings.enableHTMLAccess + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableCollaboration +farmSpec.data.displayProtocolSettings.EnableCollaboration + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableGRIDvGPUs +farmSpec.data.displayProtocolSettings.EnableGRIDvGPUs + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VGPUGridProfile +farmSpec.data.displayProtocolSettings.VGPUGridProfile + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ServerErrorThreshold +farmSpec.data.serverErrorThreshold + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OverrideGlobalSetting +farmSpec.data.mirageConfigurationOverrides.overrideGlobalSetting + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MirageServerEnabled +farmSpec.data.mirageConfigurationOverrides.enabled + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Url +farmSpec.data.mirageConfigurationOverrides.url + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Vcenter +Virtual Center server-address (IP or FQDN) where the farm RDS Servers are located. +This should be same as provided to the Connection Server while adding the vCenter server. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParentVM +Base image VM for RDS Servers. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SnapshotVM +Base image snapshot for RDS Servers. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VmFolder +VM folder to deploy the RDSServers to. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HostOrCluster +Host or cluster to deploy the RDSServers in. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourcePool +Resource pool to deploy the RDSServers. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -dataCenter +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.dataCenter if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Datastores +Datastore names to store the RDSServer. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String[] +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StorageOvercommit +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.datastores.storageOvercommit if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: String[] +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseVSAN +Whether to use vSphere VSAN. +This is applicable for vSphere 5.5 or later. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableProvisioning +Set to true to enable provision of RDSServers immediately in farm. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopProvisioningOnError +Set to true to stop provisioning of all RDSServers on error. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TransparentPageSharingScope +The transparent page sharing scope. +The default value is 'VM'. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: VM +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NamingMethod +Determines how the VMs in the farm are named. +Set PATTERN to use naming pattern. +The default value is PATTERN. +Currently only PATTERN is allowed. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: PATTERN +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NamingPattern +RDS Servers will be named according to the specified naming pattern. +Value would be considered only when $namingMethod = PATTERN +The default value is farmName + '{n:fixed=4}'. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE, JSON_FILE +Aliases: + +Required: False +Position: Named +Default value: $farmName + '{n:fixed=4}' +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MinReady +Minimum number of ready (provisioned) Servers during View Composer maintenance operations. +The default value is 0. +Applicable to Linked Clone farms. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaximumCount +Maximum number of Servers in the farm. +The default value is 1. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseSeparateDatastoresReplicaAndOSDisks +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.useSeparateDatastoresReplicaAndOSDisks if INSTANT_CLONE, LINKED_CLONE + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReplicaDiskDatastore +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.replicaDiskDatastore, if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseNativeSnapshots +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.useNativeSnapshots, if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReclaimVmDiskSpace +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.reclaimVmDiskSpace, if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReclamationThresholdGB +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.reclamationThresholdGB + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BlackoutTimes +farmSpec.automatedfarmSpec.virtualCenterProvisioningSettings.virtualCenterStorageSettings.viewComposerStorageSettings.spaceReclamationSettings.blackoutTimes + +```yaml +Type: FarmBlackoutTime[] +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: CN=Computers +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NetBiosName +Domain Net Bios Name. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DomainAdmin +Domain Administrator user name which will be used to join the domain. +Default value is null. +Applicable to Linked Clone and Instant Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReusePreExistingAccounts +farmSpec.automatedfarmSpec.customizationSettings.reusePreExistingAccounts + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SysPrepName +The customization spec to use. +Applicable to Linked Clone farms. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PowerOffScriptParameters +Power off script parameters. +Example: p1 p2 p3 +Applicable to Instant Clone farms. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PostSynchronizationScriptParameters +Post synchronization script parameters. +Example: p1 p2 p3 +Applicable to Instant Clone farms. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxSessionsType +farmSpec.automatedfarmSpec.rdsServerMaxSessionsData.maxSessionsType if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: UNLIMITED +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxSessions +farmSpec.automatedfarmSpec.rdsServerMaxSessionsData.maxSessionsType if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE, INSTANT_CLONE +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RdsServers +List of existing registered RDS server names to add into manual farm. +Applicable to Manual farms. + +```yaml +Type: String[] +Parameter Sets: MANUAL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Spec +Path of the JSON specification file. + +```yaml +Type: String +Parameter Sets: JSON_FILE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVGlobalEntitlement.md b/Modules/VMware.Hv.Helper/docs/New-HVGlobalEntitlement.md new file mode 100755 index 0000000..fdc88b2 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVGlobalEntitlement.md @@ -0,0 +1,329 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVGlobalEntitlement + +## SYNOPSIS +Creates a Global Entitlement. + +## SYNTAX + +``` +New-HVGlobalEntitlement [-DisplayName] [-Type] [[-Description] ] [[-Scope] ] + [[-Dedicated] ] [[-FromHome] ] [[-RequireHomeSite] ] + [[-MultipleSessionAutoClean] ] [[-Enabled] ] [[-SupportedDisplayProtocols] ] + [[-DefaultDisplayProtocol] ] [[-AllowUsersToChooseProtocol] ] + [[-AllowUsersToResetMachines] ] [[-EnableHTMLAccess] ] [[-HvServer] ] [-WhatIf] + [-Confirm] [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-HVGlobalEntitlement -DisplayName 'GE_APP' -Type APPLICATION_ENTITLEMENT +``` + +Creates new global application entitlement + +### EXAMPLE 2 +``` +New-HVGlobalEntitlement -DisplayName 'GE_DESKTOP' -Type DESKTOP_ENTITLEMENT +``` + +Creates new global desktop entitlement + +## PARAMETERS + +### -DisplayName +Display Name of Global Entitlement. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type +Specify whether to create desktop/app global entitlement + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +Description of Global Entitlement. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +Scope for this global entitlement. +Visibility and Placement policies are defined by this value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: ANY +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Dedicated +Specifies whether dedicated/floating resources associated with this global entitlement. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RequireHomeSite +This value determines whether we fail if a home site isn't defined for this global entitlement. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enabled +If this Global Entitlement is enabled. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SupportedDisplayProtocols +The set of supported display protocols for the global entitlement. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: @("PCOIP","BLAST") +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultDisplayProtocol +The default display protocol for the global entitlement. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 11 +Default value: PCOIP +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowUsersToChooseProtocol +Whether the users can choose the protocol used. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 12 +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowUsersToResetMachines +Whether users are allowed to reset/restart their machines. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 13 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableHTMLAccess +If set to true, the desktops that are associated with this GlobalEntitlement must also have HTML Access enabled. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 14 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 15 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVHomeSite.md b/Modules/VMware.Hv.Helper/docs/New-HVHomeSite.md new file mode 100755 index 0000000..6b44ab1 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVHomeSite.md @@ -0,0 +1,178 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVHomeSite + +## SYNOPSIS +Defines a homesite within a Horizon View Cloud Pod architecture + +## SYNTAX + +### Default (Default) +``` +New-HVHomeSite -Group -Site [-HvServer ] [] +``` + +### globalApplicationEntitlement +``` +New-HVHomeSite [-Group ] [-Site ] [-globalApplicationEntitlement ] [-HvServer ] + [] +``` + +### globalEntitlement +``` +New-HVHomeSite [-Group ] [-Site ] [-globalEntitlement ] [-HvServer ] + [] +``` + +## DESCRIPTION +Creates a new homesite within a Cloud Pod Archtitecture. +By default it will be applied to everything +but the choice can be made to only apply for a single global entitlement or singel global application entitlement + +## EXAMPLES + +### EXAMPLE 1 +``` +New-HVHomeSite -group group@domain -site SITE +``` + +### EXAMPLE 2 +``` +New-HVHomeSite -group group@domain -site SITE -globalapplicationentitlement ge-ap01 +``` + +### EXAMPLE 3 +``` +New-HVHomeSite -group group@domain -site SITE -globalentitlement GE_Production +``` + +## PARAMETERS + +### -Group +User principal name of a group + +```yaml +Type: String +Parameter Sets: Default +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: globalApplicationEntitlement, globalEntitlement +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Site +Name of the Horizon View Site + +```yaml +Type: String +Parameter Sets: Default +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: globalApplicationEntitlement, globalEntitlement +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -globalEntitlement +Name of the global entitlement + +```yaml +Type: String +Parameter Sets: globalEntitlement +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -globalApplicationEntitlement +Name of the global application entitlement + +```yaml +Type: String +Parameter Sets: globalApplicationEntitlement +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4 | +| PowerCLI Version | PowerCLI 10.1.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVManualApplication.md b/Modules/VMware.Hv.Helper/docs/New-HVManualApplication.md new file mode 100755 index 0000000..1c7a843 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVManualApplication.md @@ -0,0 +1,383 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVManualApplication + +## SYNOPSIS +Creates a Manual Application. + +## SYNTAX + +``` +New-HVManualApplication [-HvServer ] -Name [-DisplayName ] + [-Description ] -ExecutablePath [-Version ] [-Publisher ] + [-Enabled ] [-EnablePreLaunch ] [-ConnectionServerRestrictions ] + [-CategoryFolderName ] [-clientRestrictions ] [-ShortcutLocations ] + [-MultiSessionMode ] [-MaxMultiSessions ] [-StartFolder ] [-Args ] + -Farm [-AutoUpdateFileTypes ] [-AutoUpdateOtherFileTypes ] + [-GlobalApplicationEntitlement ] [] +``` + +## DESCRIPTION +Creates Application manually with given parameters. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' +``` + +Creates a manual application App1 in the farm specified. + +## PARAMETERS + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: ViewServerImpl +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The Application name is the unique identifier used to identify this Application. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -DisplayName +The display name is the name that users will see when they connect to view client. +If the display name is left blank, it defaults to Name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: $Name +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Description +The description is a set of notes about the Application. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ExecutablePath +Path to Application executable. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Version +Application version. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Publisher +Application publisher. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Enabled +Indicates if Application is enabled. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -EnablePreLaunch +Application can be pre-launched if value is true. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ConnectionServerRestrictions +Connection server restrictions. +This is a list of tags that access to the application is restricted to. +Empty/Null list means that the application can be accessed from any connection server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -CategoryFolderName +Name of the category folder in the user's OS containing a shortcut to the application. +Unset if the application does not belong to a category. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -clientRestrictions +Client restrictions to be applied to Application. +Currently it is valid for RDSH pools. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ShortcutLocations +Locations of the category folder in the user's OS containing a shortcut to the desktop. +The value must be set if categoryFolderName is provided. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -MultiSessionMode +Multi-session mode for the application. +An application launched in multi-session mode does not support reconnect behavior when user logs in from a different client instance. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: DISABLED +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -MaxMultiSessions +Maximum number of multi-sessions a user can have in this application pool. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -StartFolder +Starting folder for Application. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Args +Parameters to pass to application when launching. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Farm +Farm name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -AutoUpdateFileTypes +Whether or not the file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -AutoUpdateOtherFileTypes +Whether or not the other file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -GlobalApplicationEntitlement +The name of a Global Application Entitlement to associate this Application pool with. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### A success message is displayed when done. +## NOTES +| | | +|-|-| +Author : Samiullasha S +Author email : ssami@vmware.com +Version : 1.0 + +===Tested Against Environment==== +| | | +|-|-| +Horizon View Server Version : 7.8.0 +PowerCLI Version : PowerCLI 11.1 +PowerShell Version : 5.0 + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVPodFederation.md b/Modules/VMware.Hv.Helper/docs/New-HVPodFederation.md new file mode 100755 index 0000000..45751a7 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVPodFederation.md @@ -0,0 +1,72 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVPodFederation + +## SYNOPSIS +Initiates a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +New-HVPodFederation [[-HvServer] ] [] +``` + +## DESCRIPTION +Starts the initialisation of a Horizon View Pod Federation. +Other pod's can be joined to this federation to form the Cloud Pod Architecture + +## EXAMPLES + +### EXAMPLE 1 +``` +new-hvpodfederation +``` + +Returns health for the connectionserver(s) + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVPool.md b/Modules/VMware.Hv.Helper/docs/New-HVPool.md new file mode 100755 index 0000000..055acba --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVPool.md @@ -0,0 +1,1830 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVPool + +## SYNOPSIS +Creates new desktop pool. + +## SYNTAX + +### INSTANT_CLONE +``` +New-HVPool [-InstantClone] -PoolName [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] -UserAssignment + [-AutomaticAssignment ] [-Enable ] [-ConnectionServerRestrictions ] + [-AutomaticLogoffPolicy ] [-AutomaticLogoffMinutes ] [-allowUsersToResetMachines ] + [-allowMultipleSessionsPerUser ] [-deleteOrRefreshMachineAfterLogoff ] + [-supportedDisplayProtocols ] [-defaultDisplayProtocol ] + [-allowUsersToChooseProtocol ] [-enableHTMLAccess ] [-renderer3D ] [-Quality ] + [-Throttling ] [-Vcenter ] -ParentVM -SnapshotVM -VmFolder + -HostOrCluster -ResourcePool [-datacenter ] -Datastores + [-StorageOvercommit ] [-UseVSAN ] [-UseSeparateDatastoresReplicaAndOSDisks ] + [-ReplicaDiskDatastore ] [-UseNativeSnapshots ] [-ReclaimVmDiskSpace ] + [-RedirectWindowsProfile ] [-Nics ] + [-EnableProvisioning ] [-StopProvisioningOnError ] [-TransparentPageSharingScope ] + -NamingMethod [-NamingPattern ] [-MaximumCount ] [-SpareCount ] + [-ProvisioningTime ] [-MinimumCount ] [-SpecificNames ] + [-StartInMaintenanceMode ] [-NumUnassignedMachinesKeptPoweredOn ] [-AdContainer ] + -NetBiosName [-DomainAdmin ] [-ReusePreExistingAccounts ] + [-PowerOffScriptName ] [-PowerOffScriptParameters ] [-PostSynchronizationScriptName ] + [-PostSynchronizationScriptParameters ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### LINKED_CLONE +``` +New-HVPool [-LinkedClone] -PoolName [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] -UserAssignment + [-AutomaticAssignment ] [-Enable ] [-ConnectionServerRestrictions ] + [-PowerPolicy ] [-AutomaticLogoffPolicy ] [-AutomaticLogoffMinutes ] + [-allowUsersToResetMachines ] [-allowMultipleSessionsPerUser ] + [-deleteOrRefreshMachineAfterLogoff ] [-refreshOsDiskAfterLogoff ] + [-refreshPeriodDaysForReplicaOsDisk ] [-refreshThresholdPercentageForReplicaOsDisk ] + [-supportedDisplayProtocols ] [-defaultDisplayProtocol ] + [-allowUsersToChooseProtocol ] [-enableHTMLAccess ] [-renderer3D ] + [-enableGRIDvGPUs ] [-vRamSizeMB ] [-maxNumberOfMonitors ] + [-maxResolutionOfAnyOneMonitor ] [-Quality ] [-Throttling ] + [-overrideGlobalSetting ] [-enabled ] [-url ] [-Vcenter ] -ParentVM + -SnapshotVM -VmFolder -HostOrCluster -ResourcePool [-datacenter ] + -Datastores [-StorageOvercommit ] [-UseVSAN ] + [-UseSeparateDatastoresReplicaAndOSDisks ] [-ReplicaDiskDatastore ] + [-UseNativeSnapshots ] [-ReclaimVmDiskSpace ] [-ReclamationThresholdGB ] + [-RedirectWindowsProfile ] [-UseSeparateDatastoresPersistentAndOSDisks ] + [-PersistentDiskDatastores ] [-PersistentDiskStorageOvercommit ] [-DiskSizeMB ] + [-DiskDriveLetter ] [-redirectDisposableFiles ] [-NonPersistentDiskSizeMB ] + [-NonPersistentDiskDriveLetter ] [-UseViewStorageAccelerator ] + [-ViewComposerDiskTypes ] [-RegenerateViewStorageAcceleratorDays ] + [-BlackoutTimes ] [-Nics ] + [-EnableProvisioning ] [-StopProvisioningOnError ] [-TransparentPageSharingScope ] + -NamingMethod [-NamingPattern ] [-MinReady ] [-MaximumCount ] + [-SpareCount ] [-ProvisioningTime ] [-MinimumCount ] [-SpecificNames ] + [-StartInMaintenanceMode ] [-NumUnassignedMachinesKeptPoweredOn ] [-AdContainer ] + [-NetBiosName ] [-DomainAdmin ] -CustType [-ReusePreExistingAccounts ] + [-SysPrepName ] [-PowerOffScriptName ] [-PowerOffScriptParameters ] + [-PostSynchronizationScriptName ] [-PostSynchronizationScriptParameters ] [-HvServer ] + [-WhatIf] [-Confirm] [] +``` + +### FULL_CLONE +``` +New-HVPool [-FullClone] -PoolName [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] -UserAssignment + [-AutomaticAssignment ] [-Enable ] [-ConnectionServerRestrictions ] + [-Quality ] [-Throttling ] [-Vcenter ] -Template -VmFolder + -HostOrCluster -ResourcePool [-datacenter ] -Datastores + [-StorageOvercommit ] [-UseVSAN ] [-Nics ] + [-EnableProvisioning ] [-StopProvisioningOnError ] [-TransparentPageSharingScope ] + -NamingMethod [-NamingPattern ] [-MaximumCount ] [-SpareCount ] + [-ProvisioningTime ] [-MinimumCount ] [-SpecificNames ] + [-StartInMaintenanceMode ] [-NumUnassignedMachinesKeptPoweredOn ] [-NetBiosName ] + -CustType [-SysPrepName ] [-DoNotPowerOnVMsAfterCreation ] [-HvServer ] + [-WhatIf] [-Confirm] [] +``` + +### MANUAL +``` +New-HVPool [-Manual] -PoolName [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] -UserAssignment + [-AutomaticAssignment ] [-Enable ] [-ConnectionServerRestrictions ] + [-allowUsersToResetMachines ] [-supportedDisplayProtocols ] + [-defaultDisplayProtocol ] [-allowUsersToChooseProtocol ] [-enableHTMLAccess ] + [-Quality ] [-Throttling ] [-Vcenter ] [-TransparentPageSharingScope ] + -Source -VM [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### RDS +``` +New-HVPool [-Rds] -PoolName [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] [-Enable ] + [-ConnectionServerRestrictions ] [-Farm ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +### JSON_FILE +``` +New-HVPool -Spec [-PoolName ] [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] [-Enable ] + [-ConnectionServerRestrictions ] [-NamingPattern ] + [-NumUnassignedMachinesKeptPoweredOn ] [-VM ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +### CLONED_POOL +``` +New-HVPool -ClonePool -PoolName [-PoolDisplayName ] [-Description ] + [-AccessGroup ] [-GlobalEntitlement ] [-Enable ] + [-ConnectionServerRestrictions ] [-NamingMethod ] [-NamingPattern ] + [-SpecificNames ] [-VM ] [-Farm ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Creates new desktop pool, the type and user assignment type would be +determined based on input parameters. + +## EXAMPLES + +### EXAMPLE 1 +``` +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 -StopProvisioningOnError $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 + +### EXAMPLE 2 +``` +New-HVPool -Spec C:\VMWare\Specs\LinkedClone.json -Confirm:$false +``` + +Create new automated linked clone pool by using JSON spec file + +### EXAMPLE 3 +``` +Get-HVPool -PoolName 'vmwarepool' | New-HVPool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; +``` + +(OR) +$vmwarepool = Get-HVPool -PoolName 'vmwarepool'; New-HVPool -ClonePool $vmwarepool -PoolName 'clonedPool' -NamingPattern 'clonelnk1'; +Clones new pool by using existing pool configuration + +### EXAMPLE 4 +``` +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 5 +``` +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 6 +``` +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 7 +``` +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 8 +``` +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. + +## PARAMETERS + +### -InstantClone +Switch to Create Instant Clone pool. + +```yaml +Type: SwitchParameter +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LinkedClone +Switch to Create Linked Clone pool. + +```yaml +Type: SwitchParameter +Parameter Sets: LINKED_CLONE +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FullClone +Switch to Create Full Clone pool. + +```yaml +Type: SwitchParameter +Parameter Sets: FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Manual +Switch to Create Manual Clone pool. + +```yaml +Type: SwitchParameter +Parameter Sets: MANUAL +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Rds +Switch to Create RDS pool. + +```yaml +Type: SwitchParameter +Parameter Sets: RDS +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Spec +Path of the JSON specification file. + +```yaml +Type: String +Parameter Sets: JSON_FILE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClonePool +Existing pool info to clone a new pool. + +```yaml +Type: Object +Parameter Sets: CLONED_POOL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -PoolName +Name of the pool. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL, RDS, CLONED_POOL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: JSON_FILE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PoolDisplayName +Display name of pool. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: $poolName +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +Description of pool. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AccessGroup +View access group can organize the desktops in the pool. +Default Value is 'Root'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Root +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GlobalEntitlement +Description of pool. +Global entitlement to associate the pool. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserAssignment +User Assignment type of pool. +Set to DEDICATED for dedicated desktop pool. +Set to FLOATING for floating desktop pool. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutomaticAssignment +Automatic assignment of a user the first time they access the machine. +Applicable to dedicated desktop pool. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enable +Set true to enable the pool otherwise set to false. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConnectionServerRestrictions +Connection server restrictions. +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. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PowerPolicy +Power policy for the machines in the desktop after logoff. +This setting is only relevant for managed machines + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: TAKE_NO_POWER_ACTION +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutomaticLogoffPolicy +Automatically log-off policy after disconnect. +This property has a default value of "NEVER". + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: NEVER +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AutomaticLogoffMinutes +The timeout in minutes for automatic log-off after disconnect. +This property is required if automaticLogoffPolicy is set to "AFTER". + +```yaml +Type: Int32 +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 120 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -allowUsersToResetMachines +Whether users are allowed to reset/restart their machines. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -allowMultipleSessionsPerUser +Whether multiple sessions are allowed per user in case of Floating User Assignment. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -deleteOrRefreshMachineAfterLogoff +Whether machines are to be deleted or refreshed after logoff in case of Floating User Assignment. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: NEVER +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -refreshOsDiskAfterLogoff +Whether and when to refresh the OS disks for dedicated-assignment, linked-clone machines. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: NEVER +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -refreshPeriodDaysForReplicaOsDisk +Regular interval at which to refresh the OS disk. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 120 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -supportedDisplayProtocols +The list of supported display protocols for the desktop. + +```yaml +Type: String[] +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: @('RDP', 'PCOIP', 'BLAST') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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". + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: PCOIP +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -allowUsersToChooseProtocol +Whether the users can choose the protocol. + +```yaml +Type: Int32 +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enableHTMLAccess +HTML Access, enabled by VMware Blast technology, allows users to connect to View machines from Web browsers. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -renderer3D +Specify 3D rendering dependent types hardware, software, vsphere client etc. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: DISABLED +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enableGRIDvGPUs +Whether GRIDvGPUs enabled or not + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -vRamSizeMB +VRAM size for View managed 3D rendering. +More VRAM can improve 3D performance. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 96 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -maxNumberOfMonitors +The greater these values are, the more memory will be consumed on the associated ESX hosts + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 2 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -maxResolutionOfAnyOneMonitor +The greater these values are, the more memory will be consumed on the associated ESX hosts. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: WUXGA +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Quality +This setting determines the image quality that the flash movie will render. +Lower quality results in less bandwidth usage. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: NO_CONTROL +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: DISABLED +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -overrideGlobalSetting +Mirage configuration specified here will be used for this Desktop + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enabled +Whether a Mirage server is enabled. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Template +Virtual machine Template name to clone Virtual machines. +Applicable only to Full Clone pools. + +```yaml +Type: String +Parameter Sets: FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParentVM +Parent Virtual Machine to clone Virtual machines. +Applicable only to Linked Clone and Instant Clone pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SnapshotVM +Base image VM for Linked Clone pool and current Image for Instant Clone Pool. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VmFolder +VM folder to deploy the VMs to. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HostOrCluster +Host or cluster to deploy the VMs in. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourcePool +Resource pool to deploy the VMs. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -datacenter +desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterProvisioningData.datacenter if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Datastores +Datastore names to store the VM +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String[] +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StorageOvercommit +Storage overcommit determines how View places new VMs on the selected datastores. +Supported values are 'UNBOUNDED','AGGRESSIVE','MODERATE','CONSERVATIVE','NONE' and are case sensitive. + +```yaml +Type: String[] +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseVSAN +Whether to use vSphere VSAN. +This is applicable for vSphere 5.5 or later. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseSeparateDatastoresReplicaAndOSDisks +Whether to use separate datastores for replica and OS disks. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReplicaDiskDatastore +Datastore to store replica disks for View Composer and Instant clone engine sourced machines. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseNativeSnapshots +Native NFS Snapshots is a hardware feature, specify whether to use or not + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReclaimVmDiskSpace +virtual machines can be configured to use a space efficient disk format that supports reclamation of unused disk space. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReclamationThresholdGB +Initiate reclamation when unused space on VM exceeds the threshold. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RedirectWindowsProfile +Windows profiles will be redirected to persistent disks, which are not affected by View Composer operations such as refresh, recompose and rebalance. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseSeparateDatastoresPersistentAndOSDisks +Whether to use separate datastores for persistent and OS disks. +This must be false if redirectWindowsProfile is false. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PersistentDiskDatastores +Name of the Persistent disk datastore + +```yaml +Type: String[] +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PersistentDiskStorageOvercommit +Storage overcommit determines how view places new VMs on the selected datastores. +Supported values are 'UNBOUNDED','AGGRESSIVE','MODERATE','CONSERVATIVE','NONE' and are case sensitive. + +```yaml +Type: String[] +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DiskSizeMB +Size of the persistent disk in MB. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 2048 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DiskDriveLetter +Persistent disk drive letter. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: D +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -redirectDisposableFiles +Redirect disposable files to a non-persistent disk that will be deleted automatically when a user's session ends. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NonPersistentDiskSizeMB +Size of the non persistent disk in MB. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 4096 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NonPersistentDiskDriveLetter +Non persistent disk drive letter. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: Auto +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseViewStorageAccelerator +Whether to use View Storage Accelerator. + +```yaml +Type: Boolean +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ViewComposerDiskTypes +Disk types to enable for the View Storage Accelerator feature. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: OS_DISKS +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RegenerateViewStorageAcceleratorDays +How often to regenerate the View Storage Accelerator cache. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 7 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BlackoutTimes +A list of blackout times. + +```yaml +Type: DesktopBlackoutTime[] +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Nics +desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.virtualCenterNetworkingSettings.nics + +```yaml +Type: DesktopNetworkInterfaceCardSettings[] +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableProvisioning +desktopSpec.automatedDesktopSpec.virtualCenterProvisioningSettings.enableProvsioning if LINKED_CLONE, INSTANT_CLONE, FULL_CLONE + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopProvisioningOnError +Set to true to stop provisioning of all VMs on error. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TransparentPageSharingScope +The transparent page sharing scope. +The default value is 'VM'. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, MANUAL +Aliases: + +Required: False +Position: Named +Default value: VM +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NamingMethod +Determines how the VMs in the desktop are named. +Set SPECIFIED to use specific name. +Set PATTERN to use naming pattern. +The default value is PATTERN. +For Instant Clone pool the value must be PATTERN. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: PATTERN +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: CLONED_POOL +Aliases: + +Required: False +Position: Named +Default value: PATTERN +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NamingPattern +Virtual machines will be named according to the specified naming pattern. +Value would be considered only when $namingMethod = PATTERN. +The default value is poolName + '{n:fixed=4}'. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, JSON_FILE, CLONED_POOL +Aliases: + +Required: False +Position: Named +Default value: $poolName + '{n:fixed=4}' +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MinReady +Minimum number of ready (provisioned) machines during View Composer maintenance operations. +The default value is 0. +Applicable to Linked Clone Pools. + +```yaml +Type: Int32 +Parameter Sets: LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaximumCount +Maximum number of machines in the pool. +The default value is 1. +Applicable to Full, Linked, Instant Clone Pools + +```yaml +Type: Int32 +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SpareCount +Number of spare powered on machines in the pool. +The default value is 1. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: Int32 +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProvisioningTime +Determines when machines are provisioned. +Supported values are ON_DEMAND, UP_FRONT. +The default value is UP_FRONT. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: UP_FRONT +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MinimumCount +The minimum number of machines to have provisioned if on demand provisioning is selected. +The default value is 0. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: Int32 +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SpecificNames +Specified names of VMs in the pool. +The default value is \-1 +Applicable to Full, Linked and Cloned Pools. + +```yaml +Type: String[] +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, CLONED_POOL +Aliases: + +Required: False +Position: Named +Default value: $poolName + '-1' +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartInMaintenanceMode +Set this to true to allow virtual machines to be customized manually before users can log +in and access them. +the default value is false +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NumUnassignedMachinesKeptPoweredOn +Number of unassigned machines kept powered on. +value should be less than max number of vms in the pool. +The default value is 1. +Applicable to Full, Linked, Instant Clone Pools. +When JSON Spec file is used for pool creation, the value will be read from JSON spec. + +```yaml +Type: Int32 +Parameter Sets: INSTANT_CLONE, LINKED_CLONE, FULL_CLONE, JSON_FILE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AdContainer +This is the Active Directory container which the machines will be added to upon creation. +The default value is 'CN=Computers'. +Applicable to Instant Clone Pool. + +```yaml +Type: Object +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: CN=Computers +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NetBiosName +Domain Net Bios Name. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DomainAdmin +Domain Administrator user name which will be used to join the domain. +Default value is null. +Applicable to Full, Linked, Instant Clone Pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CustType +Type of customization to use. +Supported values are 'CLONE_PREP','QUICK_PREP','SYS_PREP','NONE'. +Applicable to Full, Linked Clone Pools. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, FULL_CLONE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReusePreExistingAccounts +desktopSpec.automatedDesktopSpec.customizationSettings.reusePreExistingAccounts if LINKED_CLONE, INSTANT_CLONE + +```yaml +Type: Boolean +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SysPrepName +The customization spec to use. +Applicable to Full, Linked Clone Pools. + +```yaml +Type: String +Parameter Sets: LINKED_CLONE, FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DoNotPowerOnVMsAfterCreation +desktopSpec.automatedDesktopSpec.customizationSettings.noCustomizationSettings.doNotPowerOnVMsAfterCreation if FULL_CLONE + +```yaml +Type: Boolean +Parameter Sets: FULL_CLONE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PowerOffScriptParameters +Power off script parameters. +Example: p1 p2 p3 +Applicable to Linked, Instant Clone pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PostSynchronizationScriptParameters +Post synchronization script parameters. +Example: p1 p2 p3 +Applicable to Linked, Instant Clone pools. + +```yaml +Type: String +Parameter Sets: INSTANT_CLONE, LINKED_CLONE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Source +Source of the Virtual machines for manual pool. +Supported values are 'VIRTUAL_CENTER','UNMANAGED'. +Set VIRTUAL_CENTER for vCenter managed VMs. +Set UNMANAGED for Physical machines or VMs which are not vCenter managed VMs. +Applicable to Manual Pools. + +```yaml +Type: String +Parameter Sets: MANUAL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -VM +List of existing virtual machine names to add into manual pool. +Applicable to Manual Pools. + +```yaml +Type: String[] +Parameter Sets: MANUAL +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String[] +Parameter Sets: JSON_FILE, CLONED_POOL +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Farm +Farm to create RDS pools +Applicable to RDS Pools. + +```yaml +Type: String +Parameter Sets: RDS, CLONED_POOL +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 in-place of hvServer. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVPreInstalledApplication.md b/Modules/VMware.Hv.Helper/docs/New-HVPreInstalledApplication.md new file mode 100755 index 0000000..f16e44f --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVPreInstalledApplication.md @@ -0,0 +1,215 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVPreInstalledApplication + +## SYNOPSIS +Creates a application pool from Pre-installed applications on RDS Server(s). + +## SYNTAX + +``` +New-HVPreInstalledApplication -ApplicationName [-ApplicationID ] [-DisplayName ] + -FarmName [-EnablePreLaunch ] [-ConnectionServerRestrictions ] + [-CategoryFolderName ] [-clientRestrictions ] [-HvServer ] [] +``` + +## DESCRIPTION +Creates a application pool from Pre-installed applications on RDS Server(s). + +## EXAMPLES + +### EXAMPLE 1 +``` +New-HVPreInstalledApplication -ApplicationName 'App1' -DisplayName 'DisplayName' -FarmName 'FarmName' +``` + +Creates a application App1 from the farm specified. + +### EXAMPLE 2 +``` +New-HVPreInstalledApplication -ApplicationName 'App2' -FarmName FarmManual -EnablePreLaunch $True +``` + +Creates a application App2 from the farm specified and the PreLaunch option will be enabled. + +### EXAMPLE 3 +``` +New-HVPreInstalledApplication -ApplicationName 'Excel 2016' -ApplicationID 'Excel-2016' -DisplayName 'Excel' -FarmName 'RDS-FARM-01' +``` + +Creates an application, Excel-2016, from the farm RDS-FARM-01. +The application will display as 'Excel' to the end user. + +## PARAMETERS + +### -ApplicationName +The Application name to search within the Farm for. +This should match the output of (Get-HVPreinstalledApplication).Name + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ApplicationID +The unique identifier for this application. +The ApplicationID can only contain alphanumeric characters, dashes, and underscores. +If ApplicationID is not specified, it will be set to match the ApplicationName, with the spaces converted to underscore (_). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: $($ApplicationName -replace " ","_") +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -DisplayName +The display name is the name that users will see when they connect with the Horizon Client. +If the display name is left blank, it defaults to ApplicationName. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: $ApplicationName +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -FarmName +Farm name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -EnablePreLaunch +Application can be pre-launched if value is true. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ConnectionServerRestrictions +Connection server restrictions. +This is a list of tags that access to the application is restricted to. +Empty/Null list means that the application can be accessed from any connection server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -CategoryFolderName +Name of the category folder in the user's OS containing a shortcut to the application. +Unset if the application does not belong to a category. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -clientRestrictions +Client restrictions to be applied to Application. +Currently it is valid for RDSH pools. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### A success message is displayed when done. +## NOTES +| | | +|-|-| +| Author | Samiullasha S | +| Author email | ssami@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.8.0 | +| PowerCLI Version | PowerCLI 11.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/New-HVSite.md b/Modules/VMware.Hv.Helper/docs/New-HVSite.md new file mode 100755 index 0000000..d03f09a --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/New-HVSite.md @@ -0,0 +1,101 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# New-HVSite + +## SYNOPSIS +Creates a new site within a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +New-HVSite [-name] [-description] [[-HvServer] ] [] +``` + +## DESCRIPTION +Creates a new site within a Horizon View Pod Federation (Cloud Pod Architecture) + +## EXAMPLES + +### EXAMPLE 1 +``` +new-hvsite -name "NAME" -description "DESCRIPTION" +``` + +Returns information about the sites within a Horizon View Pod Federation. + +## PARAMETERS + +### -name +Name of the site (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -description +Description of the site (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Register-HVPod.md b/Modules/VMware.Hv.Helper/docs/Register-HVPod.md new file mode 100755 index 0000000..aec026e --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Register-HVPod.md @@ -0,0 +1,127 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Register-HVPod + +## SYNOPSIS +Registers a pod in a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Register-HVPod [-remoteconnectionserver] [-ADUserName] [-ADpassword] + [[-HvServer] ] [] +``` + +## DESCRIPTION +Registers a pod in a Horizon View Pod Federation. +You have to be connected to the pod you are joining to the federation. + +## EXAMPLES + +### EXAMPLE 1 +``` +$adpassword = Read-Host 'Domain Password' -AsSecureString +``` + +register-hvpod -remoteconnectionserver "servername" -username "user\domain" -password $adpassword + +### EXAMPLE 2 +``` +register-hvpod -remoteconnectionserver "servername" -username "user\domain" +``` + +It will now ask for the password + +## PARAMETERS + +### -remoteconnectionserver +Servername of a connectionserver that already belongs to the PodFederation + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ADUserName +User principal name of user this is required to be in the domain\username format + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ADpassword +Password of the type Securestring. +Can be created with: +$password = Read-Host 'Domain Password' -AsSecureString + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVApplication.md b/Modules/VMware.Hv.Helper/docs/Remove-HVApplication.md new file mode 100755 index 0000000..0ffbff5 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVApplication.md @@ -0,0 +1,118 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVApplication + +## SYNOPSIS +Removes the specified application if exists. + +## SYNTAX + +``` +Remove-HVApplication [-ApplicationName] [[-HvServer] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Removes the specified application if exists. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-HVApplication -ApplicationName 'App1' -HvServer $HvServer +``` + +Removes 'App1', if exists. + +## PARAMETERS + +### -ApplicationName +Application to be deleted. +The name of the application must be given that is to be searched for and remove if exists. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Removes the specified application if exists. +## NOTES +| | | +|-|-| +| Author | Samiullasha S | +| Author email | ssami@vmware.com | +| Version | 1.2 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.8.0 | +| PowerCLI Version | PowerCLI 11.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVApplicationIcon.md b/Modules/VMware.Hv.Helper/docs/Remove-HVApplicationIcon.md new file mode 100755 index 0000000..dd24741 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVApplicationIcon.md @@ -0,0 +1,119 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVApplicationIcon + +## SYNOPSIS +Used to remove a customized icon association for a given application. + +## SYNTAX + +``` +Remove-HVApplicationIcon [-ApplicationName] [[-HvServer] ] [-WhatIf] [-Confirm] + [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +Removing the icon for an application A1. +``` + +Remove-HVApplicationIcon -ApplicationName A1 -HvServer $hvServer + +## PARAMETERS + +### -ApplicationName +Name of the application to which customized icon needs to be removed. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVEntitlement.md b/Modules/VMware.Hv.Helper/docs/Remove-HVEntitlement.md new file mode 100755 index 0000000..a206522 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVEntitlement.md @@ -0,0 +1,178 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVEntitlement + +## SYNOPSIS +Deletes association data between a user/group and a resource + +## SYNTAX + +``` +Remove-HVEntitlement [-User] [-ResourceName] [[-Type] ] [[-ResourceType] ] + [[-HvServer] ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Removes entitlement between a single user/group and a resource that already been assigned. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-HVEntitlement -User 'administrator@adviewdev' -ResourceName LnkClnJSon -Confirm:$false +``` + +Deletes entitlement between a user/group and a pool resource + +### EXAMPLE 2 +``` +Remove-HVEntitlement -User 'adviewdev\puser2' -ResourceName 'calculator' -ResourceType Application +``` + +Deletes entitlement between a user/group and a Application resource + +### EXAMPLE 3 +``` +Remove-HVEntitlement -User 'adviewdev\administrator' -ResourceName 'GEAPP1' -ResourceType GlobalApplicationEntitlement +``` + +Deletes entitlement between a user/group and a GlobalApplicationEntitlement resource + +## PARAMETERS + +### -User +User principal name of user or group + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceName +The resource(Application, Desktop etc.) name. +Supports only wildcard character '*' when resource type is desktop. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type +Whether or not this is a group or a user. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: User +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceType +Type of Resource(Application, Desktop etc) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: Desktop +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVFarm.md b/Modules/VMware.Hv.Helper/docs/Remove-HVFarm.md new file mode 100755 index 0000000..f0c1215 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVFarm.md @@ -0,0 +1,158 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVFarm + +## SYNOPSIS +Deletes specified farm(s). + +## SYNTAX + +### option +``` +Remove-HVFarm -FarmName [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### pipeline +``` +Remove-HVFarm -Farm [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +This function deletes the farm(s) with the specified name/object(s) from the Connection Server. +Optionally, user can pipe the farm object(s) as input to this function. + +## EXAMPLES + +### EXAMPLE 1 +``` +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 2 +``` +$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 3 +``` +$farm1 = Get-HVFarm -FarmName 'Farm-01' +``` + +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. + +## PARAMETERS + +### -FarmName +Name of the farm to be deleted. + +```yaml +Type: String +Parameter Sets: option +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Farm +Object(s) of the farm to be deleted. +Object(s) should be of type FarmSummaryView/FarmInfo. + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVGlobalEntitlement.md b/Modules/VMware.Hv.Helper/docs/Remove-HVGlobalEntitlement.md new file mode 100755 index 0000000..f75dc71 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVGlobalEntitlement.md @@ -0,0 +1,147 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVGlobalEntitlement + +## SYNOPSIS +Deletes a Global Entitlement. + +## SYNTAX + +### Default +``` +Remove-HVGlobalEntitlement -DisplayName [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### pipeline +``` +Remove-HVGlobalEntitlement -GlobalEntitlement [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Deletes global entitlement(s) and global application entitlement(s). +Optionally, user can pipe the global entitlement(s) as input to this function. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-HVGlobalEntitlement -DisplayName 'GE_APP' +``` + +Deletes global application/desktop entitlement with displayName 'GE_APP' + +### EXAMPLE 2 +``` +Get-HVGlobalEntitlement -DisplayName 'GE_*' | Remove-HVGlobalEntitlement +``` + +Deletes global application/desktop entitlement(s), if displayName matches with 'GE_*' + +## PARAMETERS + +### -DisplayName +Display Name of Global Entitlement. + +```yaml +Type: String +Parameter Sets: Default +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GlobalEntitlement +{{ Fill GlobalEntitlement Description }} + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVMachine.md b/Modules/VMware.Hv.Helper/docs/Remove-HVMachine.md new file mode 100755 index 0000000..e700875 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVMachine.md @@ -0,0 +1,154 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVMachine + +## SYNOPSIS +Remove a Horizon View desktop or desktops. + +## SYNTAX + +``` +Remove-HVMachine [-MachineNames] [-DeleteFromDisk] [[-HVServer] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Deletes a VM or an array of VM's from Horizon. +Utilizes an Or query filter to match machine names. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-HVMachine -HVServer 'horizonserver123' -MachineNames 'LAX-WIN10-002' +``` + +Deletes VM 'LAX-WIN10-002' from HV Server 'horizonserver123' + +### EXAMPLE 2 +``` +Remove-HVMachine -HVServer 'horizonserver123' -MachineNames $machines +``` + +Deletes VM's contained within an array of machine names from HV Server 'horizonserver123' + +### EXAMPLE 3 +``` +Remove-HVMachine -HVServer 'horizonserver123' -MachineNames 'ManualVM01' -DeleteFromDisk:$false +``` + +Deletes VM 'ManualVM01' from Horizon inventory, but not from vSphere. +Note this only works for Full Clone VMs. + +## PARAMETERS + +### -MachineNames +The name or names of the machine(s) to be deleted. +Accepts a single VM or an array of VM names.This is a mandatory parameter. + +```yaml +Type: Array +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DeleteFromDisk +Determines whether the Machine VM should be deleted from vCenter Server. +This is only applicable for managed machines. +This must always be true for machines in linked and instant clone desktops. +This defaults to true for linked and instant clone machines and false for all other types. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HVServer +The Horizon server where the machine to be deleted resides. +Parameter is not mandatory, + but if you do not specify the server, than make sure you are connected to a Horizon server + first with connect-hvserver. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Jose Rodriguez | +| Author email | jrodsguitar@gmail.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.1.1 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVPodFederation.md b/Modules/VMware.Hv.Helper/docs/Remove-HVPodFederation.md new file mode 100755 index 0000000..a401fe9 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVPodFederation.md @@ -0,0 +1,72 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVPodFederation + +## SYNOPSIS +Uninitiates a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Remove-HVPodFederation [[-HvServer] ] [] +``` + +## DESCRIPTION +Starts the uninitialisation of a Horizon View Pod Federation. +It does NOT remove a pod from a federation. + +## EXAMPLES + +### EXAMPLE 1 +``` +Starts the Uninitiates a Horizon View Pod Federation. +``` + +Unintialises + +## PARAMETERS + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVPool.md b/Modules/VMware.Hv.Helper/docs/Remove-HVPool.md new file mode 100755 index 0000000..c75ef63 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVPool.md @@ -0,0 +1,186 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVPool + +## SYNOPSIS +Deletes specified pool(s). + +## SYNTAX + +### option +``` +Remove-HVPool -poolName [-TerminateSession] [-DeleteFromDisk] [-HvServer ] [-WhatIf] + [-Confirm] [] +``` + +### pipeline +``` +Remove-HVPool [-Pool ] [-TerminateSession] [-DeleteFromDisk] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +This function deletes the pool(s) with the specified name/object(s) from Connection Server. +This can be used for deleting any pool irrespective of its type. +Optionally, user can pipe the pool object(s) as input to this function. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-HVPool -HvServer $hvServer -PoolName 'FullClone' -DeleteFromDisk -Confirm:$false +``` + +Deletes pool from disk with given parameters PoolName etc. + +### EXAMPLE 2 +``` +$pool_array | Remove-HVPool -HvServer $hvServer -DeleteFromDisk +``` + +Deletes specified pool from disk + +### EXAMPLE 3 +``` +Remove-HVPool -Pool $pool1 +``` + +Deletes specified pool and VM(s) associations are removed from view Manager + +## PARAMETERS + +### -poolName +Name of the pool to be deleted. + +```yaml +Type: String +Parameter Sets: option +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Pool +Object(s) of the pool to be deleted. + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -TerminateSession +Logs off a session forcibly to virtual machine(s). +This operation will also log off a locked session. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DeleteFromDisk +Switch parameter to delete the virtual machine(s) from the disk. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Remove-HVSite.md b/Modules/VMware.Hv.Helper/docs/Remove-HVSite.md new file mode 100755 index 0000000..dec2494 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Remove-HVSite.md @@ -0,0 +1,86 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Remove-HVSite + +## SYNOPSIS +renames a new site within a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Remove-HVSite [-name] [[-HvServer] ] [] +``` + +## DESCRIPTION +renames a new site within a Horizon View Pod Federation (Cloud Pod Architecture) + +## EXAMPLES + +### EXAMPLE 1 +``` +set-hvsite -site "CURRENTSITENAME" -name "NAME" -description "DESCRIPTION" +``` + +Returns information about the sites within a Horizon View Pod Federation. + +## PARAMETERS + +### -name +Name of the site (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Reset-HVMachine.md b/Modules/VMware.Hv.Helper/docs/Reset-HVMachine.md new file mode 100755 index 0000000..d488735 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Reset-HVMachine.md @@ -0,0 +1,129 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Reset-HVMachine + +## SYNOPSIS +Resets Horizon View desktops. + +## SYNTAX + +``` +Reset-HVMachine [-MachineName] [[-HvServer] ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queries and resets virtual machines, the machines list would be determined + based on queryable fields machineName. +Use an asterisk (*) as wildcard. +If the result has multiple machines all will be reset. + Please note that on an Instant Clone Pool this will do the same as a recover of the machine. + +## EXAMPLES + +### EXAMPLE 1 +``` +reset-HVMachine -MachineName 'PowerCLIVM' +``` + +Queries VM(s) with given parameter machineName + +### EXAMPLE 2 +``` +reset-HVMachine -MachineName 'PowerCLIVM*' +``` + +Queries VM(s) with given parameter machinename with wildcard character * + +## PARAMETERS + +### -MachineName +The name of the Machine(s) to query for. +This is a required value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVApplication.md b/Modules/VMware.Hv.Helper/docs/Set-HVApplication.md new file mode 100755 index 0000000..ec6b216 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVApplication.md @@ -0,0 +1,340 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVApplication + +## SYNOPSIS +Updates settings for an existing Application Pool. + +## SYNTAX + +``` +Set-HVApplication [-HvServer ] [-Name] [-DisplayName ] [-Description ] + [-ExecutablePath ] [-Version ] [-Publisher ] [-Enabled ] + [-EnablePreLaunch ] [-ConnectionServerRestrictions ] [-CategoryFolderName ] + [-clientRestrictions ] [-ShortcutLocations ] [-StartFolder ] [-Args ] + [-AutoUpdateFileTypes ] [-AutoUpdateOtherFileTypes ] + [-GlobalApplicationEntitlement ] [] +``` + +## DESCRIPTION +Updates settings for an existing Application Pool. +It does not update the Application Icon. +See Set-HVApplicationIcon for a function to update icons. +This function specifically targets ApplicationInfo.Data and Application.ExecutionData properties. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-HVManualApplication -Name 'App1' -DisplayName 'DisplayName' -Description 'ApplicationDescription' -ExecutablePath "PathOfTheExecutable" -Version 'AppVersion' -Publisher 'PublisherName' -Farm 'FarmName' +``` + +Creates a manual application App1 in the farm specified. + +## PARAMETERS + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: ViewServerImpl +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The Application name is the unique identifier used to identify this Application. +This cannot be updated but is used to specify which application should be updated. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -DisplayName +The display name is the name that users will see when they connect to view client. +If the display name is left blank, it defaults to Name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: $Name +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Description +The description is a set of notes about the Application. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ExecutablePath +Path to Application executable. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Version +Application version. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Publisher +Application publisher. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Enabled +Indicates if Application is enabled. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -EnablePreLaunch +Application can be pre-launched if value is true. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ConnectionServerRestrictions +Connection server restrictions. +This is a list of tags that access to the application is restricted to. +Empty/Null list means that the application can be accessed from any connection server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -CategoryFolderName +Name of the category folder in the user's OS containing a shortcut to the application. +Unset if the application does not belong to a category. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -clientRestrictions +Client restrictions to be applied to Application. +Currently it is valid for RDSH pools. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ShortcutLocations +Locations of the category folder in the user's OS containing a shortcut to the desktop. +The value must be set if categoryFolderName is provided. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -StartFolder +Starting folder for Application. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Args +Parameters to pass to application when launching. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -AutoUpdateFileTypes +Whether or not the file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -AutoUpdateOtherFileTypes +Whether or not the other file types supported by this application should be allowed to automatically update to reflect changes reported by the agent. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -GlobalApplicationEntitlement +The name of a Global Application Entitlement to associate this Application pool with. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### A success message is displayed when done. +## NOTES +| | | +|-|-| +| Author | Matt Frey | +| Author email | mfrey@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.8.0 | +| PowerCLI Version | PowerCLI 11.1 | +| PowerShell Version | 5.1 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVApplicationIcon.md b/Modules/VMware.Hv.Helper/docs/Set-HVApplicationIcon.md new file mode 100755 index 0000000..854ece7 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVApplicationIcon.md @@ -0,0 +1,134 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVApplicationIcon + +## SYNOPSIS +Used to create/update an icon association for a given application. + +## SYNTAX + +``` +Set-HVApplicationIcon [-ApplicationName] [-IconPath] [[-HvServer] ] [-WhatIf] + [-Confirm] [] +``` + +## 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. + +## EXAMPLES + +### EXAMPLE 1 +``` +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 + +## PARAMETERS + +### -ApplicationName +Name of the application to which the association to be made. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IconPath +Path of the icon. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVEventDatabase.md b/Modules/VMware.Hv.Helper/docs/Set-HVEventDatabase.md new file mode 100755 index 0000000..aaf7334 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVEventDatabase.md @@ -0,0 +1,212 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVEventDatabase + +## SYNOPSIS +Registers or changes a Horizon View Event database. + +## SYNTAX + +``` +Set-HVEventDatabase [-ServerName] [[-DatabaseType] ] [[-DatabasePort] ] + [-DatabaseName] [[-TablePrefix] ] [-UserName] [-password] + [[-eventtime] ] [[-eventnewtime] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Registers or changes a Horizon View Event database + +## EXAMPLES + +### EXAMPLE 1 +``` +register-hveventdatabase -server SERVER@domain -database DATABASENAME -username USER@domain -password $password +``` + +## PARAMETERS + +### -ServerName +Name of the database server (Required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DatabaseType +Database type, possible options: MYSQL,SQLSERVER,ORACLE. +Defaults to SQLSERVER + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: SQLSERVER +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DatabasePort +Port number on the database server to which View will send events. +Defaults to 1433. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: 1433 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DatabaseName +Name of the Database (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TablePrefix +Prefix to use for the Event Databse. +Allowed characters are letters, numbers, and the characters @, $, #, _, and may not be longer than 6 characters. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserName +UserName to connect to the database (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -password +Password of the user connecting to the database in Securestring format. +Can be created with: $password = Read-Host 'Domain Password' -AsSecureString + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + +Required: True +Position: 7 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -eventtime +Time to show the events for. +Possible options are ONE_WEEK, TWO_WEEKS, THREE_WEEKS, ONE_MONTH,TWO_MONTHS, THREE_MONTHS, SIX_MONTHS + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: TWO_WEEKS +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -eventnewtime +Time in days to classify events for new. +Range 1-3 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: 2 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4 | +| PowerCLI Version | PowerCLI 10 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVFarm.md b/Modules/VMware.Hv.Helper/docs/Set-HVFarm.md new file mode 100755 index 0000000..1ff858f --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVFarm.md @@ -0,0 +1,279 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVFarm + +## SYNOPSIS +Edit farm configuration by passing key/values as parameters/json. + +## SYNTAX + +### option +``` +Set-HVFarm -FarmName [-Enable] [-Disable] [-Start] [-Stop] [-Key ] [-Value ] + [-Spec ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### pipeline +``` +Set-HVFarm [-Farm ] [-Enable] [-Disable] [-Start] [-Stop] [-Key ] [-Value ] + [-Spec ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +This function allows user to edit farm configuration by passing key/value pairs. +Optionally, user can pass a JSON spec file. +User can also pipe the farm object(s) as input to this function. + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-HVFarm -FarmName 'Farm-01' -Spec 'C:\Edit-HVFarm\ManualEditFarm.json' -Confirm:$false +``` + +Updates farm configuration by using json file + +### EXAMPLE 2 +``` +Set-HVFarm -FarmName 'Farm-01' -Key 'base.description' -Value 'updated description' +``` + +Updates farm configuration with given parameters key and value + +### EXAMPLE 3 +``` +$farm_array | Set-HVFarm -Key 'base.description' -Value 'updated description' +``` + +Updates farm(s) configuration with given parameters key and value + +### EXAMPLE 4 +``` +Set-HVFarm -farm 'Farm2' -Start +``` + +Enables provisioning to specified farm + +### EXAMPLE 5 +``` +Set-HVFarm -farm 'Farm2' -Enable +``` + +Enables specified farm + +## PARAMETERS + +### -FarmName +Name of the farm to edit. + +```yaml +Type: String +Parameter Sets: option +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Farm +Object(s) of the farm to edit. +Object(s) should be of type FarmSummaryView/FarmInfo. + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Enable +Switch to enable the farm(s). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Disable +Switch to disable the farm(s). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Start +Switch to enable provisioning immediately for the farm(s). +It's applicable only for 'AUTOMATED' farm type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Stop +Switch to disable provisioning immediately for the farm(s). +It's applicable only for 'AUTOMATED' farm type. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Key +Property names path separated by . +(dot) from the root of desktop spec. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Property value corresponds to above key name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Spec +Path of the JSON specification file containing key/value pair. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVGlobalEntitlement.md b/Modules/VMware.Hv.Helper/docs/Set-HVGlobalEntitlement.md new file mode 100755 index 0000000..99ec97b --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVGlobalEntitlement.md @@ -0,0 +1,253 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVGlobalEntitlement + +## SYNOPSIS +Sets the existing pool properties. + +## SYNTAX + +### option +``` +Set-HVGlobalEntitlement -displayName [-Key ] [-Value ] [-Spec ] [-Enable] + [-Disable] [-enableHTMLAccess ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### pipeline +``` +Set-HVGlobalEntitlement [-GlobalEntitlements ] [-Key ] [-Value ] [-Spec ] + [-Enable] [-Disable] [-enableHTMLAccess ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +This cmdlet allows user to edit global entitlements. + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-HVGlobalEntitlement -DisplayName 'MyGlobalEntitlement' -Spec 'C:\Edit-HVPool\EditPool.json' -Confirm:$false +``` + +Updates pool configuration by using json file + +### EXAMPLE 2 +``` +Set-HVGlobalEntitlement -DisplayName 'MyGlobalEntitlement' -Key 'base.description' -Value 'update description' +``` + +Updates pool configuration with given parameters key and value + +### EXAMPLE 3 +``` +Set-HVGlobalEntitlement -DisplayName 'MyGlobalEntitlement' -enableHTMLAccess $true +``` + +Set Allow HTML Access on a global entitlement. +Note that it must also be enabled on the Pool and as of 7.3.0 Allow User to Choose Protocol must be enabled (which is unfortunately read-only) + +### EXAMPLE 4 +``` +Get-HVGlobalEntitlement | Set-HVGlobalEntitlement -Disable +``` + +Disable all global entitlements + +## PARAMETERS + +### -displayName +Display Name of Global Entitlement. + +```yaml +Type: String +Parameter Sets: option +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GlobalEntitlements +{{ Fill GlobalEntitlements Description }} + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Key +Property names path separated by . +(dot) from the root of desktop spec. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Property value corresponds to above key name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Spec +Path of the JSON specification file containing key/value pair. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enable +{{ Fill Enable Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Disable +{{ Fill Disable Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enableHTMLAccess +If set to true, the desktops that are associated with this GlobalEntitlement must also have HTML Access enabled. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### None +## NOTES +| | | +|-|-| +Author : Mark Elvers +Author email : mark.elvers@tunbury.org +Version : 1.0 + +===Tested Against Environment==== +| | | +|-|-| +Horizon View Server Version : 7.3.0, 7.3.1 +PowerCLI Version : PowerCLI 6.5.1 +PowerShell Version : 5.0 + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVGlobalSettings.md b/Modules/VMware.Hv.Helper/docs/Set-HVGlobalSettings.md new file mode 100755 index 0000000..63a7817 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVGlobalSettings.md @@ -0,0 +1,520 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVGlobalSettings + +## SYNOPSIS +Sets the Global Settings of the Connection Server Pod + +## SYNTAX + +``` +Set-HVGlobalSettings [[-Key] ] [[-Value] ] [[-Spec] ] + [[-clientMaxSessionTimePolicy] ] [[-clientMaxSessionTimeMinutes] ] + [[-clientIdleSessionTimeoutPolicy] ] [[-clientIdleSessionTimeoutMinutes] ] + [[-clientSessionTimeoutMinutes] ] [[-desktopSSOTimeoutPolicy] ] + [[-desktopSSOTimeoutMinutes] ] [[-applicationSSOTimeoutPolicy] ] + [[-applicationSSOTimeoutMinutes] ] [[-viewAPISessionTimeoutMinutes] ] + [[-preLoginMessage] ] [[-displayWarningBeforeForcedLogoff] ] + [[-forcedLogoffTimeoutMinutes] ] [[-forcedLogoffMessage] ] + [[-enableServerInSingleUserMode] ] [[-storeCALOnBroker] ] [[-storeCALOnClient] ] + [[-reauthSecureTunnelAfterInterruption] ] [[-messageSecurityMode] ] + [[-enableIPSecForSecurityServerPairing] ] [[-HvServer] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +This cmdlet allows user to set Global Settings by passing key/value pair or by passing specific parameters. +Optionally, user can pass a JSON spec file. + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-HVGlobalSettings 'ManualPool' -Spec 'C:\Set-HVGlobalSettings\Set-GlobalSettings.json' +``` + +### EXAMPLE 2 +``` +Set-HVGlobalSettings -Key 'generalData.clientMaxSessionTimePolicy' -Value 'NEVER' +``` + +### EXAMPLE 3 +``` +Set-HVGlobalSettings -clientMaxSessionTimePolicy "TIMEOUT_AFTER" -clientMaxSessionTimeMinutes 1200 +``` + +## PARAMETERS + +### -Key +Property names path separated by . +(dot) from the root of global settings spec. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Property value corresponds to above key name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Spec +Path of the JSON specification file containing key/value pair. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -clientMaxSessionTimePolicy +Client max session lifetime policy. +"TIMEOUT_AFTER" Indicates that the client session times out after a configurable session length (in minutes) +"NEVER" Indicates no absolute client session length (sessions only end due to inactivity) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -clientMaxSessionTimeMinutes +Determines how long a user can keep a session open after logging in to View Connection Server. +The value is set in minutes. +When a session times out, the session is terminated and the View client is disconnected from the resource. +Default value is 600. +Minimum value is 5. +Maximum value is 600. +This property is required if clientMaxSessionTimePolicy is set to "TIMEOUT_AFTER" + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -clientIdleSessionTimeoutPolicy +Specifies the policy for the maximum time that a that a user can be idle before the broker takes measure to protect the session. +"TIMEOUT_AFTER" Indicates that the user session can be idle for a configurable max time (in minutes) before the broker takes measure to protect the session. +"NEVER" Indicates that the client session is never locked. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -clientIdleSessionTimeoutMinutes +Determines how long a that a user can be idle before the broker takes measure to protect the session. +The value is set in minutes. +Default value is 15 +This property is required if -clientIdleSessionTimeoutPolicy is set to "TIMEOUT_AFTER" + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -clientSessionTimeoutMinutes +Determines the maximum length of time that a Broker session will be kept active if there is no traffic between a client and the Broker. +The value is set in minutes. +Default value is 1200 +Minimum value is 5 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -desktopSSOTimeoutPolicy +The single sign on setting for when a user connects to View Connection Server. +"DISABLE_AFTER" SSO is disabled the specified number of minutes after a user connects to View Connection Server. +"DISABLED" Single sign on is always disabled. +"ALWAYS_ENABLED" Single sign on is always enabled. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -desktopSSOTimeoutMinutes +SSO is disabled the specified number of minutes after a user connects to View Connection Server. +Minimum value is 1 +Maximum value is 999 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -applicationSSOTimeoutPolicy +The single sign on timeout policy for application sessions. +"DISABLE_AFTER" SSO is disabled the specified number of minutes after a user connects to View Connection Server. +"DISABLED" Single sign on is always disabled. +"ALWAYS_ENABLED" Single sign on is always enabled. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 11 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -applicationSSOTimeoutMinutes +SSO is disabled the specified number of minutes after a user connects to View Connection Server. +Minimum value is 1 +Maximum value is 999 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 12 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -viewAPISessionTimeoutMinutes +Determines how long (in minutes) an idle View API session continues before the session times out. +Setting the View API session timeout to a high number of minutes increases the risk of unauthorized use of View API. +Use caution when you allow an idle session to persist a long time. +Default value is 10 +Minimum value is 1 +Maximum value is 4320 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 13 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -preLoginMessage +Displays a disclaimer or another message to View Client users when they log in. +No message will be displayed if this is null. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 14 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -displayWarningBeforeForcedLogoff +Displays a warning message when users are forced to log off because a scheduled or immediate update such as a machine-refresh operation is about to start. +$TRUE or $FALSE + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 15 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -forcedLogoffTimeoutMinutes +{{ Fill forcedLogoffTimeoutMinutes Description }} + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 16 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -forcedLogoffMessage +The warning to be displayed before logging off the user. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 17 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enableServerInSingleUserMode +Permits certain RDSServer operating systems to be used for non-RDS Desktops. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 18 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -storeCALOnBroker +Used for configuring whether or not to store the RDS Per Device CAL on Broker. +$TRUE or $FALSE + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 19 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -storeCALOnClient +Used for configuring whether or not to store the RDS Per Device CAL on client devices. +This value can be true only if the storeCALOnBroker is true. +$TRUE or $FALSE + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 20 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -reauthSecureTunnelAfterInterruption +Reauthenticate secure tunnel connections after network interruption Determines if user credentials must be reauthenticated after a network interruption when View clients use secure tunnel connections to View resources. +When you select this setting, if a secure tunnel connection ends during a session, View Client requires the user to reauthenticate before reconnecting. +This setting offers increased security. +For example, if a laptop is stolen and moved to a different network, the user cannot automatically gain access to the remote resource because the network connection was temporarily interrupted. +When this setting is not selected, the client reconnects to the resource without requiring the user to reauthenticate. +This setting has no effect when you use direct connection. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 21 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -messageSecurityMode +Determines if signing and verification of the JMS messages passed between View Manager components takes place. +"DISABLED" Message security mode is disabled. +"MIXED" Message security mode is enabled but not enforced. +You can use this mode to detect components in your View environment that predate View Manager 3.0. +The log files generated by View Connection Server contain references to these components. +"ENABLED" Message security mode is enabled. +Unsigned messages are rejected by View components. +Message security mode is enabled by default. +Note: View components that predate View Manager 3.0 are not allowed to communicate with other View components. +"ENHANCED" Message Security mode is Enhanced. +Message signing and validation is performed based on the current Security Level and desktop Message Security mode. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 22 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enableIPSecForSecurityServerPairing +Determines whether to use Internet Protocol Security (IPSec) for connections between security servers and View Connection Server instances. +By default, secure connections (using IPSec) for security server connections is enabled. +$TRUE or $FALSE + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 23 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 24 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### None +## NOTES +| | | +|-|-| +| Author | Matt Frey. | +| Author email | mfrey@vmware.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.1 | +| PowerCLI Version | PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVInstantCloneMaintenance.md b/Modules/VMware.Hv.Helper/docs/Set-HVInstantCloneMaintenance.md new file mode 100755 index 0000000..c168004 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVInstantCloneMaintenance.md @@ -0,0 +1,147 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVInstantCloneMaintenance + +## SYNOPSIS +Enable or disable instant clone maintanence mode + +## SYNTAX + +``` +Set-HVInstantCloneMaintenance [-VMHost] [-Enable] [-Disable] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Toggles a host in instant clone maintanence mode. +Specify the VMHost name and enable or disable to toggle. + +## EXAMPLES + +### EXAMPLE 1 +``` +-Enable $true +``` + +Set-HvInstantCloneMaintenance -VMHost \ -Disable $true + +## PARAMETERS + +### -VMHost +ESXi Host name to modify the InstantClone.Maintenance attribute + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Enable +Enable Instant Clone maintenance mode. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Disable +Disable Instant Clone maintenance mode + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +{{ Fill HvServer Description }} + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Jack McMichael | +| Author email | @jackwmc4 / jackwmc4@gmail.com | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.6 | +| PowerCLI Version | PowerCLI 11 | +| PowerShell Version | 5.1 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVMachine.md b/Modules/VMware.Hv.Helper/docs/Set-HVMachine.md new file mode 100755 index 0000000..5a2d9f1 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVMachine.md @@ -0,0 +1,221 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVMachine + +## SYNOPSIS +Sets existing virtual Machine(s). + +## SYNTAX + +### option +``` +Set-HVMachine -MachineName [-Maintenance ] [-Key ] [-Value ] [-User ] + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### pipeline +``` +Set-HVMachine -Machine [-Maintenance ] [-Key ] [-Value ] [-User ] + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +This cmdlet allows user to edit Machine configuration by passing key/value pair. +Allows the machine in to Maintenance mode and vice versa + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-HVMachine -MachineName 'Agent_Praveen' -Maintenance ENTER_MAINTENANCE_MODE +``` + +Moving the machine in to Maintenance mode using machine name + +### EXAMPLE 2 +``` +Get-HVMachine -MachineName 'Agent_Praveen' | Set-HVMachine -Maintenance ENTER_MAINTENANCE_MODE +``` + +Moving the machine in to Maintenance mode using machine object(s) + +### EXAMPLE 3 +``` +$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) + +## PARAMETERS + +### -MachineName +The name of the Machine to edit. + +```yaml +Type: String +Parameter Sets: option +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Machine +Object(s) of the virtual Machine(s) to edit. + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Key +{{ Fill Key Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Property value corresponds to above key name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -User +{{ Fill User Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVPodFederation.md b/Modules/VMware.Hv.Helper/docs/Set-HVPodFederation.md new file mode 100755 index 0000000..57cf267 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVPodFederation.md @@ -0,0 +1,86 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVPodFederation + +## SYNOPSIS +Used to change the name of a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Set-HVPodFederation [-name] [[-HvServer] ] [] +``` + +## DESCRIPTION +Used to change the name of a Horizon View Pod Federation (Cloud Pod Architecture) + +## EXAMPLES + +### EXAMPLE 1 +``` +set-hvpodfederation -name "New Name" +``` + +Will update the name of the current podfederation. + +## PARAMETERS + +### -name +The new name of the Pod Federation. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVPool.md b/Modules/VMware.Hv.Helper/docs/Set-HVPool.md new file mode 100755 index 0000000..98fb92f --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVPool.md @@ -0,0 +1,361 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVPool + +## SYNOPSIS +Sets the existing pool properties. + +## SYNTAX + +### option +``` +Set-HVPool -PoolName [-Enable] [-Disable] [-Start] [-Stop] [-Key ] [-Value ] + [-Spec ] [-globalEntitlement ] [-ResourcePool ] [-clearGlobalEntitlement] + [-allowUsersToChooseProtocol ] [-enableHTMLAccess ] [-HvServer ] [-WhatIf] + [-Confirm] [] +``` + +### pipeline +``` +Set-HVPool [-Pool ] [-Enable] [-Disable] [-Start] [-Stop] [-Key ] [-Value ] + [-Spec ] [-globalEntitlement ] [-ResourcePool ] [-clearGlobalEntitlement] + [-allowUsersToChooseProtocol ] [-enableHTMLAccess ] [-HvServer ] [-WhatIf] + [-Confirm] [] +``` + +## DESCRIPTION +This cmdlet allows user to edit pool configuration by passing key/value pair. +Optionally, user can pass a JSON spec file. + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-HVPool -PoolName 'ManualPool' -Spec 'C:\Edit-HVPool\EditPool.json' -Confirm:$false +``` + +Updates pool configuration by using json file + +### EXAMPLE 2 +``` +Set-HVPool -PoolName 'RDSPool' -Key 'base.description' -Value 'update description' +``` + +Updates pool configuration with given parameters key and value + +### EXAMPLE 3 +``` +Set-HVPool -PoolName 'LnkClone' -Disable +``` + +Disables specified pool + +### EXAMPLE 4 +``` +Set-HVPool -PoolName 'LnkClone' -Enable +``` + +Enables specified pool + +### EXAMPLE 5 +``` +Set-HVPool -PoolName 'LnkClone' -Start +``` + +Enables provisioning to specified pool + +### EXAMPLE 6 +``` +Set-HVPool -PoolName 'LnkClone' -Stop +``` + +Disables provisioning to specified pool + +## PARAMETERS + +### -PoolName +Name of the pool to edit. + +```yaml +Type: String +Parameter Sets: option +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Pool +Object(s) of the pool to edit. + +```yaml +Type: Object +Parameter Sets: pipeline +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Enable +Switch parameter to enable the pool. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Disable +Switch parameter to disable the pool. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Start +Switch parameter to start the pool. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Stop +Switch parameter to stop the pool. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Key +Property names path separated by . +(dot) from the root of desktop spec. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Property value corresponds to above key name. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Spec +Path of the JSON specification file containing key/value pair. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -globalEntitlement +{{ Fill globalEntitlement Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourcePool +{{ Fill ResourcePool Description }} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -clearGlobalEntitlement +{{ Fill clearGlobalEntitlement Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -allowUsersToChooseProtocol +{{ Fill allowUsersToChooseProtocol Description }} + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -enableHTMLAccess +{{ Fill enableHTMLAccess Description }} + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### None +## NOTES +| | | +|-|-| +| Author | Praveen Mathamsetty. | +| Author email | pmathamsetty@vmware.com | +| Version | 1.2 | +| Updated | Mark Elvers \ | + +===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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVSite.md b/Modules/VMware.Hv.Helper/docs/Set-HVSite.md new file mode 100755 index 0000000..2783be4 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVSite.md @@ -0,0 +1,117 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVSite + +## SYNOPSIS +renames a new site within a Horizon View Pod Federation (Cloud Pod Architecture) + +## SYNTAX + +``` +Set-HVSite [-sitename] [-name] [-description] [[-HvServer] ] + [] +``` + +## DESCRIPTION +renames a new site within a Horizon View Pod Federation (Cloud Pod Architecture) + +## EXAMPLES + +### EXAMPLE 1 +``` +set-hvsite -site "CURRENTSITENAME" -name "NAME" -description "DESCRIPTION" +``` + +Returns information about the sites within a Horizon View Pod Federation. + +## PARAMETERS + +### -sitename +Name of the site to be edited + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -name +New name of the site (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -description +New description of the site (required) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Set-HVlicense.md b/Modules/VMware.Hv.Helper/docs/Set-HVlicense.md new file mode 100755 index 0000000..8683099 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Set-HVlicense.md @@ -0,0 +1,86 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Set-HVlicense + +## SYNOPSIS +Sets or changes the license for Horizon View + +## SYNTAX + +``` +Set-HVlicense [-license] [[-HvServer] ] [] +``` + +## DESCRIPTION +Sets or changes the license for Horizon View + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-HVlicense -license "LICENSE-KEY" +``` + +Returns information about the sites within a Horizon View Pod Federation. + +## PARAMETERS + +### -license +License key (string) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.4,7.5 | +| PowerCLI Version | PowerCLI 10 | +| PowerShell Version | 5.0 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Start-HVFarm.md b/Modules/VMware.Hv.Helper/docs/Start-HVFarm.md new file mode 100755 index 0000000..4c8cfaf --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Start-HVFarm.md @@ -0,0 +1,465 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Start-HVFarm + +## SYNOPSIS +Performs maintenance tasks on the farm(s). + +## SYNTAX + +### RECOMPOSE +``` +Start-HVFarm -Farm [-Recompose] [-StartTime ] -LogoffSetting + [-StopOnFirstError ] [-Servers ] -ParentVM -SnapshotVM + [-Vcenter ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### SCHEDULEMAINTENANCE +``` +Start-HVFarm -Farm [-ScheduleMaintenance] [-StartTime ] [-LogoffSetting ] + [-StopOnFirstError ] [-ParentVM ] [-SnapshotVM ] [-Vcenter ] + -MaintenanceMode [-MaintenanceStartTime ] [-MaintenancePeriod ] [-StartInt ] + [-EveryInt ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### CANCELMAINTENANCE +``` +Start-HVFarm -Farm [-CancelMaintenance] -MaintenanceMode [-HvServer ] [-WhatIf] + [-Confirm] [] +``` + +## DESCRIPTION +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). + +## EXAMPLES + +### EXAMPLE 1 +``` +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 2 +``` +$myTime = Get-Date '10/03/2016 12:30:00' +``` + +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 3 +``` +Start-HVFarm -Farm 'ICFarm-01' -ScheduleMaintenance -MaintenanceMode IMMEDIATE +``` + +Requests a ScheduleMaintenance task for instant-clone farm. +Schedules an IMMEDIATE maintenance. + +### EXAMPLE 4 +``` +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 5 +``` +Start-HVFarm -CancelMaintenance -Farm 'ICFarm-01' -MaintenanceMode RECURRING +``` + +Requests a CancelMaintenance task for instant-clone farm. +Cancels recurring maintenance. + +## PARAMETERS + +### -Farm +Name/Object(s) of the farm. +Object(s) should be of type FarmSummaryView/FarmInfo. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: SwitchParameter +Parameter Sets: RECOMPOSE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: SwitchParameter +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: SwitchParameter +Parameter Sets: CANCELMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartTime +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. + +```yaml +Type: DateTime +Parameter Sets: RECOMPOSE, SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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). +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. + +```yaml +Type: String +Parameter Sets: RECOMPOSE +Aliases: + +Required: True +Position: Named +Default value: FORCE_LOGOFF +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: FORCE_LOGOFF +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopOnFirstError +Indicates that the operation should stop on first error. +Defaults to true. + +```yaml +Type: Boolean +Parameter Sets: RECOMPOSE, SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Servers +The RDS Server(s) id to recompose. +Provide a comma separated list for multiple RDSServerIds. + +```yaml +Type: String[] +Parameter Sets: RECOMPOSE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParentVM +New base image VM for automated farm's RDS Servers. +This must be in the same datacenter as the base image of the RDS Server. + +```yaml +Type: String +Parameter Sets: RECOMPOSE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SnapshotVM +Base image snapshot for the Automated Farm's RDS Servers. + +```yaml +Type: String +Parameter Sets: RECOMPOSE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: RECOMPOSE, SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: String +Parameter Sets: SCHEDULEMAINTENANCE, CANCELMAINTENANCE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaintenanceStartTime +Configured start time for the recurring maintenance. +This property must be in the form hh:mm in 24 hours format. + +```yaml +Type: String +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: String +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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". + +```yaml +Type: Int32 +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Int32 +Parameter Sets: SCHEDULEMAINTENANCE +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Start-HVPool.md b/Modules/VMware.Hv.Helper/docs/Start-HVPool.md new file mode 100755 index 0000000..ebd1258 --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Start-HVPool.md @@ -0,0 +1,399 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Start-HVPool + +## SYNOPSIS +Perform maintenance tasks on Pool. + +## SYNTAX + +### REFRESH +``` +Start-HVPool -Pool [-Refresh] [-StartTime ] -LogoffSetting + [-StopOnFirstError ] [-Machines ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +### RECOMPOSE +``` +Start-HVPool -Pool [-Recompose] [-StartTime ] -LogoffSetting + [-StopOnFirstError ] [-Machines ] -ParentVM -SnapshotVM + [-Vcenter ] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### REBALANCE +``` +Start-HVPool -Pool [-Rebalance] [-StartTime ] -LogoffSetting + [-StopOnFirstError ] [-Machines ] [-HvServer ] [-WhatIf] [-Confirm] + [] +``` + +### PUSH_IMAGE +``` +Start-HVPool -Pool [-SchedulePushImage] [-StartTime ] [-LogoffSetting ] + [-StopOnFirstError ] [-ParentVM ] [-SnapshotVM ] [-Vcenter ] + [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +### CANCEL_PUSH_IMAGE +``` +Start-HVPool -Pool [-CancelPushImage] [-HvServer ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +This cmdlet is used to perform maintenance tasks like enable/disable the pool, enable/disable the provisioning of a pool, refresh, rebalance, recompose, push image and cancel image. +Push image and Cancel image tasks only applies for instant clone pool. + +## EXAMPLES + +### EXAMPLE 1 +``` +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 2 +``` +Start-HVPool -Refresh -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -Confirm:$false +``` + +Requests a refresh of machines in the specified pool + +### EXAMPLE 3 +``` +$myTime = Get-Date '10/03/2016 12:30:00' +``` + +Start-HVPool -Rebalance -Pool 'LCPool3' -LogoffSetting FORCE_LOGOFF -StartTime $myTime +Requests a rebalance of machines in a pool with specified time + +### EXAMPLE 4 +``` +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 5 +``` +Start-HVPool -CancelPushImage -Pool 'InstantPool' +``` + +Requests a cancellation of the current scheduled push image operation on the specified Instant Clone Engine sourced pool + +## PARAMETERS + +### -Pool +Name/Object(s) of the pool. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Refresh +Switch parameter to refresh operation. + +```yaml +Type: SwitchParameter +Parameter Sets: REFRESH +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Recompose +Switch parameter to recompose operation. + +```yaml +Type: SwitchParameter +Parameter Sets: RECOMPOSE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Rebalance +Switch parameter to rebalance operation. + +```yaml +Type: SwitchParameter +Parameter Sets: REBALANCE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SchedulePushImage +Switch parameter to push image operation. + +```yaml +Type: SwitchParameter +Parameter Sets: PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CancelPushImage +Switch parameter to cancel push image operation. + +```yaml +Type: SwitchParameter +Parameter Sets: CANCEL_PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StartTime +Specifies when to start the operation. +If unset, the operation will begin immediately. + +```yaml +Type: DateTime +Parameter Sets: REFRESH, RECOMPOSE, REBALANCE, PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 virtual machines. +'WAIT_FOR_LOGOFF' - Wait for connected users to disconnect before the task starts. +The operation starts immediately on machines without active sessions. + +```yaml +Type: String +Parameter Sets: REFRESH, RECOMPOSE, REBALANCE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopOnFirstError +Indicates that the operation should stop on first error. + +```yaml +Type: Boolean +Parameter Sets: REFRESH, RECOMPOSE, REBALANCE, PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Machines +The machine names to recompose. +These must be associated with the pool. + +```yaml +Type: String[] +Parameter Sets: REFRESH, RECOMPOSE, REBALANCE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ParentVM +New base image VM for the desktop. +This must be in the same datacenter as the base image of the desktop. + +```yaml +Type: String +Parameter Sets: RECOMPOSE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SnapshotVM +Name of the snapshot used in pool deployment. + +```yaml +Type: String +Parameter Sets: RECOMPOSE +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Vcenter +Virtual Center server-address (IP or FQDN) of the given pool. +This should be same as provided to the Connection Server while adding the vCenter server. + +```yaml +Type: String +Parameter Sets: RECOMPOSE, PUSH_IMAGE +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HvServer +View API service object of Connect-HVServer cmdlet. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## 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 | + +## RELATED LINKS diff --git a/Modules/VMware.Hv.Helper/docs/Unregister-HVPod.md b/Modules/VMware.Hv.Helper/docs/Unregister-HVPod.md new file mode 100755 index 0000000..0c4bccc --- /dev/null +++ b/Modules/VMware.Hv.Helper/docs/Unregister-HVPod.md @@ -0,0 +1,110 @@ +--- +external help file: VMware.HV.Helper-help.xml +Module Name: VMware.HV.Helper +online version: +schema: 2.0.0 +--- + +# Unregister-HVPod + +## SYNOPSIS +Removes a pod from a podfederation + +## SYNTAX + +``` +Unregister-HVPod [-PodName] [[-force] ] [[-HvServer] ] [] +``` + +## DESCRIPTION +Starts the uninitialisation of a Horizon View Pod Federation. +It does NOT remove a pod from a federation. + +## EXAMPLES + +### EXAMPLE 1 +``` +Unregister-hvpod -podname PODNAME +``` + +Checks if you are connected to the pod and gracefully unregisters it from the podfedaration + +### EXAMPLE 2 +``` +Unregister-hvpod -podname PODNAME -force +``` + +Checks if you are connected to the pod and gracefully unregisters it from the podfedaration + +## PARAMETERS + +### -PodName +The name of the pod to be removed. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -force +This can be used to forcefully remove a pod from the pod federation. +This can only be done while connected to one of the other pods in the federation + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -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 + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +| | | +|-|-| +| Author | Wouter Kursten | +| Author email | wouter@retouw.nl | +| Version | 1.0 | + +===Tested Against Environment==== +| | | +|-|-| +| Horizon View Server Version | 7.3.2,7.4 | +| PowerCLI Version | PowerCLI 6.5, PowerCLI 6.5.1 | +| PowerShell Version | 5.0 | + +## RELATED LINKS From b940759bbfc30ca9ee87abe951ff4cb7028263ae Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 6 Feb 2020 13:00:55 -0800 Subject: [PATCH 161/175] Retrieve VCSA Password Policy --- .../VCSAPasswordPolicy.psm1 | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 diff --git a/Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 b/Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 new file mode 100644 index 0000000..55963ca --- /dev/null +++ b/Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 @@ -0,0 +1,39 @@ +Function Get-VCSAPasswordPolicy { +<# + .DESCRIPTION Retrieves vCenter Server Appliance SSO and Local OS Password Policy Configuration + .NOTES Author: William Lam + .PARAMETER VCSAName + Inventory name of the VCSA VM + .PARAMETER VCSARootPassword + Root password for VCSA VM + .PARAMETER SSODomain + SSO Domain of the VCSA VM + .PARAMETER SSOPassword + Administrator password for the SSO Domain of the VCSA VM + .EXAMPLE + Get-VCSAPasswordPolicy -VCSAName "MGMT-VCSA-01" -VCSARootPassword "VMware1!" -SSODomain "vsphere.local" -SSOPassword "VMware1!" +#> + Param ( + [Parameter(Mandatory=$true)][String]$VCSAName, + [Parameter(Mandatory=$true)][String]$VCSARootPassword, + [Parameter(Mandatory=$true)][String]$SSODomain, + [Parameter(Mandatory=$true)][String]$SSOPassword + ) + + $vm = Get-Vm -Name $VCSAName + + if($vm) { + $a,$b = $SSODomain.split(".") + + $ssoPasswordPolicy = Invoke-VMScript -ScriptText "/opt/likewise/bin/ldapsearch -h localhost -w $SSOPassword -x -D `"cn=Administrator,cn=Users,dc=$a,dc=$b`" -b `"cn=password and lockout policy,dc=$a,dc=$b`" | grep vmwPassword" -vm $vm -GuestUser "root" -GuestPassword $VCSARootPassword + $localOSPasswordPolicy = Invoke-VMScript -ScriptText "cat /etc/login.defs | grep -v '#' | grep PASS" -vm $vm -GuestUser "root" -GuestPassword $VCSARootPassword + + Write-Host -ForegroundColor green "`nSSO Password Policy: " + $ssoPasswordPolicy + + Write-Host -ForegroundColor green "`nLocalOS Password Policy: " + $localOSPasswordPolicy + } else { + Write-Host "`nUnable to find VCSA named $VCSAName" + } +} \ No newline at end of file From a70e3242827752d1af344c4adef3eee1dffcb14d Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 8 Feb 2020 06:44:01 -0800 Subject: [PATCH 162/175] VyOS Automation --- Modules/VyOS/VyOS.psm1 | 271 +++++++++++++++++++++++++++++++++++++ Modules/VyOS/vyos.template | 64 +++++++++ 2 files changed, 335 insertions(+) create mode 100644 Modules/VyOS/VyOS.psm1 create mode 100644 Modules/VyOS/vyos.template diff --git a/Modules/VyOS/VyOS.psm1 b/Modules/VyOS/VyOS.psm1 new file mode 100644 index 0000000..31fbc0d --- /dev/null +++ b/Modules/VyOS/VyOS.psm1 @@ -0,0 +1,271 @@ +Function Set-VMKeystrokes { + param( + [Parameter(Mandatory=$true)][String]$VMName, + [Parameter(Mandatory=$true)][String]$StringInput, + [Parameter(Mandatory=$false)][Boolean]$ReturnCarriage, + [Parameter(Mandatory=$false)][Boolean]$DebugOn + ) + + # Map subset of USB HID keyboard scancodes + # https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2 + $hidCharacterMap = @{ + "a"="0x04"; + "b"="0x05"; + "c"="0x06"; + "d"="0x07"; + "e"="0x08"; + "f"="0x09"; + "g"="0x0a"; + "h"="0x0b"; + "i"="0x0c"; + "j"="0x0d"; + "k"="0x0e"; + "l"="0x0f"; + "m"="0x10"; + "n"="0x11"; + "o"="0x12"; + "p"="0x13"; + "q"="0x14"; + "r"="0x15"; + "s"="0x16"; + "t"="0x17"; + "u"="0x18"; + "v"="0x19"; + "w"="0x1a"; + "x"="0x1b"; + "y"="0x1c"; + "z"="0x1d"; + "1"="0x1e"; + "2"="0x1f"; + "3"="0x20"; + "4"="0x21"; + "5"="0x22"; + "6"="0x23"; + "7"="0x24"; + "8"="0x25"; + "9"="0x26"; + "0"="0x27"; + "!"="0x1e"; + "@"="0x1f"; + "#"="0x20"; + "$"="0x21"; + "%"="0x22"; + "^"="0x23"; + "&"="0x24"; + "*"="0x25"; + "("="0x26"; + ")"="0x27"; + "_"="0x2d"; + "+"="0x2e"; + "{"="0x2f"; + "}"="0x30"; + "|"="0x31"; + ":"="0x33"; + "`""="0x34"; + "~"="0x35"; + "<"="0x36"; + ">"="0x37"; + "?"="0x38"; + "-"="0x2d"; + "="="0x2e"; + "["="0x2f"; + "]"="0x30"; + "\"="0x31"; + "`;"="0x33"; + "`'"="0x34"; + ","="0x36"; + "."="0x37"; + "/"="0x38"; + " "="0x2c"; + } + + $vm = Get-View -ViewType VirtualMachine -Filter @{"Name"="^$($VMName)$"} + + # Verify we have a VM or fail + if(!$vm) { + Write-host "Unable to find VM $VMName" + return + } + + $hidCodesEvents = @() + foreach($character in $StringInput.ToCharArray()) { + # Check to see if we've mapped the character to HID code + if($hidCharacterMap.ContainsKey([string]$character)) { + $hidCode = $hidCharacterMap[[string]$character] + + $tmp = New-Object VMware.Vim.UsbScanCodeSpecKeyEvent + + # Add leftShift modifer for capital letters and/or special characters + if( ($character -cmatch "[A-Z]") -or ($character -match "[!|@|#|$|%|^|&|(|)|_|+|{|}|||:|~|<|>|?|*]") ) { + $modifer = New-Object Vmware.Vim.UsbScanCodeSpecModifierType + $modifer.LeftShift = $true + $tmp.Modifiers = $modifer + } + + # Convert to expected HID code format + $hidCodeHexToInt = [Convert]::ToInt64($hidCode,"16") + $hidCodeValue = ($hidCodeHexToInt -shl 16) -bor 0007 + + $tmp.UsbHidCode = $hidCodeValue + $hidCodesEvents+=$tmp + + if($DebugOn) { + Write-Host "Character: $character -> HIDCode: $hidCode -> HIDCodeValue: $hidCodeValue" + } + } else { + Write-Host "The following character `"$character`" has not been mapped, you will need to manually process this character" + break + } + } + + # Add return carriage to the end of the string input (useful for logins or executing commands) + if($ReturnCarriage) { + # Convert return carriage to HID code format + $hidCodeHexToInt = [Convert]::ToInt64("0x28","16") + $hidCodeValue = ($hidCodeHexToInt -shl 16) + 7 + + $tmp = New-Object VMware.Vim.UsbScanCodeSpecKeyEvent + $tmp.UsbHidCode = $hidCodeValue + $hidCodesEvents+=$tmp + } + + # Call API to send keystrokes to VM + $spec = New-Object Vmware.Vim.UsbScanCodeSpec + $spec.KeyEvents = $hidCodesEvents + Write-Host "Sending `'$StringInput`' ...`n" + $results = $vm.PutUsbScanCodes($spec) +} + +Function New-VyOSConfiguration { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + This function automates the installation and configuration of VyOS from ISO + .PARAMETER VMName + The name of the VyOS VM + .PARAMETER ManagementPassword + The password to configure for the vyos user + .PARAMETER ConfigFile + The path to VyOS configuration file + .PARAMETER ManagementAddress + The IP Address of the WAN Interface (eth0) + .PARAMETER ManagementGateway + The Gateway Addrss of the WAN Interface (eth0) + .PARAMETER ManagementDNSDomain + The DNS Domain on the WAN network + .PARAMETER ManagementDNSServer + The DNS Server on the WAN Network + .PARAMETER ManagementJumpHostIP + The IP Address of Windows Jumphost that can be used to RDP into various VLANs + .EXAMPLE + New-VyOSConfiguration -VMName VyOS-Router -ConfigFile vyos.template -ManagementAddress 192.168.30.155/24 -ManagementGateway 192.168.30.1 -ManagementDNSDomain primp-industries.com -ManagementDNSServer 192.168.30.2 -ManagementJumpHostIP 192.168.30.199 -ManagementPassword VMware1! +#> + param( + [Parameter(Mandatory=$true)][String]$VMName, + [Parameter(Mandatory=$true)][String]$ConfigFile, + [Parameter(Mandatory=$true)][String]$ManagementAddress, + [Parameter(Mandatory=$true)][String]$ManagementGateway, + [Parameter(Mandatory=$true)][String]$ManagementDNSDomain, + [Parameter(Mandatory=$true)][String]$ManagementDNSServer, + [Parameter(Mandatory=$true)][String]$ManagementJumpHostIP, + [Parameter(Mandatory=$true)][String]$ManagementPassword, + [Switch]$Troubleshoot + ) + + # Login to console and install VyOS before starting configuration + if(-Not $Troubleshoot) { + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "install image" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "Auto" -ReturnCarriage $true + Start-Sleep -Seconds 1 + Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true + Start-Sleep -Seconds 10 + Set-VMKeystrokes -VMName $VMName -StringInput "vyos-router" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true + Start-Sleep -Seconds 10 + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "configure" -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + + foreach ($cmd in Get-Content -Path $ConfigFile | Where-Object { $_.Trim() -ne '' }) { + if($cmd.Contains('[MANAGEMENT_ADDRESS]')) { + $cmd = $cmd.replace('[MANAGEMENT_ADDRESS]',$ManagementAddress) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_IP]')) { + $ManagementAddress = $ManagementAddress.substring(0,$ManagementAddress.IndexOf('/')) + $cmd = $cmd.replace('[MANAGEMENT_IP]',$ManagementAddress) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_GATEWAY]')) { + $cmd = $cmd.replace('[MANAGEMENT_GATEWAY]',$ManagementGateway) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[JUMPHOST_VM_IP]')) { + $cmd = $cmd.replace('[JUMPHOST_VM_IP]',$ManagementJumpHostIP) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_DNS_DOMAIN]')) { + $cmd = $cmd.replace('[MANAGEMENT_DNS_DOMAIN]',$ManagementDNSDomain) + $cmd = $cmd.replace('[MANAGEMENT_DNS_SERVER]',$ManagementDNSServer) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_DNS_SERVER]')) { + $cmd = $cmd.replace('[MANAGEMENT_DNS_SERVER]',$ManagementDNSServer) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } else { + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } + } + +} \ No newline at end of file diff --git a/Modules/VyOS/vyos.template b/Modules/VyOS/vyos.template new file mode 100644 index 0000000..df42ad8 --- /dev/null +++ b/Modules/VyOS/vyos.template @@ -0,0 +1,64 @@ +set service ssh port 22 + +set interfaces ethernet eth0 address '[MANAGEMENT_ADDRESS]' +set interfaces ethernet eth0 description 'Outside' +set interfaces ethernet eth1 address '192.168.0.1/24' +set interfaces ethernet eth1 description 'Inside' +set nat source rule 100 outbound-interface 'eth0' +set nat source rule 100 translation address '[MANAGEMENT_IP]' +set nat source rule 100 translation address 'masquerade' +set protocols static route 0.0.0.0/0 next-hop [MANAGEMENT_GATEWAY] + +set interfaces ethernet eth1 mtu '1700' +set interfaces ethernet eth1 vif 10 address '172.30.10.1/24' +set interfaces ethernet eth1 vif 10 description 'VLAN 10 for MGMT' +set interfaces ethernet eth1 vif 20 address '172.30.20.1/24' +set interfaces ethernet eth1 vif 20 description 'VLAN 20 for HOST VTEP' +set interfaces ethernet eth1 vif 20 mtu '1700' +set interfaces ethernet eth1 vif 30 address '172.30.30.1/24' +set interfaces ethernet eth1 vif 30 description 'VLAN 30 for EDGE VTEP' +set interfaces ethernet eth1 vif 30 mtu '1700' +set interfaces ethernet eth1 vif 40 address '172.30.40.1/24' +set interfaces ethernet eth1 vif 40 description 'VLAN 40 for EDGE UPLINK' +set interfaces ethernet eth1 vif 40 mtu '1700' + +set nat destination rule 100 description 'RDP to [JUMPHOST_VM_IP]:3389' +set nat destination rule 100 destination port '3389' +set nat destination rule 100 inbound-interface 'eth0' +set nat destination rule 100 protocol 'tcp' +set nat destination rule 100 translation address '192.168.0.10' +set nat destination rule 100 translation port '3389' + +set service dns forwarding domain [MANAGEMENT_DNS_DOMAIN] server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 10.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 20.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 30.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 40.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding allow-from 0.0.0.0/0 +set service dns forwarding listen-address 192.168.0.1 +set service dns forwarding listen-address 172.30.10.1 +set service dns forwarding listen-address 172.30.20.1 +set service dns forwarding listen-address 172.30.30.1 +set service dns forwarding listen-address 172.30.40.1 +set service dns forwarding name-server 8.8.8.8 +set service dns forwarding name-server 8.8.8.4 + +set nat source rule 10 outbound-interface eth0 +set nat source rule 10 source address 172.30.10.0/24 +set nat source rule 10 translation address masquerade + +set nat source rule 20 outbound-interface eth0 +set nat source rule 20 source address 172.30.20.0/24 +set nat source rule 20 translation address masquerade + +set nat source rule 30 outbound-interface eth0 +set nat source rule 30 source address 172.30.30.0/24 +set nat source rule 30 translation address masquerade + +set nat source rule 40 outbound-interface eth0 +set nat source rule 40 source address 172.30.40.0/24 +set nat source rule 40 translation address masquerade + +commit +save + From 5d570cb0dfcddbb938b9d8feec5cc655cacbde7f Mon Sep 17 00:00:00 2001 From: William Lam Date: Sat, 8 Feb 2020 06:44:01 -0800 Subject: [PATCH 163/175] VyOS Automation Signed-off-by: William Lam --- Modules/VyOS/VyOS.psm1 | 271 +++++++++++++++++++++++++++++++++++++ Modules/VyOS/vyos.template | 64 +++++++++ 2 files changed, 335 insertions(+) create mode 100644 Modules/VyOS/VyOS.psm1 create mode 100644 Modules/VyOS/vyos.template diff --git a/Modules/VyOS/VyOS.psm1 b/Modules/VyOS/VyOS.psm1 new file mode 100644 index 0000000..31fbc0d --- /dev/null +++ b/Modules/VyOS/VyOS.psm1 @@ -0,0 +1,271 @@ +Function Set-VMKeystrokes { + param( + [Parameter(Mandatory=$true)][String]$VMName, + [Parameter(Mandatory=$true)][String]$StringInput, + [Parameter(Mandatory=$false)][Boolean]$ReturnCarriage, + [Parameter(Mandatory=$false)][Boolean]$DebugOn + ) + + # Map subset of USB HID keyboard scancodes + # https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2 + $hidCharacterMap = @{ + "a"="0x04"; + "b"="0x05"; + "c"="0x06"; + "d"="0x07"; + "e"="0x08"; + "f"="0x09"; + "g"="0x0a"; + "h"="0x0b"; + "i"="0x0c"; + "j"="0x0d"; + "k"="0x0e"; + "l"="0x0f"; + "m"="0x10"; + "n"="0x11"; + "o"="0x12"; + "p"="0x13"; + "q"="0x14"; + "r"="0x15"; + "s"="0x16"; + "t"="0x17"; + "u"="0x18"; + "v"="0x19"; + "w"="0x1a"; + "x"="0x1b"; + "y"="0x1c"; + "z"="0x1d"; + "1"="0x1e"; + "2"="0x1f"; + "3"="0x20"; + "4"="0x21"; + "5"="0x22"; + "6"="0x23"; + "7"="0x24"; + "8"="0x25"; + "9"="0x26"; + "0"="0x27"; + "!"="0x1e"; + "@"="0x1f"; + "#"="0x20"; + "$"="0x21"; + "%"="0x22"; + "^"="0x23"; + "&"="0x24"; + "*"="0x25"; + "("="0x26"; + ")"="0x27"; + "_"="0x2d"; + "+"="0x2e"; + "{"="0x2f"; + "}"="0x30"; + "|"="0x31"; + ":"="0x33"; + "`""="0x34"; + "~"="0x35"; + "<"="0x36"; + ">"="0x37"; + "?"="0x38"; + "-"="0x2d"; + "="="0x2e"; + "["="0x2f"; + "]"="0x30"; + "\"="0x31"; + "`;"="0x33"; + "`'"="0x34"; + ","="0x36"; + "."="0x37"; + "/"="0x38"; + " "="0x2c"; + } + + $vm = Get-View -ViewType VirtualMachine -Filter @{"Name"="^$($VMName)$"} + + # Verify we have a VM or fail + if(!$vm) { + Write-host "Unable to find VM $VMName" + return + } + + $hidCodesEvents = @() + foreach($character in $StringInput.ToCharArray()) { + # Check to see if we've mapped the character to HID code + if($hidCharacterMap.ContainsKey([string]$character)) { + $hidCode = $hidCharacterMap[[string]$character] + + $tmp = New-Object VMware.Vim.UsbScanCodeSpecKeyEvent + + # Add leftShift modifer for capital letters and/or special characters + if( ($character -cmatch "[A-Z]") -or ($character -match "[!|@|#|$|%|^|&|(|)|_|+|{|}|||:|~|<|>|?|*]") ) { + $modifer = New-Object Vmware.Vim.UsbScanCodeSpecModifierType + $modifer.LeftShift = $true + $tmp.Modifiers = $modifer + } + + # Convert to expected HID code format + $hidCodeHexToInt = [Convert]::ToInt64($hidCode,"16") + $hidCodeValue = ($hidCodeHexToInt -shl 16) -bor 0007 + + $tmp.UsbHidCode = $hidCodeValue + $hidCodesEvents+=$tmp + + if($DebugOn) { + Write-Host "Character: $character -> HIDCode: $hidCode -> HIDCodeValue: $hidCodeValue" + } + } else { + Write-Host "The following character `"$character`" has not been mapped, you will need to manually process this character" + break + } + } + + # Add return carriage to the end of the string input (useful for logins or executing commands) + if($ReturnCarriage) { + # Convert return carriage to HID code format + $hidCodeHexToInt = [Convert]::ToInt64("0x28","16") + $hidCodeValue = ($hidCodeHexToInt -shl 16) + 7 + + $tmp = New-Object VMware.Vim.UsbScanCodeSpecKeyEvent + $tmp.UsbHidCode = $hidCodeValue + $hidCodesEvents+=$tmp + } + + # Call API to send keystrokes to VM + $spec = New-Object Vmware.Vim.UsbScanCodeSpec + $spec.KeyEvents = $hidCodesEvents + Write-Host "Sending `'$StringInput`' ...`n" + $results = $vm.PutUsbScanCodes($spec) +} + +Function New-VyOSConfiguration { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + This function automates the installation and configuration of VyOS from ISO + .PARAMETER VMName + The name of the VyOS VM + .PARAMETER ManagementPassword + The password to configure for the vyos user + .PARAMETER ConfigFile + The path to VyOS configuration file + .PARAMETER ManagementAddress + The IP Address of the WAN Interface (eth0) + .PARAMETER ManagementGateway + The Gateway Addrss of the WAN Interface (eth0) + .PARAMETER ManagementDNSDomain + The DNS Domain on the WAN network + .PARAMETER ManagementDNSServer + The DNS Server on the WAN Network + .PARAMETER ManagementJumpHostIP + The IP Address of Windows Jumphost that can be used to RDP into various VLANs + .EXAMPLE + New-VyOSConfiguration -VMName VyOS-Router -ConfigFile vyos.template -ManagementAddress 192.168.30.155/24 -ManagementGateway 192.168.30.1 -ManagementDNSDomain primp-industries.com -ManagementDNSServer 192.168.30.2 -ManagementJumpHostIP 192.168.30.199 -ManagementPassword VMware1! +#> + param( + [Parameter(Mandatory=$true)][String]$VMName, + [Parameter(Mandatory=$true)][String]$ConfigFile, + [Parameter(Mandatory=$true)][String]$ManagementAddress, + [Parameter(Mandatory=$true)][String]$ManagementGateway, + [Parameter(Mandatory=$true)][String]$ManagementDNSDomain, + [Parameter(Mandatory=$true)][String]$ManagementDNSServer, + [Parameter(Mandatory=$true)][String]$ManagementJumpHostIP, + [Parameter(Mandatory=$true)][String]$ManagementPassword, + [Switch]$Troubleshoot + ) + + # Login to console and install VyOS before starting configuration + if(-Not $Troubleshoot) { + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "install image" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "Auto" -ReturnCarriage $true + Start-Sleep -Seconds 1 + Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true + Start-Sleep -Seconds 10 + Set-VMKeystrokes -VMName $VMName -StringInput "vyos-router" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true + Start-Sleep -Seconds 10 + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "configure" -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + + foreach ($cmd in Get-Content -Path $ConfigFile | Where-Object { $_.Trim() -ne '' }) { + if($cmd.Contains('[MANAGEMENT_ADDRESS]')) { + $cmd = $cmd.replace('[MANAGEMENT_ADDRESS]',$ManagementAddress) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_IP]')) { + $ManagementAddress = $ManagementAddress.substring(0,$ManagementAddress.IndexOf('/')) + $cmd = $cmd.replace('[MANAGEMENT_IP]',$ManagementAddress) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_GATEWAY]')) { + $cmd = $cmd.replace('[MANAGEMENT_GATEWAY]',$ManagementGateway) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[JUMPHOST_VM_IP]')) { + $cmd = $cmd.replace('[JUMPHOST_VM_IP]',$ManagementJumpHostIP) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_DNS_DOMAIN]')) { + $cmd = $cmd.replace('[MANAGEMENT_DNS_DOMAIN]',$ManagementDNSDomain) + $cmd = $cmd.replace('[MANAGEMENT_DNS_SERVER]',$ManagementDNSServer) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } elseif($cmd.Contains('[MANAGEMENT_DNS_SERVER]')) { + $cmd = $cmd.replace('[MANAGEMENT_DNS_SERVER]',$ManagementDNSServer) + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } else { + if($Troubleshoot) { + $cmd + } else { + Set-VMKeystrokes -VMName $VMName -StringInput $cmd -ReturnCarriage $true + Start-Sleep -Seconds 1 + } + } + } + +} \ No newline at end of file diff --git a/Modules/VyOS/vyos.template b/Modules/VyOS/vyos.template new file mode 100644 index 0000000..df42ad8 --- /dev/null +++ b/Modules/VyOS/vyos.template @@ -0,0 +1,64 @@ +set service ssh port 22 + +set interfaces ethernet eth0 address '[MANAGEMENT_ADDRESS]' +set interfaces ethernet eth0 description 'Outside' +set interfaces ethernet eth1 address '192.168.0.1/24' +set interfaces ethernet eth1 description 'Inside' +set nat source rule 100 outbound-interface 'eth0' +set nat source rule 100 translation address '[MANAGEMENT_IP]' +set nat source rule 100 translation address 'masquerade' +set protocols static route 0.0.0.0/0 next-hop [MANAGEMENT_GATEWAY] + +set interfaces ethernet eth1 mtu '1700' +set interfaces ethernet eth1 vif 10 address '172.30.10.1/24' +set interfaces ethernet eth1 vif 10 description 'VLAN 10 for MGMT' +set interfaces ethernet eth1 vif 20 address '172.30.20.1/24' +set interfaces ethernet eth1 vif 20 description 'VLAN 20 for HOST VTEP' +set interfaces ethernet eth1 vif 20 mtu '1700' +set interfaces ethernet eth1 vif 30 address '172.30.30.1/24' +set interfaces ethernet eth1 vif 30 description 'VLAN 30 for EDGE VTEP' +set interfaces ethernet eth1 vif 30 mtu '1700' +set interfaces ethernet eth1 vif 40 address '172.30.40.1/24' +set interfaces ethernet eth1 vif 40 description 'VLAN 40 for EDGE UPLINK' +set interfaces ethernet eth1 vif 40 mtu '1700' + +set nat destination rule 100 description 'RDP to [JUMPHOST_VM_IP]:3389' +set nat destination rule 100 destination port '3389' +set nat destination rule 100 inbound-interface 'eth0' +set nat destination rule 100 protocol 'tcp' +set nat destination rule 100 translation address '192.168.0.10' +set nat destination rule 100 translation port '3389' + +set service dns forwarding domain [MANAGEMENT_DNS_DOMAIN] server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 10.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 20.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 30.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding domain 40.30.172.in-addr.arpa. server [MANAGEMENT_DNS_SERVER] +set service dns forwarding allow-from 0.0.0.0/0 +set service dns forwarding listen-address 192.168.0.1 +set service dns forwarding listen-address 172.30.10.1 +set service dns forwarding listen-address 172.30.20.1 +set service dns forwarding listen-address 172.30.30.1 +set service dns forwarding listen-address 172.30.40.1 +set service dns forwarding name-server 8.8.8.8 +set service dns forwarding name-server 8.8.8.4 + +set nat source rule 10 outbound-interface eth0 +set nat source rule 10 source address 172.30.10.0/24 +set nat source rule 10 translation address masquerade + +set nat source rule 20 outbound-interface eth0 +set nat source rule 20 source address 172.30.20.0/24 +set nat source rule 20 translation address masquerade + +set nat source rule 30 outbound-interface eth0 +set nat source rule 30 source address 172.30.30.0/24 +set nat source rule 30 translation address masquerade + +set nat source rule 40 outbound-interface eth0 +set nat source rule 40 source address 172.30.40.0/24 +set nat source rule 40 translation address masquerade + +commit +save + From 41f6194fdb49e465cec4b6e2255625c0d24929a9 Mon Sep 17 00:00:00 2001 From: William Lam Date: Sun, 9 Feb 2020 08:08:01 -0800 Subject: [PATCH 164/175] Updated VyOS Module --- Modules/VyOS/VyOS.psm1 | 123 +++++++++++++++++++++++++++---------- Modules/VyOS/vyos.template | 4 +- 2 files changed, 94 insertions(+), 33 deletions(-) diff --git a/Modules/VyOS/VyOS.psm1 b/Modules/VyOS/VyOS.psm1 index 31fbc0d..4c1c952 100644 --- a/Modules/VyOS/VyOS.psm1 +++ b/Modules/VyOS/VyOS.psm1 @@ -136,6 +136,62 @@ Function Set-VMKeystrokes { $results = $vm.PutUsbScanCodes($spec) } +Function New-VyOSInstallation { +<# + .NOTES + =========================================================================== + Created by: William Lam + Organization: VMware + Blog: www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + .DESCRIPTION + This function automates the installation and configuration of VyOS from ISO + .PARAMETER VMName + The name of the VyOS VM + .PARAMETER ManagementPassword + The password to configure for the vyos user + .EXAMPLE + New-VyOSInstallation -VMName VyOS-Router -ManagementPassword VMware1! +#> + param( + [Parameter(Mandatory=$true)][String]$VMName, + [Parameter(Mandatory=$true)][String]$ManagementPassword + ) + + # Login to console and install VyOS before starting configuration + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "install image" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "Auto" -ReturnCarriage $true + Start-Sleep -Seconds 1 + Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true + Start-Sleep -Seconds 10 + Set-VMKeystrokes -VMName $VMName -StringInput "vyos-router" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true + Start-Sleep -Seconds 10 + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "reboot" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Set-VMKeystrokes -VMName $VMName -StringInput "y" -ReturnCarriage $true + Start-Sleep -Seconds 5 + Get-VM $VMName | Get-CDDrive | Set-CDDrive -Connected $false -Confirm:$false -ErrorAction Ignore -WarningAction Ignore | Out-Null + + Write-Host -ForegroundColor Green "VyOS has been installed, VM will reboot for changes to go into effect" +} + Function New-VyOSConfiguration { <# .NOTES @@ -154,9 +210,9 @@ Function New-VyOSConfiguration { .PARAMETER ConfigFile The path to VyOS configuration file .PARAMETER ManagementAddress - The IP Address of the WAN Interface (eth0) + The IP Address of the OUTSIDE Interface (eth0) .PARAMETER ManagementGateway - The Gateway Addrss of the WAN Interface (eth0) + The Gateway Addrss of the OUTSIDE Interface (eth0) .PARAMETER ManagementDNSDomain The DNS Domain on the WAN network .PARAMETER ManagementDNSServer @@ -164,7 +220,7 @@ Function New-VyOSConfiguration { .PARAMETER ManagementJumpHostIP The IP Address of Windows Jumphost that can be used to RDP into various VLANs .EXAMPLE - New-VyOSConfiguration -VMName VyOS-Router -ConfigFile vyos.template -ManagementAddress 192.168.30.155/24 -ManagementGateway 192.168.30.1 -ManagementDNSDomain primp-industries.com -ManagementDNSServer 192.168.30.2 -ManagementJumpHostIP 192.168.30.199 -ManagementPassword VMware1! + New-VyOSConfiguration -VMName VyOS-Router -ConfigFile vyos.template -ManagementAddress 192.168.30.156/24 -ManagementGateway 192.168.30.1 -ManagementDNSDomain primp-industries.com -ManagementDNSServer 192.168.30.2 -ManagementJumpHostIP 192.168.30.199 -ManagementPassword VMware1! #> param( [Parameter(Mandatory=$true)][String]$VMName, @@ -174,38 +230,12 @@ Function New-VyOSConfiguration { [Parameter(Mandatory=$true)][String]$ManagementDNSDomain, [Parameter(Mandatory=$true)][String]$ManagementDNSServer, [Parameter(Mandatory=$true)][String]$ManagementJumpHostIP, - [Parameter(Mandatory=$true)][String]$ManagementPassword, - [Switch]$Troubleshoot + [Parameter(Mandatory=$true)][String]$ManagementPassword ) # Login to console and install VyOS before starting configuration - if(-Not $Troubleshoot) { - Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true - Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true - Set-VMKeystrokes -VMName $VMName -StringInput "install image" -ReturnCarriage $true - Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput "Auto" -ReturnCarriage $true - Start-Sleep -Seconds 1 - Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput "yes" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true - Start-Sleep -Seconds 10 - Set-VMKeystrokes -VMName $VMName -StringInput "vyos-router" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput " " -ReturnCarriage $true - Start-Sleep -Seconds 10 - Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput "sda" -ReturnCarriage $true - Start-Sleep -Seconds 5 - Set-VMKeystrokes -VMName $VMName -StringInput "configure" -ReturnCarriage $true - Start-Sleep -Seconds 1 - } + Set-VMKeystrokes -VMName $VMName -StringInput "vyos" -ReturnCarriage $true + Set-VMKeystrokes -VMName $VMName -StringInput "$ManagementPassword" -ReturnCarriage $true foreach ($cmd in Get-Content -Path $ConfigFile | Where-Object { $_.Trim() -ne '' }) { if($cmd.Contains('[MANAGEMENT_ADDRESS]')) { @@ -268,4 +298,33 @@ Function New-VyOSConfiguration { } } + <# + # Configure and Enable VyOS REST API + # REST API not very functional, no GET operatoin and a bit kludgey on setup + + $httpApiConf = "http-api.conf" + + $config = @" +{ + "listen_address": "$($ManagementAddress.substring(0,$ManagementAddress.IndexOf('/')))", + "port": 8080, + "debug": true, + "api_keys": [ + {"id": "powercli", "key": "${ManagementPassword}"} + ] +} +"@ + + $config | Set-Content "$httpApiConf" + + Get-Item "$httpApiConf" | Copy-VMGuestFile -LocalToGuest -Destination "/home/vyos/${httpApiConf}" -VM (Get-VM $VMName) -GuestUser "vyos" -GuestPassword "$ManagementPassword" -Force + + Write-Host "Creating VyOS REST API Configuration /etc/vyos/${httpApiConf} ..." + $scriptText = "echo `"${ManagementPassword}`" | sudo -S cp /home/vyos/${httpApiConf} /etc/vyos/${httpApiConf}" + Invoke-VMScript -ScriptText $scriptText -vm (Get-VM $VMName) -GuestUser "vyos" -GuestPassword $ManagementPassword + + Write-Host "Starting VyOS REST API ..." + $scriptText = "echo `"${ManagementPassword}`" | sudo -S systemctl start vyos-http-api" + Invoke-VMScript -ScriptText $scriptText -vm (Get-VM $VMName) -GuestUser "vyos" -GuestPassword $ManagementPassword + #> } \ No newline at end of file diff --git a/Modules/VyOS/vyos.template b/Modules/VyOS/vyos.template index df42ad8..023ec46 100644 --- a/Modules/VyOS/vyos.template +++ b/Modules/VyOS/vyos.template @@ -1,3 +1,5 @@ +configure + set service ssh port 22 set interfaces ethernet eth0 address '[MANAGEMENT_ADDRESS]' @@ -61,4 +63,4 @@ set nat source rule 40 translation address masquerade commit save - +exit \ No newline at end of file From e45aa0171dd868cd79b4b66b88baf32fd9dcb8f2 Mon Sep 17 00:00:00 2001 From: bfett20 <59446956+bfett20@users.noreply.github.com> Date: Mon, 24 Feb 2020 06:24:44 -0600 Subject: [PATCH 165/175] Create stale.yml --- .github/workflows/stale.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/stale.yml diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..7bbc050 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,19 @@ +name: Mark stale issues and pull requests + +on: + schedule: + - cron: "0 0 * * *" + +jobs: + stale: + + runs-on: ubuntu-latest + + steps: + - uses: actions/stale@v1 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'Stale issue message' + stale-pr-message: 'Stale pull request message' + stale-issue-label: 'no-issue-activity' + stale-pr-label: 'no-pr-activity' From 233c220dd67be91bb9aa812532f3ee7da3fa8797 Mon Sep 17 00:00:00 2001 From: bfett20 <59446956+bfett20@users.noreply.github.com> Date: Mon, 24 Feb 2020 06:30:39 -0600 Subject: [PATCH 166/175] Update VMware.Hv.Helper Added "clearGlobalEntitlement" switch to Set-HVApplication --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 89e3dfc..180f916 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -12683,6 +12683,9 @@ param ( [Parameter(Mandatory = $False)] [String]$GlobalApplicationEntitlement = $null + + [Parameter(Mandatory = $false)] + [switch]$clearGlobalEntitlement ) begin { $services = Get-ViewAPIService -HvServer $HvServer @@ -12762,6 +12765,12 @@ param ( if ($PSBoundParameters.ContainsKey("AutoUpdateOtherFileTypes")) { $updates += Get-MapEntry -key 'executionData.autoUpdateOtherFileTypes' -value $AutoUpdateOtherFileTypes } + + if ($clearGlobalEntitlement) { + $update = New-Object VMware.Hv.MapEntry + $update.key = 'data.globalApplicationEntitlement' + $updates += $update + } $AppService = New-Object VMware.Hv.ApplicationService $AppService.Application_Update($services,$App.Id,$updates) From 926260096f7b8a9e3b26a51f49fd495f1f6b7e57 Mon Sep 17 00:00:00 2001 From: bfett20 <59446956+bfett20@users.noreply.github.com> Date: Mon, 24 Feb 2020 06:40:29 -0600 Subject: [PATCH 167/175] Delete stale.yml --- .github/workflows/stale.yml | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 .github/workflows/stale.yml diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml deleted file mode 100644 index 7bbc050..0000000 --- a/.github/workflows/stale.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Mark stale issues and pull requests - -on: - schedule: - - cron: "0 0 * * *" - -jobs: - stale: - - runs-on: ubuntu-latest - - steps: - - uses: actions/stale@v1 - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-issue-message: 'Stale issue message' - stale-pr-message: 'Stale pull request message' - stale-issue-label: 'no-issue-activity' - stale-pr-label: 'no-pr-activity' From aa8d5e3c261625cdd4bf536088671d7074177cd2 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 28 Feb 2020 08:51:45 -0800 Subject: [PATCH 168/175] List VCSA Identity Source --- .../VCSAIdentitySource.psm1 | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 diff --git a/Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 b/Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 new file mode 100644 index 0000000..596cab1 --- /dev/null +++ b/Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 @@ -0,0 +1,28 @@ +Function Get-VCSAIdentitySource { +<# + .DESCRIPTION Retrieves vCenter Server Appliance Identity Source Configuration + .NOTES Author: William Lam + .PARAMETER VCSAName + Inventory name of the VCSA VM + .PARAMETER VCSARootPassword + Root password for VCSA VM + .EXAMPLE + Get-VCSAIdentitySource -VCSAName "MGMT-VCSA-01" -VCSARootPassword "VMware1!" +#> + Param ( + [Parameter(Mandatory=$true)][String]$VCSAName, + [Parameter(Mandatory=$true)][String]$VCSARootPassword + ) + + $vm = Get-Vm -Name $VCSAName + + if($vm) { + $identitySources = Invoke-VMScript -ScriptText "/opt/vmware/bin/sso-config.sh -get_identity_sources 2> /dev/null | sed -ne '/^*/,$ p'" -vm $vm -GuestUser "root" -GuestPassword $VCSARootPassword + + Write-Host -ForegroundColor green "`nIdentity Sources: " + $identitySources + + } else { + Write-Host "`nUnable to find VCSA named $VCSAName" + } +} \ No newline at end of file From f3c549a8671644e1fa513076dba998ba994f0007 Mon Sep 17 00:00:00 2001 From: William Lam Date: Fri, 28 Feb 2020 10:34:01 -0800 Subject: [PATCH 169/175] Consolidated VCSA functions into VCSA Module --- .../VCSA.psm1} | 29 +++++++++++++++++++ .../VCSAIdentitySource.psm1 | 28 ------------------ 2 files changed, 29 insertions(+), 28 deletions(-) rename Modules/{VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 => VCSA/VCSA.psm1} (64%) delete mode 100644 Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 diff --git a/Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 b/Modules/VCSA/VCSA.psm1 similarity index 64% rename from Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 rename to Modules/VCSA/VCSA.psm1 index 55963ca..a0bac0e 100644 --- a/Modules/VCSAPasswordPolicy/VCSAPasswordPolicy.psm1 +++ b/Modules/VCSA/VCSA.psm1 @@ -36,4 +36,33 @@ Function Get-VCSAPasswordPolicy { } else { Write-Host "`nUnable to find VCSA named $VCSAName" } +} + +Function Get-VCSAIdentitySource { +<# + .DESCRIPTION Retrieves vCenter Server Appliance Identity Source Configuration + .NOTES Author: William Lam + .PARAMETER VCSAName + Inventory name of the VCSA VM + .PARAMETER VCSARootPassword + Root password for VCSA VM + .EXAMPLE + Get-VCSAIdentitySource -VCSAName "MGMT-VCSA-01" -VCSARootPassword "VMware1!" +#> + Param ( + [Parameter(Mandatory=$true)][String]$VCSAName, + [Parameter(Mandatory=$true)][String]$VCSARootPassword + ) + + $vm = Get-Vm -Name $VCSAName + + if($vm) { + $identitySources = Invoke-VMScript -ScriptText "/opt/vmware/bin/sso-config.sh -get_identity_sources 2> /dev/null | sed -ne '/^*/,$ p'" -vm $vm -GuestUser "root" -GuestPassword $VCSARootPassword + + Write-Host -ForegroundColor green "`nIdentity Sources: " + $identitySources + + } else { + Write-Host "`nUnable to find VCSA named $VCSAName" + } } \ No newline at end of file diff --git a/Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 b/Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 deleted file mode 100644 index 596cab1..0000000 --- a/Modules/VCSAIdentitySource/VCSAIdentitySource.psm1 +++ /dev/null @@ -1,28 +0,0 @@ -Function Get-VCSAIdentitySource { -<# - .DESCRIPTION Retrieves vCenter Server Appliance Identity Source Configuration - .NOTES Author: William Lam - .PARAMETER VCSAName - Inventory name of the VCSA VM - .PARAMETER VCSARootPassword - Root password for VCSA VM - .EXAMPLE - Get-VCSAIdentitySource -VCSAName "MGMT-VCSA-01" -VCSARootPassword "VMware1!" -#> - Param ( - [Parameter(Mandatory=$true)][String]$VCSAName, - [Parameter(Mandatory=$true)][String]$VCSARootPassword - ) - - $vm = Get-Vm -Name $VCSAName - - if($vm) { - $identitySources = Invoke-VMScript -ScriptText "/opt/vmware/bin/sso-config.sh -get_identity_sources 2> /dev/null | sed -ne '/^*/,$ p'" -vm $vm -GuestUser "root" -GuestPassword $VCSARootPassword - - Write-Host -ForegroundColor green "`nIdentity Sources: " - $identitySources - - } else { - Write-Host "`nUnable to find VCSA named $VCSAName" - } -} \ No newline at end of file From 3cf69178d5a5ef27123232b00eaea28fbe15d933 Mon Sep 17 00:00:00 2001 From: William Lam Date: Thu, 5 Mar 2020 10:12:36 -0800 Subject: [PATCH 170/175] Support Disconnected NSX-T Segments for {New,Set}-NSXTSegment --- Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 | 115 ++++++++++++++++++- 1 file changed, 112 insertions(+), 3 deletions(-) diff --git a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 index 42be532..649efe2 100644 --- a/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 +++ b/Modules/VMware.VMC.NSXT/VMware.VMC.NSXT.psm1 @@ -120,10 +120,12 @@ Function Get-NSXTSegment { $network = $subnets.network $gateway = $subnets.gateway_address $dhcpRange = $subnets.dhcp_ranges + $type = $segment.type $tmp = [pscustomobject] @{ Name = $segment.display_name; ID = $segment.Id; + TYPE = $type; Network = $network; Gateway = $gateway; DHCPRange = $dhcpRange; @@ -156,6 +158,8 @@ Function New-NSXTSegment { New-NSXTSegment -Name "sddc-cgw-network-4" -Gateway "192.168.4.1/24" -DHCP -DHCPRange "192.168.4.2-192.168.4.254" -DomainName 'vmc.local' .EXAMPLE New-NSXTSegment -Name "sddc-cgw-network-5" -Gateway "192.168.5.1/24" + .EXAMPLE + New-NSXTSegment -Name "sddc-cgw-network-5" -Gateway "192.168.5.1/24" -Disconnected #> Param ( [Parameter(Mandatory=$True)]$Name, @@ -163,6 +167,7 @@ Function New-NSXTSegment { [Parameter(Mandatory=$False)]$DHCPRange, [Parameter(Mandatory=$False)]$DomainName, [Switch]$DHCP, + [Switch]$Disconnected, [Switch]$Troubleshoot ) @@ -178,9 +183,21 @@ Function New-NSXTSegment { } } - $payload = @{ - display_name = $Name; - subnets = @($subnets) + if($Disconnected) { + $payload = @{ + display_name = $Name; + subnets = @($subnets) + advanced_config = @{ + local_egress = "False" + connectivity = "OFF"; + } + type = "DISCONNECTED"; + } + } else { + $payload = @{ + display_name = $Name; + subnets = @($subnets) + } } if($DomainName) { @@ -221,6 +238,98 @@ Function New-NSXTSegment { } } +Function Set-NSXTSegment { +<# + .NOTES + =========================================================================== + Created by: William Lam + Date: 03/04/2018 + Organization: VMware + Blog: http://www.virtuallyghetto.com + Twitter: @lamw + =========================================================================== + + .SYNOPSIS + Set a NSX-T Segment (Logical Networks) to either connected or disconnected + .DESCRIPTION + This cmdlet set an NSX-T Segment (Logical Networks) to either connected or disconnected + .EXAMPLE + New-NSXTSegment -Name "sddc-cgw-network-4" -Disconnected + .EXAMPLE + New-NSXTSegment -Name "sddc-cgw-network-4" -Connected + +#> + Param ( + [Parameter(Mandatory=$True)]$Name, + [Switch]$Disconnected, + [Switch]$Connected, + [Switch]$Troubleshoot + ) + + If (-Not $global:nsxtProxyConnection) { Write-error "No NSX-T Proxy Connection found, please use Connect-NSXTProxy" } Else { + $SegmentId = (Get-NSXTSegment -Name $Name).Id + + if($Disconnected) { + $type = "DISCONNECTED" + $connectivity = "OFF" + $localEgress = "False" + $gateway = (Get-NSXTSegment -Name $Name).Gateway + } + + If($Connected) { + $type = "ROUTED" + $connectivity = "ON" + $localEgress = "True" + $gateway = (Get-NSXTSegment -Name $Name).Gateway + } + + $subnets = @{ + gateway_address = $gateway; + } + + $payload = @{ + advanced_config = @{ + local_egress = $localEgress; + connectivity = $connectivity; + } + type = $type; + subnets = @($subnets) + } + + $body = $payload | ConvertTo-Json -depth 4 + + $method = "PATCH" + $aegmentsURL = $global:nsxtProxyConnection.Server + "/policy/api/v1/infra/tier-1s/cgw/segments/$SegmentId" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$newSegmentsURL`n" + Write-Host -ForegroundColor cyan "[DEBUG]`n$body`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $requests = Invoke-WebRequest -Uri $aegmentsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers -SkipCertificateCheck + } else { + $requests = Invoke-WebRequest -Uri $aegmentsURL -Body $body -Method $method -Headers $global:nsxtProxyConnection.headers + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe NSX-T Proxy session is no longer valid, please re-run the Connect-NSXTProxy cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in updating NSX-T Segment connectivity" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($requests.StatusCode -eq 200) { + Write-Host "Successfully updated NSX-T Segment $Name" + ($requests.Content | ConvertFrom-Json) | select display_name, id + } + } +} + Function Remove-NSXTSegment { <# .NOTES From c5c836d3d6028cc08ffe5f51ce10589288a478e0 Mon Sep 17 00:00:00 2001 From: Kyle Ruddy Date: Fri, 6 Mar 2020 11:48:31 -0500 Subject: [PATCH 171/175] Update VMware.HV.Helper.psm1 Updated per Issue #357 --- Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 index 180f916..8ff7cbe 100644 --- a/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 +++ b/Modules/VMware.Hv.Helper/VMware.HV.Helper.psm1 @@ -12682,7 +12682,7 @@ param ( [Boolean]$AutoUpdateOtherFileTypes = $True, [Parameter(Mandatory = $False)] - [String]$GlobalApplicationEntitlement = $null + [String]$GlobalApplicationEntitlement = $null, [Parameter(Mandatory = $false)] [switch]$clearGlobalEntitlement From 23ad3e0f6409fb50ef3126346c4615924ef6122a Mon Sep 17 00:00:00 2001 From: Baoyin Qiao Date: Thu, 2 Apr 2020 18:57:41 +0800 Subject: [PATCH 172/175] Create Readme file --- .../VMware.TrustedInfrastructure.Helper/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Modules/VMware.TrustedInfrastructure.Helper/README.md diff --git a/Modules/VMware.TrustedInfrastructure.Helper/README.md b/Modules/VMware.TrustedInfrastructure.Helper/README.md new file mode 100644 index 0000000..8e5f2de --- /dev/null +++ b/Modules/VMware.TrustedInfrastructure.Helper/README.md @@ -0,0 +1,15 @@ +Prerequisites/Steps to use this module: + 1. You must be a Trust Authority Administrator, a part of the TrustedAdmins group and also have the "Host.Inventory.Add Host To Cluster" privilege on vCenter system. + 2. The ESXi host must be wiped from existing Trusted Infrastructure configuration. If the ESXi host has been previously configured as part of vSphere Trust Authority (part of a vCenter configured for vSphere Trust Authority, a Trust Authority Cluster or Trusted Cluster), you must use the decommission script first. + 3. Clusters should be in a healthy state (check all vSphere Trust Authority APIs which return Health field). + 4. The ESXi host must be removed from vCenter. +- 5. You must know the ESXi host root credentials (username and password). +- 5. You must have purchased sufficient license for vSphere Trust Authority. +- 7. You must have PowerCLI 12.0.0 and above. +- 8. Following PowerCLI module is required to be imported: VMware.VimAutomation.Security. +- 9. Run the command Get-Command -Module VMware.TrustedInfrastructure.Helper. This should inform the following functions are available: + - Add-TrustAuthorityVMHost + - Add-TrustedVMHost + If you do not see these functions listed, the PowerCLI module is not loaded correctly. + 10. Run Get-Help Add-TrustAuthorityVMHost -full and Get-Help Add-TrustedVMHost -full to see how to use these two functions. + 11. Others, please refer vSphere documentation. From 3d74470c70c9141e25d2d1600794f3049c100f95 Mon Sep 17 00:00:00 2001 From: Baoyin Qiao Date: Thu, 2 Apr 2020 18:58:49 +0800 Subject: [PATCH 173/175] Update README.md --- .../VMware.TrustedInfrastructure.Helper/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Modules/VMware.TrustedInfrastructure.Helper/README.md b/Modules/VMware.TrustedInfrastructure.Helper/README.md index 8e5f2de..059f61b 100644 --- a/Modules/VMware.TrustedInfrastructure.Helper/README.md +++ b/Modules/VMware.TrustedInfrastructure.Helper/README.md @@ -1,15 +1,15 @@ Prerequisites/Steps to use this module: 1. You must be a Trust Authority Administrator, a part of the TrustedAdmins group and also have the "Host.Inventory.Add Host To Cluster" privilege on vCenter system. - 2. The ESXi host must be wiped from existing Trusted Infrastructure configuration. If the ESXi host has been previously configured as part of vSphere Trust Authority (part of a vCenter configured for vSphere Trust Authority, a Trust Authority Cluster or Trusted Cluster), you must use the decommission script first. + 2. The ESXi host must be wiped from existing Trusted Infrastructure configuration. If the ESXi host has been previously configured as part of vSphere Trust Authority (part of a vCenter configured for vSphere Trust Authority, a Trust Authority Cluster or Trusted Cluster), you must use the decommission script first. 3. Clusters should be in a healthy state (check all vSphere Trust Authority APIs which return Health field). 4. The ESXi host must be removed from vCenter. -- 5. You must know the ESXi host root credentials (username and password). -- 5. You must have purchased sufficient license for vSphere Trust Authority. -- 7. You must have PowerCLI 12.0.0 and above. -- 8. Following PowerCLI module is required to be imported: VMware.VimAutomation.Security. -- 9. Run the command Get-Command -Module VMware.TrustedInfrastructure.Helper. This should inform the following functions are available: + 5. You must know the ESXi host root credentials (username and password). + 6. You must have purchased sufficient license for vSphere Trust Authority. + 7. You must have PowerCLI 12.0.0 and above. + 8. Following PowerCLI module is required to be imported: VMware.VimAutomation.Security. + 9. Run the command Get-Command -Module VMware.TrustedInfrastructure.Helper. This should inform the following functions are available: - Add-TrustAuthorityVMHost - Add-TrustedVMHost - If you do not see these functions listed, the PowerCLI module is not loaded correctly. + If you do not see these functions listed, the PowerCLI module is not loaded correctly. 10. Run Get-Help Add-TrustAuthorityVMHost -full and Get-Help Add-TrustedVMHost -full to see how to use these two functions. 11. Others, please refer vSphere documentation. From adba00b7e822af02d7bec55002b450bc5f0d7758 Mon Sep 17 00:00:00 2001 From: Baoyin Qiao Date: Thu, 2 Apr 2020 19:00:30 +0800 Subject: [PATCH 174/175] Adding the module script and manifest of it --- .../VMware.TrustedInfrastructure.Helper.psd1 | 316 +++++ .../VMware.TrustedInfrastructure.Helper.psm1 | 1176 +++++++++++++++++ 2 files changed, 1492 insertions(+) create mode 100644 Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psd1 create mode 100644 Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psm1 diff --git a/Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psd1 b/Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psd1 new file mode 100644 index 0000000..274d301 --- /dev/null +++ b/Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psd1 @@ -0,0 +1,316 @@ +# +# Module manifest for module 'VMware.TrustedInfrastructure.Helper' +# +# Generated by: VMware +# +# Generated on: 2020/04/02 +# + +@{ + +# Script module or binary module file associated with this manifest. +# RootModule = '' + +# Version number of this module. +ModuleVersion = '1.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = 'dbf002d4-1f6a-43d7-994f-3275275e08f9' + +# Author of this module +Author = 'VMware' + +# Company or vendor of this module +CompanyName = 'VMware, Inc.' + +# Copyright statement for this module +Copyright = 'Copyright (c) 2020 VMware, Inc. All rights reserved.' + +# Description of the functionality provided by this module +# Description = '' + +# Minimum version of the Windows PowerShell engine required by this module +# PowerShellVersion = '' + +# Name of the Windows PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the Windows PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' + +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# CLRVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +RequiredModules = @( + +@{"ModuleName"="VMware.VimAutomation.Security";"ModuleVersion"="12.0.0.15939672"} + +) + +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +NestedModules = @('VMware.TrustedInfrastructure.Helper.psm1') + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +# FunctionsToExport = @() + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @('Add-TrustedVMHost', 'Add-TrustAuthorityVMHost') + +# Variables to export from this module +# VariablesToExport = '*' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +# AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} + +# SIG # Begin signature block +# MIIi9AYJKoZIhvcNAQcCoIIi5TCCIuECAQExDzANBglghkgBZQMEAgEFADB5Bgor +# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG +# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBpNQqsdVk1BjVn +# MMKwrDCn/ghozrgmuT8MkgPS925Zl6CCD8swggTMMIIDtKADAgECAhBdqtQcwalQ +# C13tonk09GI7MA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQK +# ExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3Qg +# TmV0d29yazEwMC4GA1UEAxMnU3ltYW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBT +# aWduaW5nIENBMB4XDTE4MDgxMzAwMDAwMFoXDTIxMDkxMTIzNTk1OVowZDELMAkG +# A1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEjAQBgNVBAcMCVBhbG8gQWx0 +# bzEVMBMGA1UECgwMVk13YXJlLCBJbmMuMRUwEwYDVQQDDAxWTXdhcmUsIEluYy4w +# ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCuswYfqnKot0mNu9VhCCCR +# vVcCrxoSdB6G30MlukAVxgQ8qTyJwr7IVBJXEKJYpzv63/iDYiNAY3MOW+Pb4qGI +# bNpafqxc2WLW17vtQO3QZwscIVRapLV1xFpwuxJ4LYdsxHPZaGq9rOPBOKqTP7Jy +# KQxE/1ysjzacA4NXHORf2iars70VpZRksBzkniDmurvwCkjtof+5krxXd9XSDEFZ +# 9oxeUGUOBCvSLwOOuBkWPlvCnzEqMUeSoXJavl1QSJvUOOQeoKUHRycc54S6Lern +# 2ddmdUDPwjD2cQ3PL8cgVqTsjRGDrCgOT7GwShW3EsRsOwc7o5nsiqg/x7ZmFpSJ +# AgMBAAGjggFdMIIBWTAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDArBgNVHR8E +# JDAiMCCgHqAchhpodHRwOi8vc3Yuc3ltY2IuY29tL3N2LmNybDBhBgNVHSAEWjBY +# MFYGBmeBDAEEATBMMCMGCCsGAQUFBwIBFhdodHRwczovL2Quc3ltY2IuY29tL2Nw +# czAlBggrBgEFBQcCAjAZDBdodHRwczovL2Quc3ltY2IuY29tL3JwYTATBgNVHSUE +# DDAKBggrBgEFBQcDAzBXBggrBgEFBQcBAQRLMEkwHwYIKwYBBQUHMAGGE2h0dHA6 +# Ly9zdi5zeW1jZC5jb20wJgYIKwYBBQUHMAKGGmh0dHA6Ly9zdi5zeW1jYi5jb20v +# c3YuY3J0MB8GA1UdIwQYMBaAFJY7U/B5M5evfYPvLivMyreGHnJmMB0GA1UdDgQW +# BBTVp9RQKpAUKYYLZ70Ta983qBUJ1TANBgkqhkiG9w0BAQsFAAOCAQEAlnsx3io+ +# W/9i0QtDDhosvG+zTubTNCPtyYpv59Nhi81M0GbGOPNO3kVavCpBA11Enf0CZuEq +# f/ctbzYlMRONwQtGZ0GexfD/RhaORSKib/ACt70siKYBHyTL1jmHfIfi2yajKkMx +# UrPM9nHjKeagXTCGthD/kYW6o7YKKcD7kQUyBhofimeSgumQlm12KSmkW0cHwSSX +# TUNWtshVz+74EcnZtGFI6bwYmhvnTp05hWJ8EU2Y1LdBwgTaRTxlSDP9JK+e63vm +# SXElMqnn1DDXABT5RW8lNt6g9P09a2J8p63JGgwMBhmnatw7yrMm5EAo+K6gVliJ +# LUMlTW3O09MbDTCCBVkwggRBoAMCAQICED141/l2SWCyYX308B7KhiowDQYJKoZI +# hvcNAQELBQAwgcoxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j +# LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazE6MDgGA1UECxMxKGMp +# IDIwMDYgVmVyaVNpZ24sIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTFF +# MEMGA1UEAxM8VmVyaVNpZ24gQ2xhc3MgMyBQdWJsaWMgUHJpbWFyeSBDZXJ0aWZp +# Y2F0aW9uIEF1dGhvcml0eSAtIEc1MB4XDTEzMTIxMDAwMDAwMFoXDTIzMTIwOTIz +# NTk1OVowfzELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0 +# aW9uMR8wHQYDVQQLExZTeW1hbnRlYyBUcnVzdCBOZXR3b3JrMTAwLgYDVQQDEydT +# eW1hbnRlYyBDbGFzcyAzIFNIQTI1NiBDb2RlIFNpZ25pbmcgQ0EwggEiMA0GCSqG +# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCXgx4AFq8ssdIIxNdok1FgHnH24ke021hN +# I2JqtL9aG1H3ow0Yd2i72DarLyFQ2p7z518nTgvCl8gJcJOp2lwNTqQNkaC07BTO +# kXJULs6j20TpUhs/QTzKSuSqwOg5q1PMIdDMz3+b5sLMWGqCFe49Ns8cxZcHJI7x +# e74xLT1u3LWZQp9LYZVfHHDuF33bi+VhiXjHaBuvEXgamK7EVUdT2bMy1qEORkDF +# l5KK0VOnmVuFNVfT6pNiYSAKxzB3JBFNYoO2untogjHuZcrf+dWNsjXcjCtvanJc +# YISc8gyUXsBWUgBIzNP4pX3eL9cT5DiohNVGuBOGwhud6lo43ZvbAgMBAAGjggGD +# MIIBfzAvBggrBgEFBQcBAQQjMCEwHwYIKwYBBQUHMAGGE2h0dHA6Ly9zMi5zeW1j +# Yi5jb20wEgYDVR0TAQH/BAgwBgEB/wIBADBsBgNVHSAEZTBjMGEGC2CGSAGG+EUB +# BxcDMFIwJgYIKwYBBQUHAgEWGmh0dHA6Ly93d3cuc3ltYXV0aC5jb20vY3BzMCgG +# CCsGAQUFBwICMBwaGmh0dHA6Ly93d3cuc3ltYXV0aC5jb20vcnBhMDAGA1UdHwQp +# MCcwJaAjoCGGH2h0dHA6Ly9zMS5zeW1jYi5jb20vcGNhMy1nNS5jcmwwHQYDVR0l +# BBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMDMA4GA1UdDwEB/wQEAwIBBjApBgNVHREE +# IjAgpB4wHDEaMBgGA1UEAxMRU3ltYW50ZWNQS0ktMS01NjcwHQYDVR0OBBYEFJY7 +# U/B5M5evfYPvLivMyreGHnJmMB8GA1UdIwQYMBaAFH/TZafC3ey78DAJ80M5+gKv +# MzEzMA0GCSqGSIb3DQEBCwUAA4IBAQAThRoeaak396C9pK9+HWFT/p2MXgymdR54 +# FyPd/ewaA1U5+3GVx2Vap44w0kRaYdtwb9ohBcIuc7pJ8dGT/l3JzV4D4ImeP3Qe +# 1/c4i6nWz7s1LzNYqJJW0chNO4LmeYQW/CiwsUfzHaI+7ofZpn+kVqU/rYQuKd58 +# vKiqoz0EAeq6k6IOUCIpF0yH5DoRX9akJYmbBWsvtMkBTCd7C6wZBSKgYBU/2sn7 +# TUyP+3Jnd/0nlMe6NQ6ISf6N/SivShK9DbOXBd5EDBX6NisD3MFQAfGhEV0U5eK9 +# J0tUviuEXg+mw3QFCu+Xw4kisR93873NQ9TxTKk/tYuEr2Ty0BQhMIIFmjCCA4Kg +# AwIBAgIKYRmT5AAAAAAAHDANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJVUzET +# MBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMV +# TWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3NvZnQgQ29kZSBW +# ZXJpZmljYXRpb24gUm9vdDAeFw0xMTAyMjIxOTI1MTdaFw0yMTAyMjIxOTM1MTda +# MIHKMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNV +# BAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA2IFZl +# cmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMT +# PFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBB +# dXRob3JpdHkgLSBHNTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8k +# CAgpejWeYAyq50s7Ttx8vDxFHLsr4P4pAvlXCKNkhRUn9fGtyDGJXSLoKqqmQrOP +# +LlVt7G3S7P+j34HV+zvQ9tmYhVhz2ANpNje+ODDYgg9VBPrScpZVIUm5SuPG5/r +# 9aGRwjNJ2ENjalJL0o/ocFFN0Ylpe8dw9rPcEnTbe11LVtOWvxV3obD0oiXyrxyS +# Zxjl9AYE75C55ADk3Tq1Gf8CuvQ87uCL6zeL7PTXrPL28D2v3XWRMxkdHEDLdCQZ +# IZPZFP6sKlLHj9UESeSNY0eIPGmDy/5HvSt+T8WVrg6d1NFDwGdz4xQIfuU/n3O4 +# MwrPXT80h5aK7lPoJRUCAwEAAaOByzCByDARBgNVHSAECjAIMAYGBFUdIAAwDwYD +# VR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAYYwHQYDVR0OBBYEFH/TZafC3ey78DAJ +# 80M5+gKvMzEzMB8GA1UdIwQYMBaAFGL7CiFbf0NuEdoJVFBr9dKWcfGeMFUGA1Ud +# HwROMEwwSqBIoEaGRGh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3By +# b2R1Y3RzL01pY3Jvc29mdENvZGVWZXJpZlJvb3QuY3JsMA0GCSqGSIb3DQEBBQUA +# A4ICAQCBKoIWjDRnK+UD6zR7jKKjUIr0VYbxHoyOrn3uAxnOcpUYSK1iEf0g/T9H +# BgFa4uBvjBUsTjxqUGwLNqPPeg2cQrxc+BnVYONp5uIjQWeMaIN2K4+Toyq1f75Z +# +6nJsiaPyqLzghuYPpGVJ5eGYe5bXQdrzYao4mWAqOIV4rK+IwVqugzzR5NNrKSM +# B3k5wGESOgUNiaPsn1eJhPvsynxHZhSR2LYPGV3muEqsvEfIcUOW5jIgpdx3hv08 +# 44tx23ubA/y3HTJk6xZSoEOj+i6tWZJOfMfyM0JIOFE6fDjHGyQiKEAeGkYfF9sY +# 9/AnNWy4Y9nNuWRdK6Ve78YptPLH+CHMBLpX/QG2q8Zn+efTmX/09SL6cvX9/zoc +# Qjqh+YAYpe6NHNRmnkUB/qru//sXjzD38c0pxZ3stdVJAD2FuMu7kzonaknAMK5m +# yfcjKDJ2+aSDVshIzlqWqqDMDMR/tI6Xr23jVCfDn4bA1uRzCJcF29BUYl4DSMLV +# n3+nZozQnbBP1NOYX0t6yX+yKVLQEoDHD1S2HmfNxqBsEQOE00h15yr+sDtuCjqm +# a3aZBaPxd2hhMxRHBvxTf1K9khRcSiRqZ4yvjZCq0PZ5IRuTJnzDzh69iDiSrkXG +# GWpJULMF+K5ZN4pqJQOUsVmBUOi6g4C3IzX0drlnHVkYrSCNlDGCEn8wghJ7AgEB +# MIGTMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlv +# bjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEwMC4GA1UEAxMnU3lt +# YW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBAhBdqtQcwalQC13t +# onk09GI7MA0GCWCGSAFlAwQCAQUAoIGWMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3 +# AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCoGCisGAQQBgjcCAQwx +# HDAaoRiAFmh0dHA6Ly93d3cudm13YXJlLmNvbS8wLwYJKoZIhvcNAQkEMSIEIM0S +# yl+DLO5/G6CpV6dDnBERqJttAW4XXH7Aky0XuDpFMA0GCSqGSIb3DQEBAQUABIIB +# AFFIiFbh7hbtFYhpRzq2TM3DZ2R+LpRz2DdVTOR8iLirTkwcZvCMbsx4wZbcoDpQ +# uldpdbJS1CuXAX+TW48NtE/ph0wA+c2D5CgAvyamV9Zz/Jog9W8bYrytl3A1JNCk +# cT6xdg8L+E6OAx1L4ls8giqJXOoJSpFX4fD8Wzdd2cA4GgfPSZ3V+KahgxnOmglp +# rVcsFfdMywtGyfVyYU5ZP/a2Wo9uGioZVYaRuW6gUc8aziUWpeeUCPDeOMTpRCVE +# Hu4YO7usse7/W2c4sQGe273k/AYyyVf1pLQrmoW5Q453KcpiZa3FJAPBoyamCO2i +# 0b1IdrfRwgriLapWu2Qv4SyhghAjMIIQHwYKKwYBBAGCNwMDATGCEA8wghALBgkq +# hkiG9w0BBwKggg/8MIIP+AIBAzEPMA0GCWCGSAFlAwQCAQUAMIHmBgsqhkiG9w0B +# CRABBKCB1gSB0zCB0AIBAQYJKwYBBAGgMgIDMDEwDQYJYIZIAWUDBAIBBQAEIPY5 +# SN6u90hWWtb8WksRwND3bUpYHl/udJrlk3gg43Q7Ag4BbKiJKXgAAAAAAKUUyRgT +# MjAyMDA0MDIxMDI5MTcuMjUzWjADAgEBoGOkYTBfMQswCQYDVQQGEwJKUDEcMBoG +# A1UEChMTR01PIEdsb2JhbFNpZ24gSy5LLjEyMDAGA1UEAxMpR2xvYmFsU2lnbiBU +# U0EgZm9yIEFkdmFuY2VkIC0gRzMgLSAwMDMtMDGgggxqMIIE6jCCA9KgAwIBAgIM +# M5Agd2HEJt2UUAMNMA0GCSqGSIb3DQEBCwUAMFsxCzAJBgNVBAYTAkJFMRkwFwYD +# VQQKExBHbG9iYWxTaWduIG52LXNhMTEwLwYDVQQDEyhHbG9iYWxTaWduIFRpbWVz +# dGFtcGluZyBDQSAtIFNIQTI1NiAtIEcyMB4XDTE4MDYxNDEwMDAwMFoXDTI5MDMx +# ODEwMDAwMFowXzELMAkGA1UEBhMCSlAxHDAaBgNVBAoTE0dNTyBHbG9iYWxTaWdu +# IEsuSy4xMjAwBgNVBAMTKUdsb2JhbFNpZ24gVFNBIGZvciBBZHZhbmNlZCAtIEcz +# IC0gMDAzLTAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv3Gj+IDO +# E5Be8KfdP9KY8kE6Sdp/WC+ePDoBE8ptNJlbDCccROdW4wkv9W+rTr4nYmbGuLKH +# x2W+xsBeqT6u+yR0iyv4aARkhqo64qohj/rxnbkYMF6afAf1O3Uu2gklGav+c+lx +# neyq9j4ShYEUJPjmPpnfrvO5i9UmywSommFW7yhwqEtqKyVq5aA2ny25mofcdA4f +# QqBBOpYHDst7MtUBC1ORfVY0T7S8sHRHnKp6bF/kjlGfk5BhAz6PX0FBUHg5LRIS +# 3OvqADCyP+FtE7d1SBVrTg7Rl+NO25bZ0WKvCEHPIg/o3c7Y6pNWbtM6j2dKaki6 +# /GHlbFmzEi0CgQIDAQABo4IBqDCCAaQwDgYDVR0PAQH/BAQDAgeAMEwGA1UdIARF +# MEMwQQYJKwYBBAGgMgEeMDQwMgYIKwYBBQUHAgEWJmh0dHBzOi8vd3d3Lmdsb2Jh +# bHNpZ24uY29tL3JlcG9zaXRvcnkvMAkGA1UdEwQCMAAwFgYDVR0lAQH/BAwwCgYI +# KwYBBQUHAwgwRgYDVR0fBD8wPTA7oDmgN4Y1aHR0cDovL2NybC5nbG9iYWxzaWdu +# LmNvbS9ncy9nc3RpbWVzdGFtcGluZ3NoYTJnMi5jcmwwgZgGCCsGAQUFBwEBBIGL +# MIGIMEgGCCsGAQUFBzAChjxodHRwOi8vc2VjdXJlLmdsb2JhbHNpZ24uY29tL2Nh +# Y2VydC9nc3RpbWVzdGFtcGluZ3NoYTJnMi5jcnQwPAYIKwYBBQUHMAGGMGh0dHA6 +# Ly9vY3NwMi5nbG9iYWxzaWduLmNvbS9nc3RpbWVzdGFtcGluZ3NoYTJnMjAdBgNV +# HQ4EFgQUeaezg3HWs0B2IOZ0Crf39+bd3XQwHwYDVR0jBBgwFoAUkiGnSpVdZLCb +# tB7mADdH5p1BK0wwDQYJKoZIhvcNAQELBQADggEBAIc0fm43ZxsIEQJttimYchTL +# SH7IyY8viQ2vD/IsIZBuO7ccAaqBaMQQI0v4CeOrX+pFps4O/qSA6WtqDAD5yoYQ +# DD7/HxrpHOUil2TZrOnj6NpTYGMLt45P3NUh9J3eE2o4NeVs4yZM29Z0Z0W5TwTE +# WAgam2ZFPSQaGpJXyV8oR3hn21zKrQvotw/RthYyNCIENnJM73umvLauBMDZeKCI +# yIZrGNqWjStuIlzLf70XvZ63toZNgxBNsDKy4BOgy2DihHUU6SG9EKKktgjPOw0p +# WVmp08NMDX9CzIgUtELlugTVmEqkjQc9SR94bWVtYL38zlnrLOnFqtqt7taTrBUw +# ggQVMIIC/aADAgECAgsEAAAAAAExicZQBDANBgkqhkiG9w0BAQsFADBMMSAwHgYD +# VQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2ln +# bjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xMTA4MDIxMDAwMDBaFw0yOTAzMjkx +# MDAwMDBaMFsxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNh +# MTEwLwYDVQQDEyhHbG9iYWxTaWduIFRpbWVzdGFtcGluZyBDQSAtIFNIQTI1NiAt +# IEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqpuOw6sRUSUBtpaU +# 4k/YwQj2RiPZRcWVl1urGr/SbFfJMwYfoA/GPH5TSHq/nYeer+7DjEfhQuzj46FK +# bAwXxKbBuc1b8R5EiY7+C94hWBPuTcjFZwscsrPxNHaRossHbTfFoEcmAhWkkJGp +# eZ7X61edK3wi2BTX8QceeCI2a3d5r6/5f45O4bUIMf3q7UtxYowj8QM5j0R5tnYD +# V56tLwhG3NKMvPSOdM7IaGlRdhGLD10kWxlUPSbMQI2CJxtZIH1Z9pOAjvgqOP1r +# oEBlH1d2zFuOBE8sqNuEUBNPxtyLufjdaUyI65x7MCb8eli7WbwUcpKBV7d2ydiA +# CoBuCQIDAQABo4HoMIHlMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/ +# AgEAMB0GA1UdDgQWBBSSIadKlV1ksJu0HuYAN0fmnUErTDBHBgNVHSAEQDA+MDwG +# BFUdIAAwNDAyBggrBgEFBQcCARYmaHR0cHM6Ly93d3cuZ2xvYmFsc2lnbi5jb20v +# cmVwb3NpdG9yeS8wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz +# aWduLm5ldC9yb290LXIzLmNybDAfBgNVHSMEGDAWgBSP8Et/qC5FJK5NUPpjmove +# 4t0bvDANBgkqhkiG9w0BAQsFAAOCAQEABFaCSnzQzsm/NmbRvjWek2yX6AbOMRhZ +# +WxBX4AuwEIluBjH/NSxN8RooM8oagN0S2OXhXdhO9cv4/W9M6KSfREfnops7yyw +# 9GKNNnPRFjbxvF7stICYePzSdnno4SGU4B/EouGqZ9uznHPlQCLPOc7b5neVp7uy +# y/YZhp2fyNSYBbJxb051rvE9ZGo7Xk5GpipdCJLxo/MddL9iDSOMXCo4ldLA1c3P +# iNofKLW6gWlkKrWmotVzr9xG2wSukdduxZi61EfEVnSAR3hYjL7vK/3sbL/RlPe/ +# UOB74JD9IBh4GCJdCC6MHKCX8x2ZfaOdkdMGRE4EbnocIOM28LZQuTCCA18wggJH +# oAMCAQICCwQAAAAAASFYUwiiMA0GCSqGSIb3DQEBCwUAMEwxIDAeBgNVBAsTF0ds +# b2JhbFNpZ24gUm9vdCBDQSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYD +# VQQDEwpHbG9iYWxTaWduMB4XDTA5MDMxODEwMDAwMFoXDTI5MDMxODEwMDAwMFow +# TDEgMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkds +# b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wggEiMA0GCSqGSIb3DQEBAQUA +# A4IBDwAwggEKAoIBAQDMJXaQeQZ4Ihb1wIO2hMoonv0FdhHFrYhy/EYCQ8eyip0E +# XyTLLkvhYIJG4VKrDIFHcGzdZNHr9SyjD4I9DCuul9e2FIYQebs7E4B3jAjhSdJq +# Yi8fXvqWaN+JJ5U4nwbXPsnLJlkNc96wyOkmDoMVxu9bi9IEYMpJpij2aTv2y8go +# keWdimFXN6x0FNx04Druci8unPvQu7/1PQDhBjPogiuuU6Y6FnOM3UEOIDrAtKeh +# 6bJPkC4yYOlXy7kEkmho5TgmYHWyn3f/kRTvriBJ/K1AFUjRAjFhGV64l++td7dk +# mnq/X8ET75ti+w1s4FRpFqkD2m7pg5NxdsZphYIXAgMBAAGjQjBAMA4GA1UdDwEB +# /wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSP8Et/qC5FJK5NUPpj +# move4t0bvDANBgkqhkiG9w0BAQsFAAOCAQEAS0DbwFCq/sgM7/eWVEVJu5YACUGs +# sxOGhigHM8pr5nS5ugAtrqQK0/Xx8Q+Kv3NnSoPHRHt44K9ubG8DKY4zOUXDjuS5 +# V2yq/BKW7FPGLeQkbLmUY/vcU2hnVj6DuM81IcPJaP7O2sJTqsyQiunwXUaMld16 +# WCgaLx3ezQA3QY/tRG3XUyiXfvNnBB4V14qWtNPeTCekTBtzc3b0F5nCH3oO4y0I +# rQocLP88q1UOD5F+NuvDV0m+4S4tfGCLw0FREyOdzvcya5QBqJnnLDMfOjsl0oZA +# zjsshnjJYS8Uuu7bVW/fhO4FCU29KNhyztNiUGUe65KXgzHZs7XKR1g/XzGCAokw +# ggKFAgEBMGswWzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt +# c2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gU0hBMjU2 +# IC0gRzICDDOQIHdhxCbdlFADDTANBglghkgBZQMEAgEFAKCB8DAaBgkqhkiG9w0B +# CQMxDQYLKoZIhvcNAQkQAQQwLwYJKoZIhvcNAQkEMSIEIAZrKdIvpe4etJdIpute +# bD7Bkgo2OLI6O5CjboEGMuXnMIGgBgsqhkiG9w0BCRACDDGBkDCBjTCBijCBhwQU +# rmsC2QsljAmRsRYSid62aVY5HW8wbzBfpF0wWzELMAkGA1UEBhMCQkUxGTAXBgNV +# BAoTEEdsb2JhbFNpZ24gbnYtc2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0 +# YW1waW5nIENBIC0gU0hBMjU2IC0gRzICDDOQIHdhxCbdlFADDTANBgkqhkiG9w0B +# AQEFAASCAQCtspr11iTT8uoLlJY6Gmk9/dEzqYSh+ib0ml+qk5WNO2g0ggA42yp9 +# lnUfnLFUdqTCTm1kP5QHYISnBRVq88TDVqPOlxMUr/pxaWGi95NgkMbYS0A9bEf1 +# 0B1BjUsVHdEcRmW3RYU6bgmcoMKCNNvt2U0+r/e85MW358FMr5+Qwje5xKFhFKQi +# wZkY34+ycnFsyMBwDCYeMxIWEAJdFdp+BQ1NI4hE1+whqEoXxBFbHABzoK7CQfZt +# x38BWzvhRjGc4DFiTH25oqKHmzvvBrtIBhR1KGP0UxgJtLIkBu1lqqVCpD2DuOpu +# 6Q/wMh8Z+1DanPs+68ioAyOE0N4MaVz+ +# SIG # End signature block diff --git a/Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psm1 b/Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psm1 new file mode 100644 index 0000000..b2cfe08 --- /dev/null +++ b/Modules/VMware.TrustedInfrastructure.Helper/VMware.TrustedInfrastructure.Helper.psm1 @@ -0,0 +1,1176 @@ +# Script Module : VMware.TrustedInfrastructure.Helper +# Version : 1.0 + +# Copyright © 2020 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. + +$TrustedClusterSettingsFile = +-join((48..57 + 65..90 + 97..122) | get-random -count 6 | %{[char]$_})+".json" + +$TrustAuthorityClusterSettingsFile = +-join((48..57 + 65..90 + 97..122) | get-random -count 6 | %{[char]$_})+".json" + +Function Add-TrustAuthorityVMHost { + <# + .SYNOPSIS + + This cmdlet adds a new host into the specific Trust Authority cluster. + There are some preconditions need to be met: + 1. The newly added host is cleared of any previous Trust Authority configurations + 2. The Trust Authority Cluster settings are all healthy + 3. The connection user has the needed privileges. Please, check vSphere documentation. + 4. The trust between Key Servers and TrustAuthorityKeyProvider uses the signed client certificate, user should provide its privateKey part + + .DESCRIPTION + This cmdlet adds a new host into the specific Trust Authority cluster. + + .PARAMETER TrustAuthorityCluster + Specifies the Trust Authority cluster you want to add the new host. + + .PARAMETER VMHostAddress + Specifies the ip address of the new host you want to add to the specific Trust Authority cluster. + + .PARAMETER Credential + Specifies the credential of the new host. + + .PARAMETER DestDir + Specifies the location where you want to save the settings + + .PARAMETER PrivateKey + Specifies the private key part of the ClientCertificate of the TrustAuthorityKeyProvider. It's a hashtable type with: the keyprovider.Name as the Key, and the File having the PrivateKey string for the ClientCertificate of the keyprovider as its Value. + + .PARAMETER BaseImageFolder + Specifies the folder having all the baseImage files to re-create the TrustAuthorityVMHostBaseImage. + + .EXAMPLE + PS C:\> $ts = Get-TrustAuthorityCluster "mycluster" + PS C:\> $pass = Read-Host "Please enter the host's password" -AsSecureString + PS C:\> $credential = New-Object System.Management.Automation.PSCredential -ArgumentList root,$pass + PS C:\> $privateKeyHash = @{"provider1"="c:\myprivatekey.txt";} + PS C:\> Add-TrustAuthorityVMHost -TrustAuthorityCluster $ts -VMHostAddress 1.1.1.1 -Credential $credential -DestDir c:\destDir\ -PrivateKey $privateKeyHash -BaseImageFolder "c:\baseImages\" + + Add the host 1.1.1.1 with the $credential to Trust Authority cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\. + + .EXAMPLE + PS C:\> $ts = Get-TrustAuthorityCluster "mycluster" + PS C:\> Add-TrustAuthorityVMHost -TrustAuthorityCluster $ts -VMHostAddress 1.1.1.1 -Credential root -DestDir c:\destDir\ -BaseImageFolder "c:\baseImages\" + + Add the host 1.1.1.1 with the credential root (a window wizard will be prompted to let you input the password for the user root) to Trust Authority cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\. + + .NOTES + Author : Carrie Yang + Author email : yangm@vmware.com + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustAuthorityCluster] $TrustAuthorityCluster, + + [Parameter(Mandatory=$True)] + [String] $VMHostAddress, + + [Parameter(Mandatory=$True)] + [System.Management.Automation.Credential()] + $Credential, + + [Parameter(Mandatory=$True)] + [String] $DestDir, + + [hashtable] $PrivateKey, + + [Parameter(Mandatory=$True)] + [String] $BaseImageFolder + ) + + Begin { + Write-Warning "Please confirm the new host to add is cleared from any previous Trust Authority Configurations." -WarningAction Inquire + + Write-Warning "Please confirm the connection user has the privilege to add the new host to the cluster $($TrustAuthorityCluster.Name)." -WarningAction Inquire + + Write-Warning "Please confirm the connection user has been added to 'TrustedAdmins' group." -WarningAction Inquire + + $server = GetViServer -clusterUid $TrustAuthorityCluster.Uid + + ConfirmIsVCenter $server + + Check-VMHostVersionAndLicense -VMHostName $VMHostAddress -Credential $Credential -CheckLicense:$false -ErrorAction Stop + $DestinationFile = Join-Path $destDir $TrustAuthorityClusterSettingsFile + Write-Verbose "The file to save settings is $DestinationFile" + + Check-TrustAuthorityClusterHealth -TrustAuthorityCluster $TrustAuthorityCluster + IsSelfSignedClientCertificate -TrustAuthorityCluster $TrustAuthorityCluster -privateKey $privateKey + } + + Process { + Save-TrustAuthorityClusterSettings -TrustAuthorityCluster $TrustAuthorityCluster -DestinationFile $DestinationFile -ErrorAction Stop + + Join-VMHost -ClusterName $TrustAuthorityCluster.Name -VMHostAddress $VMHostAddress -Credential $Credential -ErrorAction Stop + Apply-TrustAuthorityClusterSettings -TrustAuthorityCluster $TrustAuthorityCluster -SettingsFile $DestinationFile -BaseImageFolder $baseImageFolder -PrivateKey $privateKey -ErrorAction Stop + } +} + +Function Add-TrustedVMHost { + <# + .SYNOPSIS + + This cmdlet adds a new host into the specific Trusted cluster. + There are some preconditions need to be met: + 1. No active workloads in the workload host as the cmdlet will interrup the workloads + 2. The newly added host is cleared of any previous Trust Authority Configurations + 3. Sufficient license + + .DESCRIPTION + This cmdlet adds a new host into the specific Trusted cluster. + + .PARAMETER TrustedCluster + Specifies the Trusted cluster you want to add the new host. + + .PARAMETER VMHostAddress + Specifies the ip address of the new host you want to add to the specific Trusted cluster. + + .PARAMETER Credential + Specifies the credential of the new host. + + .PARAMETER DestDir + Specifies the location where you want to save the settings + + .EXAMPLE + PS C:\> $ts = Get-TrustedCluster "mycluster" + PS C:\> $pass = Read-Host "Please enter the host's password" -AsSecureString + PS C:\> $credential = New-Object System.Management.Automation.PSCredential -ArgumentList root,$pass + PS C:\> Add-TrustedVMHost -TrustedCluster $ts -VMHostAddress 1.1.1.1 -Credential $credential -DestDir c:\destDir\ + + Add the host 1.1.1.1 with the $credential to Trusted Cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\. + + .EXAMPLE + PS C:\> $ts = Get-TrustedCluster "mycluster" + PS C:\> Add-TrustedVMHost -TrustedCluster $ts -VMHostAddress 1.1.1.1 -Credential root -DestDir c:\destDir\ + + Add the host 1.1.1.1 with the credential root (a window wizard will be prompted to let you input the password for the user root) to Trusted Cluster "mycluster", also saves the setting file of the trustedcluster "mycluster" to folder c:\destDir\. + + .NOTES + Author : Carrie Yang + Author email : yangm@vmware.com + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustedCluster] $TrustedCluster, + + [Parameter(Mandatory=$True)] + [String] $VMHostAddress, + + [Parameter(Mandatory=$True)] + [System.Management.Automation.Credential()] + $Credential, + + [Parameter(Mandatory=$True)] + [String] $DestDir + ) + + Begin { + Write-Warning "Please confirm workload cluster has no currently active workloads! This operation will interrupt the active crypto operations." -WarningAction Inquire + + Write-Warning "Please confirm the new host to add is cleared from any previous Trust Authority Configurations." -WarningAction Inquire + + Write-Warning "Please confirm the connection user has the privilege to add the new host to the cluster $($TrustedCluster.Name)." -WarningAction Inquire + + Write-Warning "Please confirm the connection user has been added to 'TrustedAdmins' group." -WarningAction Inquire + + $server = GetViServer -clusterUid $TrustedCluster.Uid + Write-Verbose "The server got is: $server" + ConfirmIsVCenter $server + + Check-VMHostVersionAndLicense -VMHostName $VMHostAddress -Credential $Credential -CheckLicense:$true + $DestinationFile = Join-Path $DestDir $TrustedClusterSettingsFile + Write-Verbose "The file to save settings is $DestinationFile" + } + + Process { + Check-TrustedClusterSettings -TrustedCluster $TrustedCluster -ErrorAction Stop + Save-TrustedClusterSettings -TrustedCluster $TrustedCluster -DestinationFile $DestinationFile -ErrorAction Stop + Remove-TrustedClusterSettings -TrustedCluster $TrustedCluster -ErrorAction Stop + Join-VMHost -ClusterName $TrustedCluster.Name -VMHostAddress $VMHostAddress -Credential $Credential -ErrorAction Stop + Apply-TrustedClusterSettings -TrustedCluster $TrustedCluster -SettingsFile $DestinationFile -ErrorAction Stop + } +} + +Function Save-TrustedClusterSettings { + <# + .SYNOPSIS + This cmdlet saves the settings of the specific Trusted Cluster to the file $DestinationFile. + + .DESCRIPTION + This cmdlet saves the settings of the specific Trusted Cluster to the file $DestinationFile. + + .PARAMETER TrustedCluster + Specifies the Trusted Cluster you want to save the settings. + + .PARAMETER DestinationFile + Specifies the file you want to save the settings to. + + .EXAMPLE + PS C:\> $ts = Get-TrustedCluster "mycluster" + PS C:\> Save-TrustedClusterSettings -TrustedCluster $ts -DestinationFile "c:\myfile.json" + Saves the settings of Trusted Cluster "mycluster" to file c:\myfile.json. + + .NOTES + Author : Carrie Yang + Author email : yangm@vmware.com + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustedCluster] $TrustedCluster, + + [Parameter(Mandatory=$True)] + [String] $DestinationFile + ) + + Begin { + $greenvc = GetViServer -clusterUid $TrustedCluster.Uid + Write-Host "Saving the settings of TrustedCluster $($TrustedCluster.Name)..." + } + + Process { + $TrustedCluster = Get-TrustedCluster $TrustedCluster.Name -Server $greenvc + + $TrustedClusterjson = @" + { + "VC": "", + "TrustedCluster": + { + "Name": "$($TrustedCluster.Name)", + "AttestationServiceInfo": [], + "KeyProviderServiceInfo": [] + } + } +"@ + $attestInfo = $TrustedCluster.AttestationServiceInfo + $keyproviderInfo = $TrustedCluster.KeyProviderServiceInfo + $jsonObj = ConvertFrom-Json -InputObject $TrustedClusterjson + $jsonObj.VC = $greenvc + $jsonObj.TrustedCluster.AttestationServiceInfo = $attestInfo + $jsonObj.TrustedCluster.KeyProviderServiceInfo = $keyproviderInfo + + $jsonObj | ConvertTo-Json | Out-File $DestinationFile -Force + } +} + +Function Save-TrustAuthorityClusterSettings { + <# + .SYNOPSIS + This cmdlet saves the settings of the specific Trust Authority Cluster to the file $DestinationFile. + + .DESCRIPTION + This cmdlet saves the settings of the specific Trust Authority Cluster to the file $DestinationFile. + + .PARAMETER TrustedCluster + Specifies the Trust Authority Cluster you want to save the settings. + + .PARAMETER DestinationFile + Specifies the file you want to save the settings to. + + .EXAMPLE + + PS C:\> $ts = Get-TrustAuthorityCluster "mycluster" + PS C:\> Save-TrustAuthorityClusterSettings -TrustAuthorityCluster $ts -DestinationFile "c:\myfile.json" + Saves the settings of Trust Authority Cluster "mycluster" to file c:\myfile.json. + + .NOTES + Author : Carrie Yang + Author email : yangm@vmware.com + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustAuthorityCluster] $TrustAuthorityCluster, + + [Parameter(Mandatory=$True)] + [String] $DestinationFile + ) + + Begin { + $bluevc = GetViServer -clusterUid $TrustAuthorityCluster.Uid + Write-Host "Saving the settings of TrustAuthorityCluster $($TrustAuthorityCluster.Name)..." + } + + Process { + $json = @" + { + "VC": "", + "TrustAuthorityCluster": { + "Name": "", + "TrustAuthorityPrincipal": [], + "TrustAuthorityKeyProvider": [], + "TrustAuthorityVMHostBaseImage": [], + "TrustAuthorityTpm2AttestationSettings": {}, + "TrustAuthorityTpm2CACertificate": [], + "TrustAuthorityTpm2EndorsementKey": [] + } + } +"@ + $jsonObj = ConvertFrom-Json -InputObject $json + $jsonObj.VC = $bluevc + $jsonObj.TrustAuthorityCluster.Name = $TrustAuthorityCluster.Name + $kp = Get-TrustAuthorityKeyProvider -Cluster $TrustAuthorityCluster -Server $bluevc + + $i = 0 + + if ($kp -ne $null) { + $jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider = $kp | Select-Object -Property Name, MasterKeyId, Description, ProxyAddress, ProxyPort, ConnectionTimeoutSeconds, KmipServerUsername + $clientCert = @{} + $serverCert = @{} + $clientCSR = @{} + } + + foreach ($_ in $kp) { + $kps = Get-TrustAuthorityKeyProviderServer -KeyProvider $_ -Server $bluevc| Select-Object -Property Address, Port, Name + $clientCertTemp = Get-TrustAuthorityKeyProviderClientCertificate -KeyProvider $_ -Server $bluevc + $clientCertStr = [System.Convert]::ToBase64String($($clientCertTemp.GetRawCertData())) + $serverCertTemp = Get-TrustAuthorityKeyProviderServerCertificate -KeyProvider $_ -Server $bluevc | Select-Object -Property CertificateRawData, Trusted + $clientCSRTemp = Get-TrustAuthorityKeyProviderClientCertificateCSR -KeyProvider $_ -Server $bluevc + + $jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider[$i] | Add-Member -Name "KmipServers" -value $kps -MemberType NoteProperty + $jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider[$i] | Add-Member -Name "ClientCertificate" -value $clientCertStr -MemberType NoteProperty + $jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider[$i] | Add-Member -Name "ClientCertificateCSR" -value $clientCSRTemp -MemberType NoteProperty + $jsonObj.TrustAuthorityCluster.TrustAuthorityKeyProvider[$i] | Add-Member -Name "ServerCertificate" -value $serverCertTemp -MemberType NoteProperty + $i++ + + if ($clientCertTemp -ne $null) { + $clientCert.Add($_.Name, $clientCertTemp) + } + + if ($serverCertTemp -ne $null) { + $serverCert.Add($_.Name, $serverCertTemp) + } + + if (![string]::IsNullOrWhiteSpace($clientCSRTemp)) { + $clientCSR.Add($_.Name, $clientCSRTemp) + } + } + + $principals = Get-TrustAuthorityPrincipal -Cluster $TrustAuthorityCluster -Server $bluevc| Select-Object -Property Name, Issuer, Domain, Type, IssuerAlias, certRawData + + $tpm2Settings = Get-TrustAuthorityTpm2AttestationSettings -Cluster $TrustAuthorityCluster -Server $bluevc | Select-Object -Property RequireEndorsementKey, RequireCertificateValidation + $tpm2CA = Get-TrustAuthorityTpm2CACertificate -Cluster $TrustAuthorityCluster -Server $bluevc + $tpm2Ek = Get-TrustAuthorityTpm2EndorsementKey -Cluster $TrustAuthorityCluster -Server $bluevc + $baseImages = Get-TrustAuthorityVMHostBaseImage -Cluster $TrustAuthorityCluster -Server $bluevc + + $jsonObj.VC = GetViServer -clusterUid $TrustAuthorityCluster.Uid + $jsonObj.TrustAuthorityCluster.TrustAuthorityPrincipal = $principals + + $jsonObj.TrustAuthorityCluster.TrustAuthorityTpm2AttestationSettings = $tpm2Settings + + $jsonObj.TrustAuthorityCluster.TrustAuthorityTpm2CACertificate = $tpm2CA | Select-Object -Property Name + + $i = 0 + foreach ($_ in $tpm2CA) { + $certStr = ConvertFrom-X509Chain -CertChain $_.CertificateChain + $jsonObj.TrustAuthorityCluster.TrustAuthorityTpm2CACertificate[$i] | Add-Member -Name "certRawData" -value $certStr -MemberType NoteProperty + + $i++ + } + + $jsonObj.TrustAuthorityCluster.TrustAuthorityTpm2EndorsementKey = $tpm2Ek + $jsonObj.TrustAuthorityCluster.TrustAuthorityVMHostBaseImage = $baseImages + + $jsonObj | ConvertTo-Json -Depth 6 | Out-File $DestinationFile -Force + } +} + +Function Apply-TrustAuthorityClusterSettings { + <# + .SYNOPSIS + This cmdlet applies the settings in the specific $SettingsFile to a Trust Authority Cluster. + Here are some limitations when applying the TrustAuthorityKeyProvider Settings: + - The CSR configuration will not be preserved, user needs to reset the CSR and get it signed by the Key Server, then retrieve the signed client certificate to set it back to TrustAuthorityKeyProvider + - If self signed certificates are used for trust setup, they need to be redone on new host. + + .DESCRIPTION + This cmdlet applies the settings in the specific $SettingsFile to a Trust Authority Cluster + + .PARAMETER TrustAuthorityCluster + Specifies the Trust Authority Cluster you want to apply the settings + + .PARAMETER SettingsFile + Specifies the file having the settings you want to apply + + .PARAMETER PrivateKey + Specifies the private key part of the ClientCertificate of the TrustAuthorityKeyProvider. It is a hashtable type with: the Key is the TrustAuthorityKeyProvider.Name, and the Value is the filePath for the TrustAuthorityKeyProvider's ClientCertificate PrivateKey part. + + .PARAMETER BaseImageFolder + Specifies the folder having all the baseImage files to re-create the TrustAuthorityVMHostBaseImage. All the .tgz files under this folder and its sub-folders will be used to re-create TrustAuthorityVMHostBaseImage objects. + + .EXAMPLE + PS C:\> $privateKeyHash = @{"provider1"="c:\myprivatekey.txt";} + PS C:\> $ts = Get-TrustAuthorityCluster "mycluster" + PS C:\> Apply-TrustAuthorityClusterSettings -TrustAuthorityCluster $ts -SettingsFile "c:\myfile.json" -PrivateKey $privateKeyHash -BaseImageFolder "c:\myimages\" + Applies the settings in file c:\myfile.json to Trust Authority Cluster "mycluster" with all the baseimage files under c:\myimages\ recursively, and cmdlet will prompt for inputting the password for each TrustAuthorityKeyProvider, also the PrivateKey info saved in c:\myprivatekey.txt will be used for the TrustAuthorityKeyProvider provider1. + + .NOTES + Author : Carrie Yang + Author email : yangm@vmware.com + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustAuthorityCluster] $TrustAuthorityCluster, + + [Parameter(Mandatory=$True)] + [String] $SettingsFile, + + [hashtable] $PrivateKey, + + [String] $BaseImageFolder + ) + + Begin { + Write-Host "Applying the saved settings to TrustAuthorityCluster $($TrustAuthorityCluster.Name)..." + } + + Process { + Set-TrustAuthorityCluster -TrustAuthorityCluster $TrustAuthorityCluster -State Enabled -Confirm:$false + $blueserver = GetViServer -clusterUid $TrustAuthorityCluster.Uid + + $jsonObj = Get-Content $SettingsFile | Out-String |ConvertFrom-Json + if ($($jsonObj.TrustAuthorityCluster.Name) -ne $($TrustAuthorityCluster.Name)) { + Write-Warning "Wrong TrustAuthorityCluster or wrong json file provided, the json file is not for the TrustAuthorityCluster: $($TrustAuthorityCluster.Name)" + } + + $kp = $jsonObj."TrustAuthorityCluster".TrustAuthorityKeyProvider + $principals = $jsonObj."TrustAuthorityCluster".TrustAuthorityPrincipal + $tpm2Setting = $jsonObj."TrustAuthorityCluster".TrustAuthorityTpm2AttestationSettings + $tpm2CA = $jsonObj."TrustAuthorityCluster".TrustAuthorityTpm2CACertificate + $tpm2Ek = $jsonObj."TrustAuthorityCluster".TrustAuthorityTpm2EndorsementKey + $baseImages = $jsonObj."TrustAuthorityCluster".TrustAuthorityVMHostBaseImage + + if ($kp -ne $null) { + foreach ($_ in $kp) { + $kps = $_.KmipServers + $cmd = "New-TrustAuthorityKeyProvider" + $allArgs = @{ + 'TrustAuthorityCluster' = $TrustAuthorityCluster; + 'Name' = $($_.Name); + 'MasterKeyId' = $_.MasterKeyId; + 'KmipServerName' = $kps[0].Name; + 'KmipServerAddress' = $kps[0].Address; + 'KmipServerPort' = $kps[0].Port; + 'Server' = $blueserver; + } + + if (![String]::IsNullOrWhiteSpace($_.Description)) { + $allArgs += @{'Description' = $_.Description;} + } + + if (![String]::IsNullOrWhiteSpace($_.ProxyAddress)) { + $allArgs += @{'ProxyAddress' = $_.ProxyAddress;} + } + + if (![String]::IsNullOrWhiteSpace($_.ProxyPort)) { + $allArgs += @{'ProxyPort' = $_.ProxyPort;} + } + + if (![String]::IsNullOrWhiteSpace($_.ConnectionTimeOutSeconds)) { + $allArgs += @{'ConnectionTimeOutSeconds' = $_.ConnectionTimeOutSeconds;} + } + + if (![String]::IsNullOrWhiteSpace($_.KmipServerUsername)) { + $allArgs += @{'KmipServerUsername' = $_.KmipServerUsername;} + } + + $silent = & $cmd @allArgs + + if (($kps | Measure-Object).Count -gt 1) { + for ($i = 1; $i -gt ($kps | Measure-Object).Count; $i++) { + Add-TrustAuthorityKeyProviderServer -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Address $kps[$i].Address -Name $kps[$i].Name -Port $kps[$i].Port -Server $blueserver + } + } + + if (![String]::IsNullOrWhiteSpace($($_.ClientCertificateCSR))) { + Write-Warning "CSR configuration won't be preserved, please manually establish the trust between kmip servers and trust authority keyprovider: $($_.Name)" + } + + if ($_.ClientCertificate -ne $null) { + if ($privateKey -ne $null -and $privateKey.ContainsKey($($_.Name))) { + $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 + $cert.Import([System.Text.Encoding]::Default.GetBytes($_.ClientCertificate)) + try { + $pkStr = [System.IO.File]::ReadAllText($privateKey.$($_.Name)) + } catch { + Throw "Failed to read privateKey file: $($privateKey.$($_.Name))" + } + Set-TrustAuthorityKeyProviderClientCertificate -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Certificate $cert -PrivateKey $pkStr -Server $blueserver + } else { + New-TrustAuthorityKeyProviderClientCertificate -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Server $blueserver + } + } + + if ($_.ServerCertificate -ne $null) { + $trustedcerts = [System.Collections.ArrayList]@() + foreach ($certStr in $_.ServerCertificate) { + $tempStr = $certStr.CertificateRawData + if ($certStr.Trusted) { + $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 + $cert.Import([System.Text.Encoding]::Default.GetBytes($tempStr)) + $silent = $trustedcerts.Add($cert) + } + } + Set-TrustAuthorityKeyProviderServerCertificate -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -Certificate $trustedcerts -Server $blueserver + } + + $kmipPwd = Read-Host "Enter the password of Trust Authority Key Provider $($_.Name) (Return if none)" -AsSecureString + + if ($kmipPwd.Length -gt 0) { + Set-TrustAuthorityKeyProvider -KeyProvider $_.Name -TrustAuthorityCluster $TrustAuthorityCluster -KmipServerPassword $kmipPwd -Server $blueserver + } + } + } + + if ($principals -ne $null) { + foreach ($_ in $principals) { + $chainList = [System.Collections.ArrayList]@() + foreach ($str in $_.certRawData) { + $chain = ConvertTo-X509Chain -certString $str + $silent = $chainList.Add($chain) + } + + New-TrustAuthorityPrincipal -TrustAuthorityCluster $TrustAuthorityCluster -Name $_.Name -Domain $_.Domain -Issuer $_.Issuer -CertificateChain $chainList -Type $_.Type -Server $blueserver -Confirm:$false + } + } + + if ($tpm2Setting -ne $null) { + Set-TrustAuthorityTpm2AttestationSettings -RequireCertificateValidation:$tpm2Setting.RequireCertificateValidation -RequireEndorsementKey:$tpm2Setting.RequireEndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Confirm:$false + } + + if ($tpm2CA -ne $null) { + foreach ($_ in $tpm2CA) { + $chain = ConvertTo-X509Chain $_.certRawData + New-TrustAuthorityTpm2CACertificate -TrustAuthorityCluster $TrustAuthorityCluster -CertificateChain $chain -Name $_.Name -Server $blueserver -Confirm:$false + } + } + + if ($tpm2Ek -ne $null) { + foreach ($_ in $tpm2Ek) { + New-TrustAuthorityTpm2EndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Name $_.Name -PublicKey $_.PublicKey -Server $blueserver -Confirm:$false + } + } + + if ($baseImages -ne $null) { + New-TrustAuthorityVMHostBaseImage -TrustAuthorityCluster $TrustAuthorityCluster -FilePath $baseImageFolder -Server $blueserver -Confirm:$false + } + } +} + + +Function Apply-TrustedClusterSettings { + <# + .SYNOPSIS + This cmdlet applies the settings in the specific $SettingsFile to a Trusted Cluster. + + .DESCRIPTION + This cmdlet applies the settings in the specific $SettingsFile to a Trusted Cluster + + .PARAMETER TrustedCluster + Specifies the Trusted Cluster you want to apply the settings. + + .PARAMETER SettingsFile + Specifies the file having the settings you want to apply. + + .EXAMPLE + PS C:\> $ts = Get-TrustedCluster "mycluster" + PS C:\> Apply-TrustedClusterSettings -TrustedCluster $ts -SettingsFile "c:\myfile.json" + Applies the settings in file c:\myfile.json to Trusted Cluster "mycluster". + + .NOTES + Author : Carrie Yang + Author email : yangm@vmware.com + #> + + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustedCluster] $TrustedCluster, + + [Parameter(Mandatory=$True)] + [String] $SettingsFile + ) + + Begin { + $greenvc = GetViServer -clusterUid $TrustedCluster.Uid + Write-Host "Applying the saved settings to TrustedCluster $($TrustedCluster.Name)..." + } + + Process { + $jsonObj = Get-Content $SettingsFile | ConvertFrom-Json + + if ($($jsonObj.TrustedCluster.Name) -ne $($TrustedCluster.Name)) { + Write-Warning "Wrong trustedcluster or wrong json file provided, the json file is not for the trustedcluster: $($TrustedCluster.Name)" + } + + if ($jsonObj.TrustedCluster.AttestationServiceInfo -ne $null) { + $attests = Get-AttestationServiceInfo | where {$($_.Name) -in $($jsonObj.TrustedCluster.AttestationServiceInfo)} + Add-TrustedClusterAttestationServiceInfo -TrustedCluster $TrustedCluster -AttestationServiceInfo $attests -Confirm:$false -Server $greenvc + } + + if ($jsonObj.TrustedCluster.KeyProviderServiceInfo -ne $null) { + $kms = Get-KeyProviderServiceInfo | where {$($_.Name) -in $($jsonObj.TrustedCluster.KeyProviderServiceInfo)} + Add-TrustedClusterKeyProviderServiceInfo -TrustedCluster $TrustedCluster -KeyProviderServiceInfo $kms -Confirm:$false -Server $greenvc + } + } +} + + + +Function Join-VMHost { + Param ( + [Parameter(Mandatory=$True)] + [String] $ClusterName, + + [Parameter(Mandatory=$True)] + [String] $VMHostAddress, + + [Parameter(Mandatory=$True)] + [System.Management.Automation.Credential()] + $Credential + ) + + Process { + Write-Host "Adding new host $VMHostAddress to cluster $ClusterName..." + Add-VMHost -Name $VMHostAddress -Credential $Credential -Location $ClusterName -Force + } +} + +Function Remove-TrustedClusterSettings { + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustedCluster] $TrustedCluster + ) + + Begin { + $greenvc = GetViServer -clusterUid $TrustedCluster.Uid + Write-Host "Removing the settings of TrustedCluster $($TrustedCluster.Name)..." + } + + Process { + if ($TrustedCluster.State -eq 'Enabled') { + Set-TrustedCluster -TrustedCluster $TrustedCluster -State Disabled -Server $greenvc -Confirm:$false + } else { + if ($TrustedCluster.KeyProviderServiceInfo -ne $null) { + Remove-TrustedClusterKeyProviderServiceInfo -TrustedCluster $TrustedCluster -KeyProviderServiceInfo $TrustedCluster.KeyProviderServiceInfo -Server $greenvc + } + } + } +} + + +Function IsSelfSignedClientCertificate { + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustAuthorityCluster] $TrustAuthorityCluster, + + [hashtable] $privateKey + ) + + Begin { + $bluevc = GetViServer -clusterUid $TrustAuthorityCluster.Uid + } + + Process { + $kp = Get-TrustAuthorityKeyProvider -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + + $privateKeyNotSet = $False + $kpNames = [System.Collections.ArrayList]@() + if ($kp -ne $null) { + foreach ($k in $kp) { + $clientCert = Get-TrustAuthorityKeyProviderClientCertificate -KeyProvider $k -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + if ($clientCert -ne $null -and !($privateKey -ne $null -and $privateKey.ContainsKey($($k.Name)))) { + $privateKeyNotSet = $True + $silent = $kpNames.Add($k.Name) + } + } + } + + if ($privateKeyNotSet) { + $kpnameStr = [System.String]::join(",", $($kpNames)) + Write-Warning "For self-signed client certificate, the cmdlet could not be able to establish the trust between the kmip servers and the keyprovider: ($kpnameStr). + Please manually use these followed cmdlets to establish the trust: New-TrustAuthorityKeyProviderClientCertificate, and Get-TrustAuthorityKeyProviderClientCertificate, then make the certificate be signed in kmip servers." -WarningAction Inquire + } + } +} + +Function Check-VMHostVersionAndLicense { + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True)] + [String] $VMHostName, + + [Parameter(Mandatory=$True)] + [System.Management.Automation.Credential()] + $Credential, + + [Parameter(Mandatory=$True)] + [bool]$CheckLicense + ) + + Begin { + Write-Host "Checking the version of the vmhost $VMHostName..." + } + + Process { + $server = Connect-VIServer -Server $VMHostName -Credential $Credential -ErrorAction:Stop + + $vmhost = Get-VMHost -server $server + + $apiVersion = [System.Version]$($vmhost.ApiVersion) + $MajorVersion = $apiVersion.Major + $MinorVersion = $apiVersion.Minor + $buildNum = $apiVersion.Build + if ($MajorVersion -lt 7 -And $MinorVersion -ne 0 -And $buildNum -ne 0) { + Disconnect-VIServer -Server $server -confirm:$false + Throw "VMHost of $apiVersion is not supported, only 7.0.0 is supported...`n" + } + + # Check license + if ($CheckLicense) { + Write-Host "Checking the license of the vmhost $VMHostName..." + $si = Get-View serviceinstance -Server $server + $lm = Get-View $si.Content.LicenseManager + $a = $lm.Licenses.Properties.Value | Where-Object {"trustedplatform" -in $_.Key} + if ($a -eq $null) { + Disconnect-VIServer -Server $server -confirm:$false + Throw "VMHost $VMHostName has no sufficient license to be configured as trusted infrastructure host...`n" + } + } + + Disconnect-VIServer -Server $server -confirm:$false + } +} + +Function Check-TrustAuthorityClusterHealth { + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustAuthorityCluster] $TrustAuthorityCluster + ) + + Begin { + $bluevc = GetViServer -clusterUid $TrustAuthorityCluster.Uid + } + + Process { + Write-Host "Checking the healthy status of TrustAuthorityCluster $($TrustAuthorityCluster.Name)..." + $TrustAuthorityCluster = Get-TrustAuthorityCluster -Name $TrustAuthorityCluster.Name -Server $bluevc + # Check the cluster is enabled + if ($TrustAuthorityCluster.State -ne 'Enabled') { + Throw "The given TrustAuthorityCluster $($TrustAuthorityCluster.Name) hasn't been configured yet!" + } + + # Check services healthy + $status = Get-TrustAuthorityServicesStatus -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + + if ($status.AttestationServiceStatus.Health -ne 'Ok') { + Throw "The AttestationServiceStatus is not healthy, please fix it first!" + } + + if ($status.KeyProviderServiceStatus.Health -ne 'Ok') { + Throw "The KeyProviderServiceStatus is not healthy, please fix it first!" + } + + # Check TrustAuthorityPrincipal's healthy + $principals = Get-TrustAuthorityPrincipal -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + + foreach ($p in $principals) { + if ($p.Health -ne 'Ok') { + Throw "The TrustAuthorityPrincipal $($p.Name) is not healthy, please fix it first!" + } + } + + # Check TrustAuthorityKeyProvider's healthy + $kp = Get-TrustAuthorityKeyProvider -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + foreach ($k in $kp) { + if ($k.Status.Health -ne 'Ok') { + Throw "TrustAuthorityKeyProvider $($k.Name) is not healthy, please fix it first!" + } + + foreach ($status in $k.Status.ServerStatus) { + if ($status.Health -ne 'Ok') { + Throw "The ServerStatus $($status.Name) in TrustAuthorityKeyProvider $($k.Name) is not healthy, please fix it first!" + } + } + } + + # Check tpm2 settings + $tpm2Setting = Get-TrustAuthorityTpm2AttestationSettings -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + if ($tpm2Setting.Health -ne 'Ok') { + Throw "TrustAuthorityTpm2AttestationSettings is not healthy, please fix it first!" + } + + # Check tpm2Ek healthy + $tpm2Eks = Get-TrustAuthorityTpm2EndorsementKey -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + if ($tpm2Eks -ne $null) { + foreach ($ek in $tpm2Eks) { + if ($ek.Health -ne 'Ok') { + Throw "TrustAuthorityTpm2EndorsementKey $($ek.Name) is not healthy, please fix it first!" + } + } + } + + # Check tpm2CA healthy + $tpm2cas = Get-TrustAuthorityTpm2CACertificate -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + if ($tpm2cas -ne $null) { + foreach ($ca in $tpm2cas) { + if ($ca.Health -ne 'Ok') { + Throw "TrustAuthorityTpm2CACertificate $($ca.Name) is not healthy, please fix it first!" + } + } + } + + # Check BaseImage healthy + $baseImages = Get-TrustAuthorityVMHostBaseImage -TrustAuthorityCluster $TrustAuthorityCluster -Server $bluevc + if ($baseImages -ne $null) { + foreach ($img in $baseImages) { + if ($img.Health -ne 'Ok') { + Throw "TrustAuthorityVMHostBaseImage $($img.Name) is not healthy, please fix it first!" + } + } + } + } +} + +Function Check-TrustedClusterSettings { + [CmdLetBinding()] + + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [VMware.VimAutomation.Security.Types.V1.TrustedInfrastructure.TrustedCluster] $TrustedCluster + ) + + Begin { + $greenvc = GetViServer -clusterUid $TrustedCluster.Uid + Write-Host "Checking the settings of TrustedCluster $($TrustedCluster.Name)..." + } + + Process { + $TrustedCluster = Get-TrustedCluster $TrustedCluster.Name -Server $greenvc + + if (!$TrustedCluster.AttestationServiceInfo -and !$TrustedCluster.KeyProviderServiceInfo) { + Throw "The cluster $($TrustedCluster.Name) hasn't been configured yet, you can add the host directly." + } + } +} + +Function GetViServer { + Param ( + [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] + [string] $clusterUid + ) + + Process { + $server = $global:DefaultVIServers | Where-Object { [VMware.VimAutomation.Sdk.Types.V1.DistinguishedName]::GetConnectionDn($clusterUid) -eq $_.Id} + + return $server + } +} + +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. + #> + + Param ( + [Parameter(Mandatory=$True)] + [ValidateNotNullOrEmpty()] + [String] $VIServer + ) + + Process { + if ([String]::IsNullOrWhiteSpace($VIServer)) { + Throw "Please provide a valid vCenter Server!" + } + + $SI = Get-View Serviceinstance -Server $VIServer + $VIType = $SI.Content.About.ApiType + + if ($VIType -ne "VirtualCenter") { + Throw "Operation requires vCenter Server!" + } + } +} + +Function ConvertFrom-X509Chain { + Param ( + [Parameter(Mandatory=$True)] + [System.Security.Cryptography.X509Certificates.X509Chain] $CertChain + ) + + Process { + $certStr = $null + foreach ($c in $($CertChain.ChainElements)) { + if ($certStr -eq $null) { + $certStr = [System.Convert]::ToBase64String($($c.Certificate.GetRawCertData())) + } else { + $certStr = $certStr, [System.Convert]::ToBase64String($($c.Certificate.GetRawCertData())) + } + } + + return $certStr + } +} + +Function ConvertTo-X509Chain { + Param ( + [Parameter(Mandatory=$True)] + [System.Array] $certString + ) + + Process { + $chain = new-object System.Security.Cryptography.X509Certificates.X509Chain + if ($certString.Length -gt 0) { + for ($i = 0; $i -lt $certString.Length - 1; $i++ ) { + $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 + $cert.Import([System.Text.Encoding]::Default.GetBytes($certString[$i].replace("\n", [Environment]::NewLine))) + $silent = $chain.ChainPolicy.ExtraStore.Add($cert) + } + } + + $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 + $cert.Import([System.Text.Encoding]::Default.GetBytes($certString[-1].replace("\n", [Environment]::NewLine))) + $silent = $chain.Build($cert) + + return $chain + } +} + + +Export-ModuleMember Add-TrustAuthorityVMHost, Add-TrustedVMHost + +# SIG # Begin signature block +# MIIi9AYJKoZIhvcNAQcCoIIi5TCCIuECAQExDzANBglghkgBZQMEAgEFADB5Bgor +# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG +# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCwMEx3Ndpn/K5N +# T9PigHlgbfEAXX20xwVouOnKKMD48KCCD8swggTMMIIDtKADAgECAhBdqtQcwalQ +# C13tonk09GI7MA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQK +# ExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3Qg +# TmV0d29yazEwMC4GA1UEAxMnU3ltYW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBT +# aWduaW5nIENBMB4XDTE4MDgxMzAwMDAwMFoXDTIxMDkxMTIzNTk1OVowZDELMAkG +# A1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEjAQBgNVBAcMCVBhbG8gQWx0 +# bzEVMBMGA1UECgwMVk13YXJlLCBJbmMuMRUwEwYDVQQDDAxWTXdhcmUsIEluYy4w +# ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCuswYfqnKot0mNu9VhCCCR +# vVcCrxoSdB6G30MlukAVxgQ8qTyJwr7IVBJXEKJYpzv63/iDYiNAY3MOW+Pb4qGI +# bNpafqxc2WLW17vtQO3QZwscIVRapLV1xFpwuxJ4LYdsxHPZaGq9rOPBOKqTP7Jy +# KQxE/1ysjzacA4NXHORf2iars70VpZRksBzkniDmurvwCkjtof+5krxXd9XSDEFZ +# 9oxeUGUOBCvSLwOOuBkWPlvCnzEqMUeSoXJavl1QSJvUOOQeoKUHRycc54S6Lern +# 2ddmdUDPwjD2cQ3PL8cgVqTsjRGDrCgOT7GwShW3EsRsOwc7o5nsiqg/x7ZmFpSJ +# AgMBAAGjggFdMIIBWTAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDArBgNVHR8E +# JDAiMCCgHqAchhpodHRwOi8vc3Yuc3ltY2IuY29tL3N2LmNybDBhBgNVHSAEWjBY +# MFYGBmeBDAEEATBMMCMGCCsGAQUFBwIBFhdodHRwczovL2Quc3ltY2IuY29tL2Nw +# czAlBggrBgEFBQcCAjAZDBdodHRwczovL2Quc3ltY2IuY29tL3JwYTATBgNVHSUE +# DDAKBggrBgEFBQcDAzBXBggrBgEFBQcBAQRLMEkwHwYIKwYBBQUHMAGGE2h0dHA6 +# Ly9zdi5zeW1jZC5jb20wJgYIKwYBBQUHMAKGGmh0dHA6Ly9zdi5zeW1jYi5jb20v +# c3YuY3J0MB8GA1UdIwQYMBaAFJY7U/B5M5evfYPvLivMyreGHnJmMB0GA1UdDgQW +# BBTVp9RQKpAUKYYLZ70Ta983qBUJ1TANBgkqhkiG9w0BAQsFAAOCAQEAlnsx3io+ +# W/9i0QtDDhosvG+zTubTNCPtyYpv59Nhi81M0GbGOPNO3kVavCpBA11Enf0CZuEq +# f/ctbzYlMRONwQtGZ0GexfD/RhaORSKib/ACt70siKYBHyTL1jmHfIfi2yajKkMx +# UrPM9nHjKeagXTCGthD/kYW6o7YKKcD7kQUyBhofimeSgumQlm12KSmkW0cHwSSX +# TUNWtshVz+74EcnZtGFI6bwYmhvnTp05hWJ8EU2Y1LdBwgTaRTxlSDP9JK+e63vm +# SXElMqnn1DDXABT5RW8lNt6g9P09a2J8p63JGgwMBhmnatw7yrMm5EAo+K6gVliJ +# LUMlTW3O09MbDTCCBVkwggRBoAMCAQICED141/l2SWCyYX308B7KhiowDQYJKoZI +# hvcNAQELBQAwgcoxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j +# LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazE6MDgGA1UECxMxKGMp +# IDIwMDYgVmVyaVNpZ24sIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTFF +# MEMGA1UEAxM8VmVyaVNpZ24gQ2xhc3MgMyBQdWJsaWMgUHJpbWFyeSBDZXJ0aWZp +# Y2F0aW9uIEF1dGhvcml0eSAtIEc1MB4XDTEzMTIxMDAwMDAwMFoXDTIzMTIwOTIz +# NTk1OVowfzELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0 +# aW9uMR8wHQYDVQQLExZTeW1hbnRlYyBUcnVzdCBOZXR3b3JrMTAwLgYDVQQDEydT +# eW1hbnRlYyBDbGFzcyAzIFNIQTI1NiBDb2RlIFNpZ25pbmcgQ0EwggEiMA0GCSqG +# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCXgx4AFq8ssdIIxNdok1FgHnH24ke021hN +# I2JqtL9aG1H3ow0Yd2i72DarLyFQ2p7z518nTgvCl8gJcJOp2lwNTqQNkaC07BTO +# kXJULs6j20TpUhs/QTzKSuSqwOg5q1PMIdDMz3+b5sLMWGqCFe49Ns8cxZcHJI7x +# e74xLT1u3LWZQp9LYZVfHHDuF33bi+VhiXjHaBuvEXgamK7EVUdT2bMy1qEORkDF +# l5KK0VOnmVuFNVfT6pNiYSAKxzB3JBFNYoO2untogjHuZcrf+dWNsjXcjCtvanJc +# YISc8gyUXsBWUgBIzNP4pX3eL9cT5DiohNVGuBOGwhud6lo43ZvbAgMBAAGjggGD +# MIIBfzAvBggrBgEFBQcBAQQjMCEwHwYIKwYBBQUHMAGGE2h0dHA6Ly9zMi5zeW1j +# Yi5jb20wEgYDVR0TAQH/BAgwBgEB/wIBADBsBgNVHSAEZTBjMGEGC2CGSAGG+EUB +# BxcDMFIwJgYIKwYBBQUHAgEWGmh0dHA6Ly93d3cuc3ltYXV0aC5jb20vY3BzMCgG +# CCsGAQUFBwICMBwaGmh0dHA6Ly93d3cuc3ltYXV0aC5jb20vcnBhMDAGA1UdHwQp +# MCcwJaAjoCGGH2h0dHA6Ly9zMS5zeW1jYi5jb20vcGNhMy1nNS5jcmwwHQYDVR0l +# BBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMDMA4GA1UdDwEB/wQEAwIBBjApBgNVHREE +# IjAgpB4wHDEaMBgGA1UEAxMRU3ltYW50ZWNQS0ktMS01NjcwHQYDVR0OBBYEFJY7 +# U/B5M5evfYPvLivMyreGHnJmMB8GA1UdIwQYMBaAFH/TZafC3ey78DAJ80M5+gKv +# MzEzMA0GCSqGSIb3DQEBCwUAA4IBAQAThRoeaak396C9pK9+HWFT/p2MXgymdR54 +# FyPd/ewaA1U5+3GVx2Vap44w0kRaYdtwb9ohBcIuc7pJ8dGT/l3JzV4D4ImeP3Qe +# 1/c4i6nWz7s1LzNYqJJW0chNO4LmeYQW/CiwsUfzHaI+7ofZpn+kVqU/rYQuKd58 +# vKiqoz0EAeq6k6IOUCIpF0yH5DoRX9akJYmbBWsvtMkBTCd7C6wZBSKgYBU/2sn7 +# TUyP+3Jnd/0nlMe6NQ6ISf6N/SivShK9DbOXBd5EDBX6NisD3MFQAfGhEV0U5eK9 +# J0tUviuEXg+mw3QFCu+Xw4kisR93873NQ9TxTKk/tYuEr2Ty0BQhMIIFmjCCA4Kg +# AwIBAgIKYRmT5AAAAAAAHDANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJVUzET +# MBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMV +# TWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3NvZnQgQ29kZSBW +# ZXJpZmljYXRpb24gUm9vdDAeFw0xMTAyMjIxOTI1MTdaFw0yMTAyMjIxOTM1MTda +# MIHKMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNV +# BAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA2IFZl +# cmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMT +# PFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBB +# dXRob3JpdHkgLSBHNTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8k +# CAgpejWeYAyq50s7Ttx8vDxFHLsr4P4pAvlXCKNkhRUn9fGtyDGJXSLoKqqmQrOP +# +LlVt7G3S7P+j34HV+zvQ9tmYhVhz2ANpNje+ODDYgg9VBPrScpZVIUm5SuPG5/r +# 9aGRwjNJ2ENjalJL0o/ocFFN0Ylpe8dw9rPcEnTbe11LVtOWvxV3obD0oiXyrxyS +# Zxjl9AYE75C55ADk3Tq1Gf8CuvQ87uCL6zeL7PTXrPL28D2v3XWRMxkdHEDLdCQZ +# IZPZFP6sKlLHj9UESeSNY0eIPGmDy/5HvSt+T8WVrg6d1NFDwGdz4xQIfuU/n3O4 +# MwrPXT80h5aK7lPoJRUCAwEAAaOByzCByDARBgNVHSAECjAIMAYGBFUdIAAwDwYD +# VR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAYYwHQYDVR0OBBYEFH/TZafC3ey78DAJ +# 80M5+gKvMzEzMB8GA1UdIwQYMBaAFGL7CiFbf0NuEdoJVFBr9dKWcfGeMFUGA1Ud +# HwROMEwwSqBIoEaGRGh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3By +# b2R1Y3RzL01pY3Jvc29mdENvZGVWZXJpZlJvb3QuY3JsMA0GCSqGSIb3DQEBBQUA +# A4ICAQCBKoIWjDRnK+UD6zR7jKKjUIr0VYbxHoyOrn3uAxnOcpUYSK1iEf0g/T9H +# BgFa4uBvjBUsTjxqUGwLNqPPeg2cQrxc+BnVYONp5uIjQWeMaIN2K4+Toyq1f75Z +# +6nJsiaPyqLzghuYPpGVJ5eGYe5bXQdrzYao4mWAqOIV4rK+IwVqugzzR5NNrKSM +# B3k5wGESOgUNiaPsn1eJhPvsynxHZhSR2LYPGV3muEqsvEfIcUOW5jIgpdx3hv08 +# 44tx23ubA/y3HTJk6xZSoEOj+i6tWZJOfMfyM0JIOFE6fDjHGyQiKEAeGkYfF9sY +# 9/AnNWy4Y9nNuWRdK6Ve78YptPLH+CHMBLpX/QG2q8Zn+efTmX/09SL6cvX9/zoc +# Qjqh+YAYpe6NHNRmnkUB/qru//sXjzD38c0pxZ3stdVJAD2FuMu7kzonaknAMK5m +# yfcjKDJ2+aSDVshIzlqWqqDMDMR/tI6Xr23jVCfDn4bA1uRzCJcF29BUYl4DSMLV +# n3+nZozQnbBP1NOYX0t6yX+yKVLQEoDHD1S2HmfNxqBsEQOE00h15yr+sDtuCjqm +# a3aZBaPxd2hhMxRHBvxTf1K9khRcSiRqZ4yvjZCq0PZ5IRuTJnzDzh69iDiSrkXG +# GWpJULMF+K5ZN4pqJQOUsVmBUOi6g4C3IzX0drlnHVkYrSCNlDGCEn8wghJ7AgEB +# MIGTMH8xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlv +# bjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEwMC4GA1UEAxMnU3lt +# YW50ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBAhBdqtQcwalQC13t +# onk09GI7MA0GCWCGSAFlAwQCAQUAoIGWMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3 +# AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCoGCisGAQQBgjcCAQwx +# HDAaoRiAFmh0dHA6Ly93d3cudm13YXJlLmNvbS8wLwYJKoZIhvcNAQkEMSIEIL6r +# SvvCSJpAoQz4YvtfQH11/WevM1ULBbGfNUE3j37RMA0GCSqGSIb3DQEBAQUABIIB +# AKUHXKwZcvP2g8/l7dqWyaG7h4q/yJDxaWpk9r1mnUSw1MBR+0AOCm1mquTlpFVH +# ZD1KMQWtu1rJDz5A7XAm8/n6LpyqCCHcgMm+hiEjA8r02oTA8vMFch3OR6Z1/aad +# tOBkeln18M9kVkQ//uociG89A2LkfE35UKAhnDVcOBNlU0g43n9vSgakNdOOc0ZI +# VC2FD/tn9QPJXtcZ0LAFrCPuiIya+gvQ1aQCALUYi+aLuARNN01KBMRFG9za/JwX +# L6rwInitQt/BRNDINiuuTI96xBEMq3JjzW9AE8jF1rVqr1ISBgf8ZZUHdnNHiE91 +# HxLh4zvDq7SEh2ne6UhOJg6hghAjMIIQHwYKKwYBBAGCNwMDATGCEA8wghALBgkq +# hkiG9w0BBwKggg/8MIIP+AIBAzEPMA0GCWCGSAFlAwQCAQUAMIHmBgsqhkiG9w0B +# CRABBKCB1gSB0zCB0AIBAQYJKwYBBAGgMgIDMDEwDQYJYIZIAWUDBAIBBQAEIII1 +# T46qC5Scv1JNpvu1aNNVzRq4lB1M9EZlbgeSsNYJAg4BbKiJKXgAAAAAAKUUzBgT +# MjAyMDA0MDIxMDI5MTguNjc5WjADAgEBoGOkYTBfMQswCQYDVQQGEwJKUDEcMBoG +# A1UEChMTR01PIEdsb2JhbFNpZ24gSy5LLjEyMDAGA1UEAxMpR2xvYmFsU2lnbiBU +# U0EgZm9yIEFkdmFuY2VkIC0gRzMgLSAwMDMtMDGgggxqMIIE6jCCA9KgAwIBAgIM +# M5Agd2HEJt2UUAMNMA0GCSqGSIb3DQEBCwUAMFsxCzAJBgNVBAYTAkJFMRkwFwYD +# VQQKExBHbG9iYWxTaWduIG52LXNhMTEwLwYDVQQDEyhHbG9iYWxTaWduIFRpbWVz +# dGFtcGluZyBDQSAtIFNIQTI1NiAtIEcyMB4XDTE4MDYxNDEwMDAwMFoXDTI5MDMx +# ODEwMDAwMFowXzELMAkGA1UEBhMCSlAxHDAaBgNVBAoTE0dNTyBHbG9iYWxTaWdu +# IEsuSy4xMjAwBgNVBAMTKUdsb2JhbFNpZ24gVFNBIGZvciBBZHZhbmNlZCAtIEcz +# IC0gMDAzLTAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv3Gj+IDO +# E5Be8KfdP9KY8kE6Sdp/WC+ePDoBE8ptNJlbDCccROdW4wkv9W+rTr4nYmbGuLKH +# x2W+xsBeqT6u+yR0iyv4aARkhqo64qohj/rxnbkYMF6afAf1O3Uu2gklGav+c+lx +# neyq9j4ShYEUJPjmPpnfrvO5i9UmywSommFW7yhwqEtqKyVq5aA2ny25mofcdA4f +# QqBBOpYHDst7MtUBC1ORfVY0T7S8sHRHnKp6bF/kjlGfk5BhAz6PX0FBUHg5LRIS +# 3OvqADCyP+FtE7d1SBVrTg7Rl+NO25bZ0WKvCEHPIg/o3c7Y6pNWbtM6j2dKaki6 +# /GHlbFmzEi0CgQIDAQABo4IBqDCCAaQwDgYDVR0PAQH/BAQDAgeAMEwGA1UdIARF +# MEMwQQYJKwYBBAGgMgEeMDQwMgYIKwYBBQUHAgEWJmh0dHBzOi8vd3d3Lmdsb2Jh +# bHNpZ24uY29tL3JlcG9zaXRvcnkvMAkGA1UdEwQCMAAwFgYDVR0lAQH/BAwwCgYI +# KwYBBQUHAwgwRgYDVR0fBD8wPTA7oDmgN4Y1aHR0cDovL2NybC5nbG9iYWxzaWdu +# LmNvbS9ncy9nc3RpbWVzdGFtcGluZ3NoYTJnMi5jcmwwgZgGCCsGAQUFBwEBBIGL +# MIGIMEgGCCsGAQUFBzAChjxodHRwOi8vc2VjdXJlLmdsb2JhbHNpZ24uY29tL2Nh +# Y2VydC9nc3RpbWVzdGFtcGluZ3NoYTJnMi5jcnQwPAYIKwYBBQUHMAGGMGh0dHA6 +# Ly9vY3NwMi5nbG9iYWxzaWduLmNvbS9nc3RpbWVzdGFtcGluZ3NoYTJnMjAdBgNV +# HQ4EFgQUeaezg3HWs0B2IOZ0Crf39+bd3XQwHwYDVR0jBBgwFoAUkiGnSpVdZLCb +# tB7mADdH5p1BK0wwDQYJKoZIhvcNAQELBQADggEBAIc0fm43ZxsIEQJttimYchTL +# SH7IyY8viQ2vD/IsIZBuO7ccAaqBaMQQI0v4CeOrX+pFps4O/qSA6WtqDAD5yoYQ +# DD7/HxrpHOUil2TZrOnj6NpTYGMLt45P3NUh9J3eE2o4NeVs4yZM29Z0Z0W5TwTE +# WAgam2ZFPSQaGpJXyV8oR3hn21zKrQvotw/RthYyNCIENnJM73umvLauBMDZeKCI +# yIZrGNqWjStuIlzLf70XvZ63toZNgxBNsDKy4BOgy2DihHUU6SG9EKKktgjPOw0p +# WVmp08NMDX9CzIgUtELlugTVmEqkjQc9SR94bWVtYL38zlnrLOnFqtqt7taTrBUw +# ggQVMIIC/aADAgECAgsEAAAAAAExicZQBDANBgkqhkiG9w0BAQsFADBMMSAwHgYD +# VQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2ln +# bjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xMTA4MDIxMDAwMDBaFw0yOTAzMjkx +# MDAwMDBaMFsxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNh +# MTEwLwYDVQQDEyhHbG9iYWxTaWduIFRpbWVzdGFtcGluZyBDQSAtIFNIQTI1NiAt +# IEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqpuOw6sRUSUBtpaU +# 4k/YwQj2RiPZRcWVl1urGr/SbFfJMwYfoA/GPH5TSHq/nYeer+7DjEfhQuzj46FK +# bAwXxKbBuc1b8R5EiY7+C94hWBPuTcjFZwscsrPxNHaRossHbTfFoEcmAhWkkJGp +# eZ7X61edK3wi2BTX8QceeCI2a3d5r6/5f45O4bUIMf3q7UtxYowj8QM5j0R5tnYD +# V56tLwhG3NKMvPSOdM7IaGlRdhGLD10kWxlUPSbMQI2CJxtZIH1Z9pOAjvgqOP1r +# oEBlH1d2zFuOBE8sqNuEUBNPxtyLufjdaUyI65x7MCb8eli7WbwUcpKBV7d2ydiA +# CoBuCQIDAQABo4HoMIHlMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/ +# AgEAMB0GA1UdDgQWBBSSIadKlV1ksJu0HuYAN0fmnUErTDBHBgNVHSAEQDA+MDwG +# BFUdIAAwNDAyBggrBgEFBQcCARYmaHR0cHM6Ly93d3cuZ2xvYmFsc2lnbi5jb20v +# cmVwb3NpdG9yeS8wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz +# aWduLm5ldC9yb290LXIzLmNybDAfBgNVHSMEGDAWgBSP8Et/qC5FJK5NUPpjmove +# 4t0bvDANBgkqhkiG9w0BAQsFAAOCAQEABFaCSnzQzsm/NmbRvjWek2yX6AbOMRhZ +# +WxBX4AuwEIluBjH/NSxN8RooM8oagN0S2OXhXdhO9cv4/W9M6KSfREfnops7yyw +# 9GKNNnPRFjbxvF7stICYePzSdnno4SGU4B/EouGqZ9uznHPlQCLPOc7b5neVp7uy +# y/YZhp2fyNSYBbJxb051rvE9ZGo7Xk5GpipdCJLxo/MddL9iDSOMXCo4ldLA1c3P +# iNofKLW6gWlkKrWmotVzr9xG2wSukdduxZi61EfEVnSAR3hYjL7vK/3sbL/RlPe/ +# UOB74JD9IBh4GCJdCC6MHKCX8x2ZfaOdkdMGRE4EbnocIOM28LZQuTCCA18wggJH +# oAMCAQICCwQAAAAAASFYUwiiMA0GCSqGSIb3DQEBCwUAMEwxIDAeBgNVBAsTF0ds +# b2JhbFNpZ24gUm9vdCBDQSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYD +# VQQDEwpHbG9iYWxTaWduMB4XDTA5MDMxODEwMDAwMFoXDTI5MDMxODEwMDAwMFow +# TDEgMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkds +# b2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wggEiMA0GCSqGSIb3DQEBAQUA +# A4IBDwAwggEKAoIBAQDMJXaQeQZ4Ihb1wIO2hMoonv0FdhHFrYhy/EYCQ8eyip0E +# XyTLLkvhYIJG4VKrDIFHcGzdZNHr9SyjD4I9DCuul9e2FIYQebs7E4B3jAjhSdJq +# Yi8fXvqWaN+JJ5U4nwbXPsnLJlkNc96wyOkmDoMVxu9bi9IEYMpJpij2aTv2y8go +# keWdimFXN6x0FNx04Druci8unPvQu7/1PQDhBjPogiuuU6Y6FnOM3UEOIDrAtKeh +# 6bJPkC4yYOlXy7kEkmho5TgmYHWyn3f/kRTvriBJ/K1AFUjRAjFhGV64l++td7dk +# mnq/X8ET75ti+w1s4FRpFqkD2m7pg5NxdsZphYIXAgMBAAGjQjBAMA4GA1UdDwEB +# /wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSP8Et/qC5FJK5NUPpj +# move4t0bvDANBgkqhkiG9w0BAQsFAAOCAQEAS0DbwFCq/sgM7/eWVEVJu5YACUGs +# sxOGhigHM8pr5nS5ugAtrqQK0/Xx8Q+Kv3NnSoPHRHt44K9ubG8DKY4zOUXDjuS5 +# V2yq/BKW7FPGLeQkbLmUY/vcU2hnVj6DuM81IcPJaP7O2sJTqsyQiunwXUaMld16 +# WCgaLx3ezQA3QY/tRG3XUyiXfvNnBB4V14qWtNPeTCekTBtzc3b0F5nCH3oO4y0I +# rQocLP88q1UOD5F+NuvDV0m+4S4tfGCLw0FREyOdzvcya5QBqJnnLDMfOjsl0oZA +# zjsshnjJYS8Uuu7bVW/fhO4FCU29KNhyztNiUGUe65KXgzHZs7XKR1g/XzGCAokw +# ggKFAgEBMGswWzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt +# c2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gU0hBMjU2 +# IC0gRzICDDOQIHdhxCbdlFADDTANBglghkgBZQMEAgEFAKCB8DAaBgkqhkiG9w0B +# CQMxDQYLKoZIhvcNAQkQAQQwLwYJKoZIhvcNAQkEMSIEIA4jXM836yg3wGdHIpch +# UiliyMiFAI2ifPJZqDcXgJ1ZMIGgBgsqhkiG9w0BCRACDDGBkDCBjTCBijCBhwQU +# rmsC2QsljAmRsRYSid62aVY5HW8wbzBfpF0wWzELMAkGA1UEBhMCQkUxGTAXBgNV +# BAoTEEdsb2JhbFNpZ24gbnYtc2ExMTAvBgNVBAMTKEdsb2JhbFNpZ24gVGltZXN0 +# YW1waW5nIENBIC0gU0hBMjU2IC0gRzICDDOQIHdhxCbdlFADDTANBgkqhkiG9w0B +# AQEFAASCAQB89B/P9T38HdPsMvwHePaxCuxvcVOb0tWYORy4h/6961Hr8+uJi3g8 +# oPQl5tMvsUObcO+hMG8YyXfRpQRr5YrHeWpUGdQzMMHb+gC540P+r3jm6iWoKtpR +# 1WGSnQQUqKaB7a4wZtQoizzSm9a7hB4JEcDtb2Qh2jmSr4yhMx7XmFMLo7NVlEnW +# lS6kTYR9kE4qTagRIOZW5iIUjcAaVn/uhNAOZUjatErU8c/a8vJ7TxtPj4YSaK0J +# IeC+HeUYNRrjwtSgmnU+j/xg1Jo9zUoCGJHBIEJ9iwzgCeRLJuqHKUZiAGBZm09F +# EzycbyZmxfS5ui4MX5wSMdO1ETnvkbRc +# SIG # End signature block From 500e4022e7cf2a05ff7e984bf3331afbaeed061d Mon Sep 17 00:00:00 2001 From: Alan Renouf Date: Wed, 15 Apr 2020 14:09:13 -0700 Subject: [PATCH 175/175] Updated Workspace One Access module to include Get-UEMConfig and Remove-UEMConfig --- .../VMware.WorkspaceOneAccess.psd1 | 4 +- .../VMware.WorkspaceOneAccess.psm1 | 115 ++++++++++++++++++ 2 files changed, 117 insertions(+), 2 deletions(-) diff --git a/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 index b25bf20..d226ed5 100644 --- a/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 +++ b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psd1 @@ -12,7 +12,7 @@ RootModule = 'VMware.WorkspaceOneAccess.psm1' # Version number of this module. -ModuleVersion = '1.0.0' +ModuleVersion = '1.0.1' # Supported PSEditions # CompatiblePSEditions = @() @@ -37,7 +37,7 @@ PowerShellVersion = '6.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = 'Connect-WorkspaceOneAccess','Get-WSDirectory','Get-WSIdentityProvider','Get-WSOrgNetwork','New-WS3rdPartyIdentityProvider','New-WSJitDirectory','Remove-WS3rdPartyIdentityProvider','Remove-WSDirectory' +FunctionsToExport = 'Connect-WorkspaceOneAccess','Get-WSDirectory','Get-WSIdentityProvider','Get-WSOrgNetwork','New-WS3rdPartyIdentityProvider','New-WSJitDirectory','Remove-WS3rdPartyIdentityProvider','Remove-WSDirectory', "Get-UEMConfig", "Remove-UEMConfig" # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() diff --git a/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 index 9e2e978..642e14f 100644 --- a/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 +++ b/Modules/VMware.WorkspaceOneAccess/VMware.WorkspaceOneAccess.psm1 @@ -569,4 +569,119 @@ Function Remove-WS3rdPartyIdentityProvider { } else { Write-Host "`nUnable to find Identity Provider $Name" } +} + +Function Get-UEMConfig { +<# + .NOTES + =========================================================================== + Created by: Alan Renouf + Date: 04/15/2020 + Organization: VMware + Blog: http://virtu-al.net + Twitter: @alanrenouf + =========================================================================== + + .SYNOPSIS + Retrieves UEM Configuration from Workspace One Access + .DESCRIPTION + This cmdlet retrieves the UEM Configuration from Workspace One Access + .EXAMPLE + Get-UEMConfig + .EXAMPLE + Get-UEMConfig +#> + Param ( + [Switch]$Troubleshoot + ) + + $directoryHeaders = @{ + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $directoryUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/tenants/tenant/airwatchoptin/config" + $method = "GET" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$directoryUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in retrieving UEM Configuration" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + $config = ([System.Text.Encoding]::ASCII.GetString($results.Content) | ConvertFrom-Json) + $config + } +} + +Function Remove-UEMConfig { +<# + .NOTES + =========================================================================== + Created by: Alan Renouf + Date: 04/15/2020 + Organization: VMware + Blog: http://virtu-al.net + Twitter: @alanrenouf + =========================================================================== + + .SYNOPSIS + Removes the UEM Configuration from Workspace One Access + .DESCRIPTION + This cmdlet removes the UEM Configuration from Workspace One Access, there can only be one configuration. + .EXAMPLE + Remove-UEMConfig + .EXAMPLE + Remove-UEMConfig +#> + Param ( + [Switch]$Troubleshoot + ) + + $directoryHeaders = @{ + "Authorization"=$global:workspaceOneAccessConnection.headers.Authorization; + } + + $directoryUrl = $global:workspaceOneAccessConnection.Server + "/SAAS/jersey/manager/api/tenants/tenant/airwatchoptin/config" + $method = "DELETE" + + if($Troubleshoot) { + Write-Host -ForegroundColor cyan "`n[DEBUG] - $method`n$directoryUrl`n" + } + + try { + if($PSVersionTable.PSEdition -eq "Core") { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders -SkipCertificateCheck + } else { + $results = Invoke-Webrequest -Uri $directoryUrl -Method $method -UseBasicParsing -Headers $directoryHeaders + } + } catch { + if($_.Exception.Response.StatusCode -eq "Unauthorized") { + Write-Host -ForegroundColor Red "`nThe Workspace One session is no longer valid, please re-run the Connect-WorkspaceOne cmdlet to retrieve a new token`n" + break + } else { + Write-Error "Error in deleting UEM Configuration" + Write-Error "`n($_.Exception.Message)`n" + break + } + } + + if($results.StatusCode -eq 200) { + Write-Host "`nSuccessfully deleted UEM Configuration" + } } \ No newline at end of file