diff --git a/module/Include.ps1 b/module/Include.ps1 index 4eff9465..e32d47a7 100644 --- a/module/Include.ps1 +++ b/module/Include.ps1 @@ -99,6 +99,8 @@ $FunctionsToExport = @( 'Get-NsxEdgeStatus', 'Enable-NsxEdgeSsh', 'Disable-NsxEdgeSsh', + 'Enable-NsxEdgeFips', + 'Disable-NsxEdgeFips', 'Set-NsxEdgeNat', 'Get-NsxEdgeNat', 'Get-NsxEdgeNatRule', diff --git a/module/PowerNSX.psm1 b/module/PowerNSX.psm1 index 5a434a65..ce392211 100644 --- a/module/PowerNSX.psm1 +++ b/module/PowerNSX.psm1 @@ -26,32 +26,32 @@ has its own license that is located in the source code of the respective compone #My installer home and valid PNSX branches (releases) (used in Update-Powernsx.) $PNsxUrlBase = "https://raw.githubusercontent.com/vmware/powernsx" -$ValidBranches = @("master","v2", "v3") +$ValidBranches = @("master", "v2", "v3") $Script:AllValidServices = @("AARP", "AH", "ARPATALK", "ATMFATE", "ATMMPOA", - "BPQ", "CUST", "DEC", "DIAG", "DNA_DL", "DNA_RC", "DNA_RT", "ESP", - "FR_ARP", "FTP", "GRE", "ICMP", "IEEE_802_1Q", "IGMP", "IPCOMP", - "IPV4", "IPV6", "IPV6FRAG", "IPV6ICMP", "IPV6NONXT", "IPV6OPTS", - "IPV6ROUTE", "IPX", "L2_OTHERS", "L2TP", "L3_OTHERS", "LAT", "LLC", - "LOOP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", - "NBNS_BROADCAST", "NETBEUI", "ORACLE_TNS", "PPP", "PPP_DISC", - "PPP_SES", "RARP", "RAW_FR", "RSVP", "SCA", "SCTP", "SUN_RPC_TCP", - "SUN_RPC_UDP", "TCP", "UDP", "X25") + "BPQ", "CUST", "DEC", "DIAG", "DNA_DL", "DNA_RC", "DNA_RT", "ESP", + "FR_ARP", "FTP", "GRE", "ICMP", "IEEE_802_1Q", "IGMP", "IPCOMP", + "IPV4", "IPV6", "IPV6FRAG", "IPV6ICMP", "IPV6NONXT", "IPV6OPTS", + "IPV6ROUTE", "IPX", "L2_OTHERS", "L2TP", "L3_OTHERS", "LAT", "LLC", + "LOOP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", + "NBNS_BROADCAST", "NETBEUI", "ORACLE_TNS", "PPP", "PPP_DISC", + "PPP_SES", "RARP", "RAW_FR", "RSVP", "SCA", "SCTP", "SUN_RPC_TCP", + "SUN_RPC_UDP", "TCP", "UDP", "X25") $Script:AllServicesRequiringPort = @( "FTP", "L2_OTHERS", "L3_OTHERS", - "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", - "SUN_RPC_TCP", "SUN_RPC_UDP" ) + "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", + "SUN_RPC_TCP", "SUN_RPC_UDP" ) $script:AllServicesNotRequiringPort = $Script:AllValidServices | Where-Object { $AllServicesRequiringPort -notcontains $_ } $script:AllServicesValidSourcePort = @( "FTP", "MS_RPC_TCP", "MS_RPC_UDP", -"NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", "SUN_RPC_TCP", "SUN_RPC_UDP", -"TCP", "UDP" ) + "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", "SUN_RPC_TCP", "SUN_RPC_UDP", + "TCP", "UDP" ) $Script:AllValidIcmpTypes = @("echo-reply", "destination-unreachable", "source-quench", "redirect", "echo-request", "time-exceeded", "parameter-problem", "timestamp-request", "timestamp-reply", - "address-mask-request", "address-mask-reply","router-solicitation", + "address-mask-request", "address-mask-reply", "router-solicitation", "router-advertisement", "source-host-isolated", "pointer-to-error", "redirect-host", "fragmentation-needed", "bad-length", "destination-network-prohibited", "ttl-zero-transit", @@ -60,7 +60,7 @@ $Script:AllValidIcmpTypes = @("echo-reply", "destination-unreachable", "ttl-zero-reassembly", "port-unreachable", "address-mask-request" ) -set-strictmode -version Latest +Set-StrictMode -Version Latest ######## ######## @@ -106,12 +106,12 @@ Function _init { if ( $script:PNsxPSTarget -eq "Desktop" ) { if ( -not ("TrustAllCertsPolicy" -as [type])) { - add-type $TrustAllCertsPolicy + Add-Type $TrustAllCertsPolicy } } elseif ( $script:PNsxPSTarget -eq "Core") { if ( -not ("InternalHttpClientHandler" -as [type]) ) { - add-type $InternalHttpClientHandler -ReferencedAssemblies System.Net.Http, System.Security.Cryptography.X509Certificates, System.Net.Primitives -WarningAction "SilentlyContinue" + Add-Type $InternalHttpClientHandler -ReferencedAssemblies System.Net.Http, System.Security.Cryptography.X509Certificates, System.Net.Primitives -WarningAction "SilentlyContinue" } } @@ -140,7 +140,7 @@ Function _init { } } "@ - add-type $InternalWebResponse + Add-Type $InternalWebResponse #Custom NSX API exception $InternalNsxApiException = @" @@ -152,7 +152,7 @@ Function _init { public InternalNsxApiException(string message, Exception inner) : base(message, inner) {} } "@ - add-type $InternalNsxApiException -IgnoreWarnings -warningaction "SilentlyContinue" + Add-Type $InternalNsxApiException -IgnoreWarnings -WarningAction "SilentlyContinue" } function Invoke-XpathQuery { @@ -188,16 +188,16 @@ function Invoke-XpathQuery { #> param ( - [Parameter (Mandatory=$true)] - #XPath query method. Supports SelectSingleNode or SelectNodes. - [ValidateSet("SelectSingleNode","SelectNodes")] - [string]$QueryMethod, - [Parameter (Mandatory=$true)] - #XmlDocument or XmlElement node to be queried. - $Node, - [Parameter (Mandatory=$true)] - #Xpath Query. - [string]$query + [Parameter (Mandatory = $true)] + #XPath query method. Supports SelectSingleNode or SelectNodes. + [ValidateSet("SelectSingleNode", "SelectNodes")] + [string]$QueryMethod, + [Parameter (Mandatory = $true)] + #XmlDocument or XmlElement node to be queried. + $Node, + [Parameter (Mandatory = $true)] + #Xpath Query. + [string]$query ) @@ -205,10 +205,10 @@ function Invoke-XpathQuery { #Use the XPath extensions class to perform the query switch ($QueryMethod) { "SelectSingleNode" { - [System.Xml.XmlDocumentXPathExtensions]::SelectSingleNode($node,$query) + [System.Xml.XmlDocumentXPathExtensions]::SelectSingleNode($node, $query) } "SelectNodes" { - [System.Xml.XmlDocumentXPathExtensions]::SelectNodes($node,$query) + [System.Xml.XmlDocumentXPathExtensions]::SelectNodes($node, $query) } } } @@ -234,7 +234,7 @@ function Read-HostWithDefault { ) if ($default) { - $response = read-host -prompt "$Prompt [$Default]" + $response = Read-Host -Prompt "$Prompt [$Default]" if ( $response -eq "" ) { $Default } @@ -243,24 +243,24 @@ function Read-HostWithDefault { } } else { - read-host -prompt $Prompt + Read-Host -Prompt $Prompt } } function ConvertFrom-Bitmask { param ( - [Parameter(Mandatory=$true)] - [ValidateRange(1,32)] - [int]$Bitmask + [Parameter(Mandatory = $true)] + [ValidateRange(1, 32)] + [int]$Bitmask ) [ipaddress]$base = "255.255.255.255" - $invertedmask = [ipaddress]($base.address - [convert]::toint64(([math]::pow(2,(32-$bitmask)) -bxor $base.Address) + 1)) + $invertedmask = [ipaddress]($base.address - [convert]::toint64(([math]::pow(2, (32 - $bitmask)) -bxor $base.Address) + 1)) [ipaddress]$subnetmask = "$(255-$($invertedmask.GetAddressBytes()[3]))." + - "$(255-$($invertedmask.GetAddressBytes()[2]))." + - "$(255-$($invertedmask.GetAddressBytes()[1]))." + - "$(255-$($invertedmask.GetAddressBytes()[0]))" + "$(255-$($invertedmask.GetAddressBytes()[2]))." + + "$(255-$($invertedmask.GetAddressBytes()[1]))." + + "$(255-$($invertedmask.GetAddressBytes()[0]))" $subnetmask } @@ -268,8 +268,8 @@ function ConvertFrom-Bitmask { function ConvertTo-Bitmask { param ( - [Parameter(Mandatory=$true)] - [ipaddress]$subnetmask + [Parameter(Mandatory = $true)] + [ipaddress]$subnetmask ) $bitcount = 0 @@ -282,7 +282,8 @@ function ConvertTo-Bitmask { "255" { if ( $boundaryoctetfound ) { throw "SubnetMask specified is not valid. Specify a valid mask and try again." - } else { + } + else { $bitcount += 8 } } @@ -298,7 +299,7 @@ function ConvertTo-Bitmask { $boundaryoctet = $_ for ( $i = 7; $i -ge 0 ; $i-- ) { - if ( $boundaryoctet -band [math]::pow(2,$i) ) { + if ( $boundaryoctet -band [math]::pow(2, $i) ) { if ( $boundarybitfound) { #Already hit boundary - mask isnt valid. throw "SubnetMask specified is not valid. Specify a valid mask and try again." @@ -319,17 +320,17 @@ function ConvertTo-Bitmask { function Get-NetworkFromHostAddress { - [CmdletBinding(DefaultParameterSetName="mask")] + [CmdletBinding(DefaultParameterSetName = "mask")] param ( - [Parameter(Mandatory=$true,ParameterSetName="cidr")] - [Parameter(Mandatory=$true,ParameterSetName="mask")] - [ipaddress]$Address, - [Parameter(Mandatory=$true,ParameterSetName="mask")] - [ipaddress]$SubnetMask, - [Parameter(Mandatory=$true,ParameterSetName="cidr")] - [ValidateRange(1,32)] - [int]$BitMask + [Parameter(Mandatory = $true, ParameterSetName = "cidr")] + [Parameter(Mandatory = $true, ParameterSetName = "mask")] + [ipaddress]$Address, + [Parameter(Mandatory = $true, ParameterSetName = "mask")] + [ipaddress]$SubnetMask, + [Parameter(Mandatory = $true, ParameterSetName = "cidr")] + [ValidateRange(1, 32)] + [int]$BitMask ) @@ -342,22 +343,22 @@ function Get-NetworkFromHostAddress { $NetAddress += "$($Address.GetAddressBytes()[$i] -band $SubnetMask.GetAddressBytes()[$i])." } - [ipaddress]($NetAddress -replace "\.$","") + [ipaddress]($NetAddress -replace "\.$", "") } function Test-AddressInNetwork { - [CmdletBinding(DefaultParameterSetName="mask")] + [CmdletBinding(DefaultParameterSetName = "mask")] param ( - [Parameter(Mandatory=$true,ParameterSetName="mask")] - [ipaddress]$SubnetMask, - [Parameter(Mandatory=$true,ParameterSetName="cidr")] - [ValidateRange(1,32)] - [int]$Bitmask, - [Parameter(Mandatory=$true)] - [ipaddress]$Network, - [Parameter(Mandatory=$true)] - [ipaddress]$Address + [Parameter(Mandatory = $true, ParameterSetName = "mask")] + [ipaddress]$SubnetMask, + [Parameter(Mandatory = $true, ParameterSetName = "cidr")] + [ValidateRange(1, 32)] + [int]$Bitmask, + [Parameter(Mandatory = $true)] + [ipaddress]$Network, + [Parameter(Mandatory = $true)] + [ipaddress]$Address ) if ( $PsCmdlet.ParameterSetName -eq 'cidr') { @@ -370,15 +371,15 @@ function Get-NetworkRange { #Im well aware that this is very inefficient, but I need it quickly, and CPUs are cheap ;) - [CmdletBinding(DefaultParameterSetName="mask")] + [CmdletBinding(DefaultParameterSetName = "mask")] param ( - [Parameter(Mandatory=$true,ParameterSetName="mask")] - [ipaddress]$SubnetMask, - [Parameter(Mandatory=$true,ParameterSetName="cidr")] - [ValidateRange(1,32)] - [int]$Bitmask, - [Parameter(Mandatory=$true)] - [ipaddress]$Network + [Parameter(Mandatory = $true, ParameterSetName = "mask")] + [ipaddress]$SubnetMask, + [Parameter(Mandatory = $true, ParameterSetName = "cidr")] + [ValidateRange(1, 32)] + [int]$Bitmask, + [Parameter(Mandatory = $true)] + [ipaddress]$Network ) if ( $PsCmdlet.ParameterSetName -eq 'cidr') { @@ -416,7 +417,7 @@ function Get-NetworkRange { } $currentaddress = "$($CurrAddressBytes[0]).$($CurrAddressBytes[1]).$($CurrAddressBytes[2]).$($CurrAddressBytes[3])" - $Range.Add($currentaddress) | out-null + $Range.Add($currentaddress) | Out-Null } while ( Test-AddressInNetwork -network $network -subnetmask $subnetmask -address $currentaddress ) @@ -426,9 +427,9 @@ function Get-NetworkRange { $range.RemoveAt($range.Count - 1 ) [pscustomobject]@{ - "NetworkAddress" = $network + "NetworkAddress" = $network "ValidAddressRange" = $range - "Broadcast" = $BroadCastAddress + "Broadcast" = $BroadCastAddress } } @@ -445,8 +446,8 @@ function Add-XmlElement { #Create an Element and append it to the root [System.XML.XMLElement]$xmlNode = $xmlRoot.OwnerDocument.CreateElement($xmlElementName) [System.XML.XMLNode]$xmlText = $xmlRoot.OwnerDocument.CreateTextNode($xmlElementText) - $xmlNode.AppendChild($xmlText) | out-null - $xmlRoot.AppendChild($xmlNode) | out-null + $xmlNode.AppendChild($xmlText) | Out-Null + $xmlRoot.AppendChild($xmlNode) | Out-Null } function Get-FeatureStatus { @@ -455,12 +456,12 @@ function Get-FeatureStatus { [string]$featurestring, [system.xml.xmlelement[]]$statusxml - ) + ) - [system.xml.xmlelement]$feature = $statusxml | where-object { $_.featureId -eq $featurestring } | select-object -first 1 + [system.xml.xmlelement]$feature = $statusxml | Where-Object { $_.featureId -eq $featurestring } | Select-Object -First 1 [string]$statusstring = $feature.status - $message = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $feature -Query 'message') - if ( $message -and ( $message | get-member -membertype Property -Name '#Text')) { + $message = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $feature -query 'message') + if ( $message -and ( $message | Get-Member -MemberType Property -Name '#Text')) { $statusstring += " ($($message.'#text'))" } $statusstring @@ -469,8 +470,8 @@ function Get-FeatureStatus { function ParseCentralCliResponse { param ( - [Parameter ( Mandatory=$True, Position=1)] - [String]$response + [Parameter ( Mandatory = $True, Position = 1)] + [String]$response ) #Response is straight text unfortunately, so there is no structure. Having a crack at writing a very simple parser though the formatting looks.... challenging... @@ -489,20 +490,20 @@ function ParseCentralCliResponse { #Defined this as variable as the swtich statement does not let me concat strings, which makes for a verrrrry long line... $RegexDFWRule = "^(?#\sinternal\s#\s)?(?rule\s)?(?\d+)\sat\s(?\d+)\s(?in|out|inout)\s" + - "(?protocol|ethertype)\s(?.*?)\sfrom\s(?.*?)\sto\s(?.*?)(?:\sport\s(?.*))?\s" + - "(?accept|reject|drop)(?:\swith\s(?log))?(?:\stag\s(?'.*'))?;" + "(?protocol|ethertype)\s(?.*?)\sfrom\s(?.*?)\sto\s(?.*?)(?:\sport\s(?.*))?\s" + + "(?accept|reject|drop)(?:\swith\s(?log))?(?:\stag\s(?'.*'))?;" foreach ( $line in ($response -split '[\r\n]')) { #Init EntryHash hashtable - $EntryHash= @{} + $EntryHash = @{} switch -regex ($line.trim()) { #C CLI appears to emit some error conditions as ^ Error: "^Error \d+:.*$" { - write-debug "$($MyInvocation.MyCommand.Name) : Matched Error line. $_ " + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Error line. $_ " Throw "CLI command returned an error: ( $_ )" @@ -510,7 +511,7 @@ function ParseCentralCliResponse { "^\s*$" { #Blank line, ignore... - write-debug "$($MyInvocation.MyCommand.Name) : Ignoring blank line: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Ignoring blank line: $_" break } @@ -518,7 +519,7 @@ function ParseCentralCliResponse { "^# Filter rules$" { #Filter line encountered in a ruleset list, ignore... if ( $MatchedRuleSet ) { - write-debug "$($MyInvocation.MyCommand.Name) : Ignoring meaningless #Filter rules line in ruleset: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Ignoring meaningless #Filter rules line in ruleset: $_" break } else { @@ -530,11 +531,11 @@ function ParseCentralCliResponse { #Example is the Index in a VNIC list. AFAIK, the index should only be 1-9. but just in case we are matching 1 or more digit... "^(\d+)\.$" { - write-debug "$($MyInvocation.MyCommand.Name) : Matched Index line. Discarding value: $_ " + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Index line. Discarding value: $_ " If ( $MatchedVnicsList ) { #We are building a VNIC list output and this is the first line. #Init the output object to static kv props, but discard the value (we arent outputing as it appears superfluous.) - write-debug "$($MyInvocation.MyCommand.Name) : Processing Vnic List, initialising new Vnic list object" + Write-Debug "$($MyInvocation.MyCommand.Name) : Processing Vnic List, initialising new Vnic list object" $VnicListHash = @{} $VnicListHash += $KeyValHash @@ -548,7 +549,7 @@ function ParseCentralCliResponse { "ruleset\s(\S+) {" { #Set a flag to say we matched a ruleset List, and create the output object. - write-debug "$($MyInvocation.MyCommand.Name) : Matched start of DFW Ruleset output. Processing following lines as DFW Ruleset: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched start of DFW Ruleset output. Processing following lines as DFW Ruleset: $_" $MatchedRuleset = $true $RuleSetName = $matches[1].trim() break @@ -558,7 +559,7 @@ function ParseCentralCliResponse { "addrset\s(\S+) {" { #Set a flag to say we matched a addrset List, and create the output object. - write-debug "$($MyInvocation.MyCommand.Name) : Matched start of DFW Addrset output. Processing following lines as DFW Addrset: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched start of DFW Addrset output. Processing following lines as DFW Addrset: $_" $MatchedAddrSet = $true $AddrSetName = $matches[1].trim() break @@ -575,7 +576,7 @@ function ParseCentralCliResponse { #We are processing a RuleSet, so we need to emit an output object that contains the ruleset name. [PSCustomobject]@{ "AddrSet" = $AddrSetName; - "Type" = $matches.Type; + "Type" = $matches.Type; "Address" = $matches.Address } @@ -591,7 +592,7 @@ function ParseCentralCliResponse { Throw "Error parsing Centralised CLI command output response. Unexpected dfw ruleset entry : $_" } - $Type = switch ( $matches.Type ) { "protocol" { "Layer3" } "ethertype" { "Layer2" }} + $Type = switch ( $matches.Type ) { "protocol" { "Layer3" } "ethertype" { "Layer2" } } $Internal = if ( $matches.ContainsKey("Internal")) { $true } else { $false } $Port = if ( $matches.ContainsKey("Port") ) { $matches.port } else { "Any" } $Log = if ( $matches.ContainsKey("Log") ) { $true } else { $false } @@ -601,19 +602,19 @@ function ParseCentralCliResponse { #We are processing a RuleSet, so we need to emit an output object that contains the ruleset name. [PSCustomobject]@{ - "RuleSet" = $RuleSetName; + "RuleSet" = $RuleSetName; "InternalRule" = $Internal; - "RuleID" = $matches.RuleId; - "Position" = $matches.Position; - "Direction" = $matches.Direction; - "Type" = $Type; - "Service" = $matches.Service; - "Source" = $matches.Source; - "Destination" = $matches.Destination; - "Port" = $Port; - "Action" = $matches.Action; - "Log" = $Log; - "Tag" = $Tag + "RuleID" = $matches.RuleId; + "Position" = $matches.Position; + "Direction" = $matches.Direction; + "Type" = $Type; + "Service" = $matches.Service; + "Source" = $matches.Source; + "Destination" = $matches.Destination; + "Port" = $Port; + "Action" = $matches.Action; + "Log" = $Log; + "Tag" = $Tag } } @@ -622,17 +623,17 @@ function ParseCentralCliResponse { #We are not processing a RuleSet; so we need to emit an output object without a ruleset name. [PSCustomobject]@{ "InternalRule" = $Internal; - "RuleID" = $matches.RuleId; - "Position" = $matches.Position; - "Direction" = $matches.Direction; - "Type" = $Type; - "Service" = $matches.Service; - "Source" = $matches.Source; - "Destination" = $matches.Destination; - "Port" = $Port; - "Action" = $matches.Action; - "Log" = $Log; - "Tag" = $Tag + "RuleID" = $matches.RuleId; + "Position" = $matches.Position; + "Direction" = $matches.Direction; + "Type" = $Type; + "Service" = $matches.Service; + "Source" = $matches.Source; + "Destination" = $matches.Destination; + "Port" = $Port; + "Action" = $matches.Action; + "Log" = $Log; + "Tag" = $Tag } } @@ -645,7 +646,7 @@ function ParseCentralCliResponse { if ( $MatchedRuleset ) { #Clear the flag to say we matched a ruleset List - write-debug "$($MyInvocation.MyCommand.Name) : Matched end of DFW ruleset." + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched end of DFW ruleset." $MatchedRuleset = $false $RuleSetName = "" break @@ -654,7 +655,7 @@ function ParseCentralCliResponse { if ( $MatchedAddrSet ) { #Clear the flag to say we matched an addrset List - write-debug "$($MyInvocation.MyCommand.Name) : Matched end of DFW addrset." + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched end of DFW addrset." $MatchedAddrSet = $false $AddrSetName = "" break @@ -672,26 +673,26 @@ function ParseCentralCliResponse { # - The rest should be self explanatory. "^((?:\S|\s(?!\s))+\s{2,}){1}((?:\S|\s(?!\s))+)$" { - write-debug "$($MyInvocation.MyCommand.Name) : Matched Key Value line (multispace separated): $_ )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Key Value line (multispace separated): $_ )" $key = $matches[1].trim() $value = $matches[2].trim() If ( $MatchedVnicsList ) { #We are building a VNIC list output and this is one of the lines. - write-debug "$($MyInvocation.MyCommand.Name) : Processing Vnic List, Adding $key = $value to current VnicListHash" + Write-Debug "$($MyInvocation.MyCommand.Name) : Processing Vnic List, Adding $key = $value to current VnicListHash" - $VnicListHash.Add($key,$value) + $VnicListHash.Add($key, $value) if ( $key -eq "Filters" ) { #Last line in a VNIC List... - write-debug "$($MyInvocation.MyCommand.Name) : VNIC List : Outputing VNIC List Hash." + Write-Debug "$($MyInvocation.MyCommand.Name) : VNIC List : Outputing VNIC List Hash." [PSCustomobject]$VnicListHash } } else { #Add KV to hash table that we will append to output object - $KeyValHash.Add($key,$value) + $KeyValHash.Add($key, $value) } break } @@ -700,10 +701,10 @@ function ParseCentralCliResponse { #This will match a line with multiple colons in it, not sure if thats an issue yet... "^((?:\S|\s(?!\s))+):((?:\S|\s(?!\s))+)$" { if ( $TableHeaderFound ) { Throw "Error parsing Centralised CLI command output response. Key Value line found after header: ( $_ )" } - write-debug "$($MyInvocation.MyCommand.Name) : Matched Key Value line (Colon Separated) : $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Key Value line (Colon Separated) : $_" #Add KV to hash table that we will append to output object - $KeyValHash.Add($matches[1].trim(),$matches[2].trim()) + $KeyValHash.Add($matches[1].trim(), $matches[2].trim()) break } @@ -713,7 +714,7 @@ function ParseCentralCliResponse { if ( $TableHeaderFound ) { throw "Error parsing Centralised CLI command output response. Matched header line more than once: ( $_ )" } - write-debug "$($MyInvocation.MyCommand.Name) : Matched Table Header line: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Table Header line: $_" $TableHeaderFound = $true $Props = $_.trim() -split "\s{2,}" break @@ -733,7 +734,7 @@ function ParseCentralCliResponse { #Filters nic-4822904-eth0-vmware-sfw.2 #Set a flag to say we matched a VNic List, and create the output object initially with just the KV's matched already. - write-debug "$($MyInvocation.MyCommand.Name) : Matched VNIC List line. Processing remaining lines as Vnic List: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched VNIC List line. Processing remaining lines as Vnic List: $_" $MatchedVnicsList = $true break @@ -744,18 +745,18 @@ function ParseCentralCliResponse { if ( -not $TableHeaderFound ) { throw "Error parsing Centralised CLI command output response. Matched table entry line before header: ( $_ )" } - write-debug "$($MyInvocation.MyCommand.Name) : Matched Table Entry line: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Table Entry line: $_" $Vals = $_.trim() -split "\s{2,}" if ($Vals.Count -ne $Props.Count ) { Throw "Error parsing Centralised CLI command output response. Table entry line contains different value count compared to properties count: ( $_ )" } #Build the output hashtable with the props returned in the table entry line - for ( $i= 0; $i -lt $props.count; $i++ ) { + for ( $i = 0; $i -lt $props.count; $i++ ) { #Ordering is hard, and No. entry is kinda superfluous, so removing it from output (for now) if ( -not ( $props[$i] -eq "No." )) { - $EntryHash[$props[$i].trim()]=$vals[$i].trim() + $EntryHash[$props[$i].trim()] = $vals[$i].trim() } } @@ -782,7 +783,7 @@ function ParseCentralCliResponse { #Some output is just key value, so, if it hasnt been appended to output object already, we will just emit it. #Not sure how this approach will work long term, but it works for show dfw vnic <> - write-debug "$($MyInvocation.MyCommand.Name) : KeyValHash has not been used after all line processing, outputing as is: $_" + Write-Debug "$($MyInvocation.MyCommand.Name) : KeyValHash has not been used after all line processing, outputing as is: $_" [PSCustomObject]$KeyValHash } } @@ -791,8 +792,8 @@ function ConvertTo-NsxApiCriteriaOperator { #Convert the CriteriaOperator to the API AND/OR from the UI/PowerNSX value of ANY/ALL switch ( $args[0] ) { - "any" { "OR"} - "all" { "AND"} + "any" { "OR" } + "all" { "AND" } } } @@ -801,7 +802,7 @@ function ConvertFrom-NsxApiCriteriaOperator { #Convert from the CriteriaOperator of the API AND/OR to the UI/PowerNSX value of ANY/ALL switch ( $args[0] ) { "or" { "ANY" } - "and" { "ALL"} + "and" { "ALL" } } } @@ -850,7 +851,7 @@ function ConvertTo-NsxApiSectionOperation { "top" { "insert_top" } "bottom" { "insert_before_default" } "before" { "insert_before" } - "after" { "insert_after"} + "after" { "insert_after" } default { $args[0] } } } @@ -860,7 +861,7 @@ function ConvertFrom-NsxApiSectionOperation { "insert_top" { "top" } "insert_before_default" { "bottom" } "insert_before" { "before" } - "insert_after" { "after"} + "insert_after" { "after" } default { $args[0] } } } @@ -897,13 +898,14 @@ function ConvertFrom-NsxApiActionType { function ValidateUpdateBranch { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Case sensitive if ( $ValidBranches -Ccontains $argument ) { $true - } else { + } + else { throw "Invalid Branch. Specify one of the valid branches : $($Validbranches -join ", ")" } @@ -912,15 +914,14 @@ function ValidateUpdateBranch { Function ValidateTransportZone { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) - if ( $argument -is [system.xml.xmlelement] ) - { - if ( -not ($argument | get-member -MemberType Property -Name objectId )) { + if ( $argument -is [system.xml.xmlelement] ) { + if ( -not ($argument | Get-Member -MemberType Property -Name objectId )) { throw "Invalid Transport Zone object specified" } - if ( -not ($argument | get-member -MemberType Property -Name objectTypeName )) { + if ( -not ($argument | Get-Member -MemberType Property -Name objectTypeName )) { throw "Invalid Transport Zone object specified" } if ( -not ($argument.objectTypeName -eq "VdnScope")) { @@ -936,27 +937,26 @@ Function ValidateTransportZone { Function ValidateLogicalSwitchOrDistributedPortGroup { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if (-not ( - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] ) -or - ($argument -is [System.Xml.XmlElement] ))) - { + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] ) -or + ($argument -is [System.Xml.XmlElement] ))) { throw "Must specify a distributed port group or a logical switch" } else { #Do we Look like XML describing a Logical Switch if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified does not contain an objectId property. Specify a Distributed PortGroup or Logical Switch object." } - if ( -not ( $argument | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectTypeName -MemberType Properties)) { throw "Object specified does not contain a type property. Specify a Distributed PortGroup or Logical Switch object." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "Object specified does not contain a name property. Specify a Distributed PortGroup or Logical Switch object." } switch ($argument.objectTypeName) { @@ -974,26 +974,25 @@ Function ValidateLogicalSwitchOrDistributedPortGroup { Function ValidateLogicalSwitchOrDistributedPortGroupOrStandardPortGroup { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if (-not ( - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.VirtualPortGroupBaseInterop] ) -or - ($argument -is [System.Xml.XmlElement] ))) - { + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.VirtualPortGroupBaseInterop] ) -or + ($argument -is [System.Xml.XmlElement] ))) { throw "Must specify a distributed port group, logical switch or standard port group" } #Do we Look like XML describing a Logical Switch if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified does not contain an objectId property. Specify a Distributed PortGroup, Standard PortGroup or Logical Switch object." } - if ( -not ( $argument | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectTypeName -MemberType Properties)) { throw "Object specified does not contain a type property. Specify a Distributed PortGroup, Standard PortGroup or Logical Switch object." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "Object specified does not contain a name property. Specify a Distributed PortGroup, Standard PortGroup or Logical Switch object." } switch ($argument.objectTypeName) { @@ -1008,20 +1007,20 @@ Function ValidateLogicalSwitchOrDistributedPortGroupOrStandardPortGroup { Function ValidateIpPool { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name usedPercentage -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name usedPercentage -MemberType Properties)) { throw "XML Element specified does not contain a usedPercentage property." } $true @@ -1034,22 +1033,22 @@ Function ValidateIpPool { Function ValidateVdsContext { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name switch -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name switch -MemberType Properties)) { throw "XML Element specified does not contain a switch property." } - if ( -not ( $argument | get-member -name mtu -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name mtu -MemberType Properties)) { throw "XML Element specified does not contain an mtu property." } - if ( -not ( $argument | get-member -name uplinkPortName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name uplinkPortName -MemberType Properties)) { throw "XML Element specified does not contain an uplinkPortName property." } - if ( -not ( $argument | get-member -name promiscuousMode -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name promiscuousMode -MemberType Properties)) { throw "XML Element specified does not contain a promiscuousMode property." } $true @@ -1062,22 +1061,22 @@ Function ValidateVdsContext { Function ValidateSegmentIdRange { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name Id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Id -MemberType Properties)) { throw "XML Element specified does not contain an Id property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name begin -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name begin -MemberType Properties)) { throw "XML Element specified does not contain a begin property." } - if ( -not ( $argument | get-member -name end -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name end -MemberType Properties)) { throw "XML Element specified does not contain an end property." } $true @@ -1090,12 +1089,11 @@ Function ValidateSegmentIdRange { Function ValidateDistributedSwitch { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) - if (-not ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedSwitchInterop] )) - { + if (-not ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedSwitchInterop] )) { throw "Must specify a distributed switch" } @@ -1105,25 +1103,24 @@ Function ValidateDistributedSwitch { Function ValidateLogicalSwitch { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) - if (-not ($argument -is [System.Xml.XmlElement] )) - { + if (-not ($argument -is [System.Xml.XmlElement] )) { throw "Must specify a logical switch" } else { #Do we Look like XML describing a Logical Switch - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified does not contain an objectId property. Specify a Logical Switch object." } - if ( -not ( $argument | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectTypeName -MemberType Properties)) { throw "Object specified does not contain a type property. Specify a Logical Switch object." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "Object specified does not contain a name property. Specify a Logical Switch object." } switch ($argument.objectTypeName) { @@ -1138,7 +1135,7 @@ Function ValidateLogicalRouterInterfaceSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) @@ -1153,7 +1150,7 @@ Function ValidateLogicalRouterInterfaceSpec { Function ValidateEdgeInterfaceSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) @@ -1167,25 +1164,25 @@ Function ValidateEdgeInterfaceSpec { Function ValidateEdgeInterfaceAddress { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name primaryAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name primaryAddress -MemberType Properties)) { throw "XML Element specified does not contain a primaryAddress property." } - if ( -not ( $argument | get-member -name subnetPrefixLength -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name subnetPrefixLength -MemberType Properties)) { throw "XML Element specified does not contain a subnetPrefixLength property." } - if ( -not ( $argument | get-member -name subnetMask -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name subnetMask -MemberType Properties)) { throw "XML Element specified does not contain a subnetMask property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } - if ( -not ( $argument | get-member -name interfaceIndex -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name interfaceIndex -MemberType Properties)) { throw "XML Element specified does not contain an interfaceIndex property." } $true @@ -1198,16 +1195,16 @@ Function ValidateEdgeInterfaceAddress { Function ValidateAddressGroupSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name primaryAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name primaryAddress -MemberType Properties)) { throw "XML Element specified does not contain a primaryAddress property." } - if ( -not ( $argument | get-member -name subnetPrefixLength -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name subnetPrefixLength -MemberType Properties)) { throw "XML Element specified does not contain a subnetPrefixLength property." } $true @@ -1220,23 +1217,23 @@ Function ValidateAddressGroupSpec { Function ValidateLogicalRouter { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if we are an XML element if ($argument -is [System.Xml.XmlElement] ) { - if ( $argument | get-member -name edgeSummary -memberType Properties) { - if ( -not ( $argument.edgeSummary | get-member -name objectId -Membertype Properties)) { + if ( $argument | Get-Member -Name edgeSummary -MemberType Properties) { + if ( -not ( $argument.edgeSummary | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an edgesummary.objectId property. Specify a valid Logical Router Object" } - if ( -not ( $argument.edgeSummary | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument.edgeSummary | Get-Member -Name objectTypeName -MemberType Properties)) { throw "XML Element specified does not contain an edgesummary.ObjectTypeName property. Specify a valid Logical Router Object" } - if ( -not ( $argument.edgeSummary | get-member -name name -Membertype Properties)) { + if ( -not ( $argument.edgeSummary | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain an edgesummary.name property. Specify a valid Logical Router Object" } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property. Specify a valid Logical Router Object" } if ($argument.edgeSummary.objectTypeName -ne "Edge" ) { @@ -1259,23 +1256,23 @@ Function ValidateLogicalRouter { Function ValidateEdge { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if we are an XML element if ($argument -is [System.Xml.XmlElement] ) { - if ( $argument | get-member -name edgeSummary -memberType Properties) { - if ( -not ( $argument.edgeSummary | get-member -name objectId -Membertype Properties)) { + if ( $argument | Get-Member -Name edgeSummary -MemberType Properties) { + if ( -not ( $argument.edgeSummary | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an edgesummary.objectId property. Specify an NSX Edge Services Gateway object" } - if ( -not ( $argument.edgeSummary | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument.edgeSummary | Get-Member -Name objectTypeName -MemberType Properties)) { throw "XML Element specified does not contain an edgesummary.ObjectTypeName property. Specify an NSX Edge Services Gateway object" } - if ( -not ( $argument.edgeSummary | get-member -name name -Membertype Properties)) { + if ( -not ( $argument.edgeSummary | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain an edgesummary.name property. Specify an NSX Edge Services Gateway object" } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property. Specify an NSX Edge Services Gateway object" } if ($argument.edgeSummary.objectTypeName -ne "Edge" ) { @@ -1298,23 +1295,23 @@ Function ValidateEdge { Function ValidateEdgeRouting { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name routingGlobalConfig -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name routingGlobalConfig -MemberType Properties)) { throw "XML Element specified does not contain a routingGlobalConfig property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name version -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name version -MemberType Properties)) { throw "XML Element specified does not contain a version property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1327,23 +1324,23 @@ Function ValidateEdgeRouting { Function ValidateEdgeStaticRoute { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property." } - if ( -not ( $argument | get-member -name network -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name network -MemberType Properties)) { throw "XML Element specified does not contain a network property." } - if ( -not ( $argument | get-member -name nextHop -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name nextHop -MemberType Properties)) { throw "XML Element specified does not contain a nextHop property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1356,29 +1353,29 @@ Function ValidateEdgeStaticRoute { Function ValidateEdgeBgpNeighbour { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { throw "XML Element specified does not contain an ipAddress property." } - if ( -not ( $argument | get-member -name remoteAS -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name remoteAS -MemberType Properties)) { throw "XML Element specified does not contain a remoteAS property." } - if ( -not ( $argument | get-member -name weight -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name weight -MemberType Properties)) { throw "XML Element specified does not contain a weight property." } - if ( -not ( $argument | get-member -name holdDownTimer -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name holdDownTimer -MemberType Properties)) { throw "XML Element specified does not contain a holdDownTimer property." } - if ( -not ( $argument | get-member -name keepAliveTimer -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name keepAliveTimer -MemberType Properties)) { throw "XML Element specified does not contain a keepAliveTimer property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1391,20 +1388,20 @@ Function ValidateEdgeBgpNeighbour { Function ValidateEdgeOspfArea { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name areaId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name areaId -MemberType Properties)) { throw "XML Element specified does not contain an areaId property." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1417,20 +1414,20 @@ Function ValidateEdgeOspfArea { Function ValidateEdgeOspfInterface { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name areaId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name areaId -MemberType Properties)) { throw "XML Element specified does not contain an areaId property." } - if ( -not ( $argument | get-member -name vnic -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name vnic -MemberType Properties)) { throw "XML Element specified does not contain a vnic property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1443,23 +1440,23 @@ Function ValidateEdgeOspfInterface { Function ValidateEdgeRedistributionRule { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name learner -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name learner -MemberType Properties)) { throw "XML Element specified does not contain an areaId property." } - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "XML Element specified does not contain an id property." } - if ( -not ( $argument | get-member -name action -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name action -MemberType Properties)) { throw "XML Element specified does not contain an action property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1472,23 +1469,23 @@ Function ValidateEdgeRedistributionRule { Function ValidateLogicalRouterRouting { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LogicalRouter routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name routingGlobalConfig -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name routingGlobalConfig -MemberType Properties)) { throw "XML Element specified does not contain a routingGlobalConfig property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name version -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name version -MemberType Properties)) { throw "XML Element specified does not contain a version property." } - if ( -not ( $argument | get-member -name logicalrouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalrouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalrouterId property." } $true @@ -1501,17 +1498,17 @@ Function ValidateLogicalRouterRouting { Function ValidateLogicalRouterBridging { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LogicalRouter bridging element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name version -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name version -MemberType Properties)) { throw "XML Element specified does not contain a version property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } $true @@ -1524,23 +1521,23 @@ Function ValidateLogicalRouterBridging { Function ValidateLogicalRouterStaticRoute { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LogicalRouter routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property." } - if ( -not ( $argument | get-member -name network -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name network -MemberType Properties)) { throw "XML Element specified does not contain a network property." } - if ( -not ( $argument | get-member -name nextHop -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name nextHop -MemberType Properties)) { throw "XML Element specified does not contain a nextHop property." } - if ( -not ( $argument | get-member -name logicalrouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalrouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalrouterId property." } $true @@ -1553,23 +1550,23 @@ Function ValidateLogicalRouterStaticRoute { Function ValidateLogicalRouterBridge { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LogicalRouter routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name bridgeID -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name bridgeID -MemberType Properties)) { throw "XML Element specified does not contain a bridgeId property. Specify a valid LogicalRouter bridge instance" } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property. Specify a valid LogicalRouter bridge instance" } - if ( -not ( $argument | get-member -name virtualWire -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name virtualWire -MemberType Properties)) { throw "XML Element specified does not contain a virtualWire property. Specify a valid LogicalRouter bridge instance" } - if ( -not ( $argument | get-member -name dvportGroup -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name dvportGroup -MemberType Properties)) { throw "XML Element specified does not contain an dvportGroup property. Specify a valid LogicalRouter bridge instance" } $true @@ -1582,29 +1579,29 @@ Function ValidateLogicalRouterBridge { Function ValidateLogicalRouterBgpNeighbour { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LogicalRouter routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { throw "XML Element specified does not contain an ipAddress property." } - if ( -not ( $argument | get-member -name remoteAS -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name remoteAS -MemberType Properties)) { throw "XML Element specified does not contain a remoteAS property." } - if ( -not ( $argument | get-member -name weight -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name weight -MemberType Properties)) { throw "XML Element specified does not contain a weight property." } - if ( -not ( $argument | get-member -name holdDownTimer -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name holdDownTimer -MemberType Properties)) { throw "XML Element specified does not contain a holdDownTimer property." } - if ( -not ( $argument | get-member -name keepAliveTimer -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name keepAliveTimer -MemberType Properties)) { throw "XML Element specified does not contain a keepAliveTimer property." } - if ( -not ( $argument | get-member -name logicalrouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalrouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalrouterId property." } $true @@ -1617,20 +1614,20 @@ Function ValidateLogicalRouterBgpNeighbour { Function ValidateLogicalRouterOspfArea { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name areaId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name areaId -MemberType Properties)) { throw "XML Element specified does not contain an areaId property." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property." } - if ( -not ( $argument | get-member -name logicalrouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalrouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalrouterId property." } $true @@ -1643,20 +1640,20 @@ Function ValidateLogicalRouterOspfArea { Function ValidateLogicalRouterOspfInterface { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name areaId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name areaId -MemberType Properties)) { throw "XML Element specified does not contain an areaId property." } - if ( -not ( $argument | get-member -name vnic -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name vnic -MemberType Properties)) { throw "XML Element specified does not contain a vnic property." } - if ( -not ( $argument | get-member -name logicalrouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalrouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalrouterId property." } $true @@ -1669,23 +1666,23 @@ Function ValidateLogicalRouterOspfInterface { Function ValidateLogicalRouterRedistributionRule { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an OSPF Area element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name learner -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name learner -MemberType Properties)) { throw "XML Element specified does not contain an areaId property." } - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "XML Element specified does not contain an id property." } - if ( -not ( $argument | get-member -name action -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name action -MemberType Properties)) { throw "XML Element specified does not contain an action property." } - if ( -not ( $argument | get-member -name logicalrouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalrouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalrouterId property." } $true @@ -1698,20 +1695,20 @@ Function ValidateLogicalRouterRedistributionRule { Function ValidateEdgePrefix { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge prefix element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { throw "XML Element specified does not contain an ipAddress property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -1724,20 +1721,20 @@ Function ValidateEdgePrefix { Function ValidateLogicalRouterPrefix { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge prefix element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { throw "XML Element specified does not contain an ipAddress property." } - if ( -not ( $argument | get-member -name logicalRouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalRouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalRouterId property." } $true @@ -1750,22 +1747,22 @@ Function ValidateLogicalRouterPrefix { Function ValidateEdgeInterface { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Accepts an interface Object. if ($argument -is [System.Xml.XmlElement] ) { - If ( $argument | get-member -name index -memberType Properties ) { + If ( $argument | Get-Member -Name index -MemberType Properties ) { #Looks like an interface object - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property. Specify a valid Edge Services Gateway Interface object." } - if ( -not ( $argument | get-member -name label -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name label -MemberType Properties)) { throw "XML Element specified does not contain a label property. Specify a valid Edge Services Gateway Interface object." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property. Specify a valid Edge Services Gateway Interface object." } } @@ -1782,22 +1779,22 @@ Function ValidateEdgeInterface { Function ValidateLogicalRouterInterface { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Accepts an interface Object. if ($argument -is [System.Xml.XmlElement] ) { - If ( $argument | get-member -name index -memberType Properties ) { + If ( $argument | Get-Member -Name index -MemberType Properties ) { #Looks like an interface object - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property. Specify a valid Logical Router Interface object" } - if ( -not ( $argument | get-member -name label -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name label -MemberType Properties)) { throw "XML Element specified does not contain a label property. Specify a valid Logical Router Interface object" } - if ( -not ( $argument | get-member -name logicalRouterId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logicalRouterId -MemberType Properties)) { throw "XML Element specified does not contain an logicalRouterId property. Specify a valid Logical Router Interface object" } } @@ -1814,25 +1811,25 @@ Function ValidateLogicalRouterInterface { Function ValidateEdgeSubInterface { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Accepts a Subinterface Object. if ($argument -is [System.Xml.XmlElement] ) { - If ( $argument | get-member -name vnicId -memberType Properties ) { + If ( $argument | Get-Member -Name vnicId -MemberType Properties ) { #Looks like a Subinterface object - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain a edgeId property." } - if ( -not ( $argument | get-member -name vnicId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name vnicId -MemberType Properties)) { throw "XML Element specified does not contain a vnicId property." } - if ( -not ( $argument | get-member -name index -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name index -MemberType Properties)) { throw "XML Element specified does not contain an index property." } - if ( -not ( $argument | get-member -name label -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name label -MemberType Properties)) { throw "XML Element specified does not contain a label property." } } @@ -1849,23 +1846,23 @@ Function ValidateEdgeSubInterface { Function ValidateEdgeNat { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an EdgeNAT element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name version -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name version -MemberType Properties)) { throw "XML Element specified does not contain an version property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } - if ( -not ( $argument | get-member -name natRules -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name natRules -MemberType Properties)) { throw "XML Element specified does not contain a natRules property." } $true @@ -1878,32 +1875,32 @@ Function ValidateEdgeNat { Function ValidateEdgeNatRule { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an EdgeNAT element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name ruleId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ruleId -MemberType Properties)) { throw "XML Element specified does not contain a ruleId property. Specify a valid EdgeNatRule object." } - if ( -not ( $argument | get-member -name ruleType -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ruleType -MemberType Properties)) { throw "XML Element specified does not contain a ruleType property. Specify a valid EdgeNatRule object." } - if ( -not ( $argument | get-member -name action -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name action -MemberType Properties)) { throw "XML Element specified does not contain an action property. Specify a valid EdgeNatRule object." } - if ( -not ( $argument | get-member -name vnic -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name vnic -MemberType Properties)) { throw "XML Element specified does not contain a vnic property. Specify a valid EdgeNatRule object." } - if ( -not ( $argument | get-member -name translatedAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name translatedAddress -MemberType Properties)) { throw "XML Element specified does not contain a translatedAddress property. Specify a valid EdgeNatRule object." } - if ( -not ( $argument | get-member -name originalAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name originalAddress -MemberType Properties)) { throw "XML Element specified does not contain an originalAddress property. Specify a valid EdgeNatRule object." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property. Specify a valid EdgeNatRule object." } $true @@ -1916,23 +1913,23 @@ Function ValidateEdgeNatRule { Function ValidateEdgeFw { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an EdgeFW element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property. Specify a valid Edge Firewall object." } - if ( -not ( $argument | get-member -name globalConfig -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name globalConfig -MemberType Properties)) { throw "XML Element specified does not contain a globalConfig property. Specify a valid Edge Firewall object." } - if ( -not ( $argument | get-member -name defaultPolicy -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name defaultPolicy -MemberType Properties)) { throw "XML Element specified does not contain a defaultPolicy property. Specify a valid Edge Firewall object." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property. Specify a valid Edge Firewall object." } $true @@ -1945,23 +1942,23 @@ Function ValidateEdgeFw { Function ValidateEdgeFwRule { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an EdgeFWRule element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "XML Element specified does not contain an id property. Specify a valid Edge FirewallRule object." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an EdgeId property. Specify a valid Edge FirewallRule object." } - if ( -not ( $argument | get-member -name ruleType -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ruleType -MemberType Properties)) { throw "XML Element specified does not contain a ruleType property. Specify a valid Edge FirewallRule object." } - if ( -not ( $argument | get-member -name action -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name action -MemberType Properties)) { throw "XML Element specified does not contain an action property. Specify a valid Edge FirewallRule object." } $true @@ -1974,32 +1971,32 @@ Function ValidateEdgeFwRule { Function ValidateEdgeSslVpn { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name logging -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logging -MemberType Properties)) { throw "XML Element specified does not contain a logging property." } - if ( -not ( $argument | get-member -name advancedConfig -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name advancedConfig -MemberType Properties)) { throw "XML Element specified does not contain an advancedConfig property." } - if ( -not ( $argument | get-member -name clientConfiguration -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name clientConfiguration -MemberType Properties)) { throw "XML Element specified does not contain a clientConfiguration property." } - if ( -not ( $argument | get-member -name layoutConfiguration -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name layoutConfiguration -MemberType Properties)) { throw "XML Element specified does not contain a layoutConfiguration property." } - if ( -not ( $argument | get-member -name authenticationConfiguration -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name authenticationConfiguration -MemberType Properties)) { throw "XML Element specified does not contain a authenticationConfiguration property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -2012,23 +2009,23 @@ Function ValidateEdgeSslVpn { Function ValidateEdgeCsr { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name subject -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name subject -MemberType Properties)) { throw "XML Element specified does not contain a subject property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name algorithm -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name algorithm -MemberType Properties)) { throw "XML Element specified does not contain an algorithm property." } - if ( -not ( $argument | get-member -name keysize -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name keysize -MemberType Properties)) { throw "XML Element specified does not contain a keysize property." } $true @@ -2041,23 +2038,23 @@ Function ValidateEdgeCsr { Function ValidateEdgeCertificate { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name issuerCn -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name issuerCn -MemberType Properties)) { throw "XML Element specified does not contain an issuerCn property." } - if ( -not ( $argument | get-member -name subjectCn -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name subjectCn -MemberType Properties)) { throw "XML Element specified does not contain a subjectCn property." } - if ( -not ( $argument | get-member -name certificateType -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name certificateType -MemberType Properties)) { throw "XML Element specified does not contain a certificateType property." } - if ( -not ( $argument | get-member -name x509Certificate -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name x509Certificate -MemberType Properties)) { throw "XML Element specified does not contain an x509Certificate property." } $true @@ -2070,20 +2067,20 @@ Function ValidateEdgeCertificate { Function ValidateEdgeSslVpnUser { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name userId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name userId -MemberType Properties)) { throw "XML Element specified does not contain a userId property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeID property." } @@ -2097,29 +2094,29 @@ Function ValidateEdgeSslVpnUser { Function ValidateEdgeSslVpnIpPool { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name ipRange -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipRange -MemberType Properties)) { throw "XML Element specified does not contain a userId property." } - if ( -not ( $argument | get-member -name netmask -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name netmask -MemberType Properties)) { throw "XML Element specified does not contain a netmask property." } - if ( -not ( $argument | get-member -name gateway -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name gateway -MemberType Properties)) { throw "XML Element specified does not contain a gateway property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeID property." } @@ -2133,23 +2130,23 @@ Function ValidateEdgeSslVpnIpPool { Function ValidateEdgeSslVpnPrivateNetwork { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name network -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name network -MemberType Properties)) { throw "XML Element specified does not contain a network property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeID property." } @@ -2163,23 +2160,23 @@ Function ValidateEdgeSslVpnPrivateNetwork { Function ValidateEdgeSslVpnClientPackage { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name profileName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name profileName -MemberType Properties)) { throw "XML Element specified does not contain a profileName property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeID property." } @@ -2193,13 +2190,13 @@ Function ValidateEdgeSslVpnClientPackage { Function ValidateSecurityGroupMember { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Populate the global membertype cache if not already done #Using the API rather than hardcoding incase this changes with versions of NSX - if ( -not (test-path Variable:\NsxMemberTypes) ) { + if ( -not (Test-Path Variable:\NsxMemberTypes) ) { $script:NsxMemberTypes = Get-NsxSecurityGroupMemberTypes } @@ -2212,7 +2209,7 @@ Function ValidateSecurityGroupMember { #Argument is objectid and matches a recognised NSX SG membertype $true } - elseif ( ($argument -is [string] ) -and ( [guid]::tryparse(($argument -replace ".\d{3}$",""), [ref][guid]::Empty)) ) { + elseif ( ($argument -is [string] ) -and ( [guid]::tryparse(($argument -replace ".\d{3}$", ""), [ref][guid]::Empty)) ) { #Argument is vNIC as object ID. $true } @@ -2225,13 +2222,13 @@ Function ValidateSecurityGroupMember { $true } elseif ($argument -is [System.Xml.XmlElement]) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Member is not a supported type. Specify an object of type $($NsxMemberTypes -join ",")." } - if ( -not ( $argument | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectTypeName -MemberType Properties)) { throw "Member is not a supported type. Specify an object of type $($NsxMemberTypes -join ",")." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "Member is not a supported type. Specify an object of type $($NsxMemberTypes -join ",")." } if ( $NsxMemberTypes -notcontains $argument.objectTypeName) { @@ -2247,10 +2244,10 @@ Function ValidateSecurityGroupMember { Function ValidateIPHost { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) - if ( ( $argument -as [ipaddress] ) -or ( ( ValidateIPPrefix $argument ) -and ($argument -match '^(\d{1,3}\.){3}\d{1,3}\/32\s*$') ) ) { + if ( ( $argument -as [ipaddress] ) -or ( ( ValidateIPPrefix $argument ) -and ($argument -match '^(\d{1,3}\.){3}\d{1,3}\/32\s*$') ) ) { $true } } @@ -2258,7 +2255,7 @@ Function ValidateIPHost { Function ValidateIPRange { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ( ($argument -as [string]) -and ($argument -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\-\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") ) { @@ -2269,7 +2266,7 @@ Function ValidateIPRange { Function ValidateIPPrefix { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ( ($argument -as [string]) -and ($argument -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/([0-9]|[1-2][0-9]|3[0-2])?$") ) { @@ -2280,7 +2277,7 @@ Function ValidateIPPrefix { Function ValidateFirewallRuleSourceDest { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) @@ -2296,33 +2293,33 @@ Function ValidateFirewallRuleSourceDest { } else { ValidateSecurityGroupMember $argument - } + } } Function ValidateFirewallRule { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like a DFW rule if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name id -MemberType Properties )) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties )) { throw "Specified firewall rule XML element does not contain an id property." } - if ( -not ( $argument | get-member -name action -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name action -MemberType Properties)) { throw "Specified firewall rule XML element does not contain an action property." } - if ( -not ( $argument | get-member -name appliedToList -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name appliedToList -MemberType Properties)) { throw "Specified firewall rule XML element does not contain an appliedToList property." } #Validate that the rule has a parent node that we can use to update it if required. try { - $ParentSection = invoke-xpathquery -query "parent::section" -QueryMethod SelectSingleNode -Node $argument + $ParentSection = Invoke-XpathQuery -query "parent::section" -QueryMethod SelectSingleNode -Node $argument $null = $Parentsection.HasAttribute("id") -as [int] $null = $argument.HasAttribute("id") } @@ -2341,7 +2338,7 @@ Function ValidateFirewallRuleMember { #Distinct from ValidateFirewallRuleMemberObject in that it checks for an arg that is a valid firewallrule member object, OR a string to match against the value of one. Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) @@ -2359,28 +2356,28 @@ Function ValidateFirewallRuleMemberObject { #Distinct from ValidateFirewallRuleMember in that it checks for an arg that looks like the appropriate return object from get-nsxfirewallrulemember. Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Same requirements for Firewall Rule SourceDest except for string match on name as well. If ( $argument -is [pscustomobject] ) { - if ( -not ( $argument | get-member -name RuleId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name RuleId -MemberType Properties)) { throw "Specified argument is not a valid FirewallRuleMember object." } - if ( -not ( $argument | get-member -name SectionId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SectionId -MemberType Properties)) { throw "Specified argument is not a valid FirewallRuleMember object." } - if ( -not ( $argument | get-member -name MemberType -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name MemberType -MemberType Properties)) { throw "Specified argument is not a valid FirewallRuleMember object." } - if ( -not ( $argument | get-member -name Name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Name -MemberType Properties)) { throw "Specified argument is not a valid FirewallRuleMember object." } - if ( -not ( $argument | get-member -name Value -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Value -MemberType Properties)) { throw "Specified argument is not a valid FirewallRuleMember object." } - if ( -not ( $argument | get-member -name Type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Type -MemberType Properties)) { throw "Specified argument is not a valid FirewallRuleMember object." } $true @@ -2393,17 +2390,17 @@ Function ValidateFirewallRuleMemberObject { Function ValidateServiceGroup { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) - if ( $argument -is [system.xml.xmlelement] ){ - if ( -not ($argument | get-member -MemberType Property -Name objectId )) { + if ( $argument -is [system.xml.xmlelement] ) { + if ( -not ($argument | Get-Member -MemberType Property -Name objectId )) { throw "Invalid service group specified" } - if ( -not ($argument | get-member -MemberType Property -Name objectTypeName )) { + if ( -not ($argument | Get-Member -MemberType Property -Name objectTypeName )) { throw "Invalid service group specified" } - if ( -not ($argument.objectTypeName -eq "ApplicationGroup")){ + if ( -not ($argument.objectTypeName -eq "ApplicationGroup")) { throw "Invalid service group specified" } $true @@ -2416,17 +2413,17 @@ Function ValidateServiceGroup { Function ValidateService { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) - if ( $argument -is [system.xml.xmlelement] ){ - if ( -not ($argument | get-member -MemberType Property -Name objectId )) { + if ( $argument -is [system.xml.xmlelement] ) { + if ( -not ($argument | Get-Member -MemberType Property -Name objectId )) { throw "Invalid service specified" } - if ( -not ($argument | get-member -MemberType Property -Name objectTypeName )) { + if ( -not ($argument | Get-Member -MemberType Property -Name objectTypeName )) { throw "Invalid service specified" } - if ( -not ($argument.objectTypeName -eq "Application")){ + if ( -not ($argument.objectTypeName -eq "Application")) { throw "Invalid service specified" } $true @@ -2439,7 +2436,7 @@ Function ValidateService { Function ValidateServiceOrServiceGroup { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) try { @@ -2460,20 +2457,21 @@ Function ValidateServiceOrServiceGroup { Function ValidateFirewallRuleService { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) switch ($argument) { # Testing to see if a raw protocol/port has been provided. - { $argument -is [string]} { + { $argument -is [string] } { # Now we check to see that the protocol provided is valid. if ($argument -match "/") { $exploded = $argument -split "/" if ( -not ($Script:AllValidServices -contains $exploded[0] ) ) { throw "Invalid protocol specified" } - } elseif ( $Script:AllValidServices -notcontains $argument ) { + } + elseif ( $Script:AllValidServices -notcontains $argument ) { throw "Invalid protocol specified" } $true @@ -2482,7 +2480,7 @@ Function ValidateFirewallRuleService { # If an single xml element object or a collection of objects have been provide, # then we run it through validation to stop doing stupid stuff like trying to pass # a logical switch or IP Set through to here. - { ($argument -is [System.Xml.XmlElement]) -or ($argument -is [System.Object])} { + { ($argument -is [System.Xml.XmlElement]) -or ($argument -is [System.Object]) } { foreach ( $item in $argument ) { try { ValidateService -argument $item @@ -2505,13 +2503,13 @@ Function ValidateFirewallRuleService { Function ValidateEdgeFirewallRuleService { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) switch ($argument) { # Testing to see if a raw protocol/port has been provided. - { $argument -is [string]} { + { $argument -is [string] } { ## NB : Need to populate AllValidEdgeServices, and I havent yet found how to get this list. ## In mean time, we will rely on the API pushing back in event of invalid service being specified by user. @@ -2531,7 +2529,7 @@ Function ValidateEdgeFirewallRuleService { # If an single xml element object or a collection of objects have been provide, # then we run it through validation to stop doing stupid stuff like trying to pass # a logical switch or IP Set through to here. - { ($argument -is [System.Xml.XmlElement]) -or ($argument -is [System.Object])} { + { ($argument -is [System.Xml.XmlElement]) -or ($argument -is [System.Object]) } { foreach ( $item in $argument ) { try { ValidateService -argument $item @@ -2554,49 +2552,50 @@ Function ValidateEdgeFirewallRuleService { Function ValidateFirewallAppliedTo { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check types first if (-not ( - ($argument -is [System.Xml.XmlElement]) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop] ) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.DatacenterInterop] ) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VMHostInterop] ) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.VirtualPortGroupBaseInterop] ) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop] ) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop] ) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ))) { - - throw "$($_.gettype()) is not a supported type. Specify a Datacenter, Cluster, Host ` + ($argument -is [System.Xml.XmlElement]) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop] ) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.DatacenterInterop] ) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VMHostInterop] ) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.VirtualPortGroupBaseInterop] ) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop] ) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop] ) -or + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ))) { + + throw "$($_.gettype()) is not a supported type. Specify a Datacenter, Cluster, Host ` DistributedPortGroup, PortGroup, ResourcePool, VirtualMachine, NetworkAdapter, ` IPSet, SecurityGroup, Logical Switch or Edge object." - } else { + } + else { #Check if we have an ID property if ($argument -is [System.Xml.XmlElement] ) { - if ( $argument | get-member -name edgeSummary ) { + if ( $argument | Get-Member -Name edgeSummary ) { #Looks like an Edge, get the summary details... I KNEW this would come in handy when I wrote the Get-NSxEdge cmdlet... FIGJAM... $argument = $argument.edgeSummary } - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name objectTypeName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectTypeName -MemberType Properties)) { throw "XML Element specified does not contain a type property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } switch ($argument.objectTypeName) { - "IPSet"{} + "IPSet" {} "SecurityGroup" {} "VirtualWire" {} "Edge" {} @@ -2614,20 +2613,20 @@ Function ValidateFirewallAppliedTo { Function ValidateLoadBalancer { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LB element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name version -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name version -MemberType Properties)) { throw "XML Element specified does not contain an version property." } - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -2640,23 +2639,23 @@ Function ValidateLoadBalancer { Function ValidateLoadBalancerMonitor { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LB monitor element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name monitorId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name monitorId -MemberType Properties)) { throw "XML Element specified does not contain a version property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -2669,23 +2668,23 @@ Function ValidateLoadBalancerMonitor { Function ValidateLoadBalancerVip { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LB monitor element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name virtualServerId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name virtualServerId -MemberType Properties)) { throw "XML Element specified does not contain a virtualServerId property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { throw "XML Element specified does not contain an ipAddress property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -2698,24 +2697,24 @@ Function ValidateLoadBalancerVip { Function ValidateLoadBalancerMemberSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property. Create with New-NsxLoadbalancerMemberSpec" } - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { throw "XML Element specified does not contain an ipAddress property. Create with New-NsxLoadbalancerMemberSpec" } - if ( -not ( $argument | get-member -name weight -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name weight -MemberType Properties)) { throw "XML Element specified does not contain a weight property. Create with New-NsxLoadbalancerMemberSpec" } - if ( -not ( $argument | get-member -name minConn -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name minConn -MemberType Properties)) { throw "XML Element specified does not contain a minConn property. Create with New-NsxLoadbalancerMemberSpec" } - if ( -not ( $argument | get-member -name maxConn -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name maxConn -MemberType Properties)) { throw "XML Element specified does not contain a maxConn property. Create with New-NsxLoadbalancerMemberSpec" } $true @@ -2728,20 +2727,20 @@ Function ValidateLoadBalancerMemberSpec { Function ValidateLoadBalancerApplicationProfile { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LB applicationProfile element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name applicationProfileId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name applicationProfileId -MemberType Properties)) { throw "XML Element specified does not contain an applicationProfileId property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } - if ( -not ( $argument | get-member -name template -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name template -MemberType Properties)) { throw "XML Element specified does not contain a template property." } $True @@ -2754,17 +2753,17 @@ Function ValidateLoadBalancerApplicationProfile { Function ValidateLoadBalancerPool { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LB pool element if ($_ -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name poolId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name poolId -MemberType Properties)) { throw "XML Element specified does not contain an poolId property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } $True @@ -2777,25 +2776,25 @@ Function ValidateLoadBalancerPool { Function ValidateLoadBalancerPoolMember { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an LB pool element if ($_ -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name poolId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name poolId -MemberType Properties)) { throw "XML Element specified does not contain an poolId property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } - if ( -not ( $argument | get-member -name ipAddress -Membertype Properties)) { - if ( -not ( $argument | get-member -name groupingObjectId -MemberType Properties ) ) { + if ( -not ( $argument | Get-Member -Name ipAddress -MemberType Properties)) { + if ( -not ( $argument | Get-Member -Name groupingObjectId -MemberType Properties ) ) { throw "XML Element specified does not contain an ipAddress property." } } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain a name property." } $True @@ -2808,20 +2807,20 @@ Function ValidateLoadBalancerPoolMember { Function ValidateSecurityGroup { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property. Specify a valid Security Group object." } - if ( -not ( $argument | get-member -name Name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Name -MemberType Properties)) { throw "XML Element specified does not contain a Name property. Specify a valid Security Group object." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property. Specify a valid Security Group object." } if ( -not ( $argument.type.typeName -eq "SecurityGroup" )) { @@ -2837,7 +2836,7 @@ Function ValidateSecurityGroup { Function ValidateSPFirewallSrcDest { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) @@ -2856,22 +2855,22 @@ Function ValidateSPFirewallSrcDest { Function ValidateSecPolFwSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ( $argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name Name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Name -MemberType Properties)) { Throw "Specify a valid Security Policy Firewall Spec object as created by New-NsxSecurityPolicyFirewallRuleSpec." } - if ( -not ( $argument | get-member -name action -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name action -MemberType Properties)) { Throw "Specify a valid Security Policy Firewall Spec object as created by New-NsxSecurityPolicyFirewallRuleSpec." } - if ( -not ( $argument | get-member -name isEnabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name isEnabled -MemberType Properties)) { Throw "Specify a valid Security Policy Firewall Spec object as created by New-NsxSecurityPolicyFirewallRuleSpec." } - if ( -not ( $argument | get-member -name 'class' -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name 'class' -MemberType Properties)) { Throw "Specify a valid Security Policy Firewall Spec object as created by New-NsxSecurityPolicyFirewallRuleSpec." } if ( -not ( $argument.class -eq "firewallSecurityAction" )) { @@ -2888,16 +2887,16 @@ Function ValidateSecPolFwSpec { Function ValidateSecPolGiSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ( $argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name isEnabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name isEnabled -MemberType Properties)) { Throw "Specify a valid Security Policy Guest Introspection Spec object as created by New-NsxSecurityPolicyGuestIntrospectionSpec." } - if ( -not ( $argument | get-member -name 'class' -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name 'class' -MemberType Properties)) { Throw "Specify a valid Security Policy Guest Introspection Spec object as created by New-NsxSecurityPolicyGuestIntrospectionSpec." } if ( -not ( $argument.class -eq "endpointSecurityAction" )) { @@ -2914,16 +2913,16 @@ Function ValidateSecPolGiSpec { Function ValidateSecPolNiSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ( $argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name isEnabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name isEnabled -MemberType Properties)) { Throw "Specify a valid Security Policy Network Introspection Spec object as created by New-NsxSecurityPolicyGuestIntrospectionSpec." } - if ( -not ( $argument | get-member -name 'class' -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name 'class' -MemberType Properties)) { Throw "Specify a valid Security Policy Network Introspection Spec object as created by New-NsxSecurityPolicyGuestIntrospectionSpec." } if ( -not ( $argument.class -eq "trafficSteeringSecurityAction" )) { @@ -2940,20 +2939,20 @@ Function ValidateSecPolNiSpec { Function ValidateSecurityTag { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ($_ -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "XML Element specified does not contain an objectId property." } - if ( -not ( $argument | get-member -name Name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Name -MemberType Properties)) { throw "XML Element specified does not contain a Name property." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "XML Element specified does not contain a type property." } if ( -not ( $argument.Type.TypeName -eq 'SecurityTag' )) { @@ -2969,23 +2968,23 @@ Function ValidateSecurityTag { Function ValidateSpoofguardPolicy { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ($_ -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name policyId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name policyId -MemberType Properties)) { throw "XML Element specified does not contain an policyId property." } - if ( -not ( $argument | get-member -name Name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name Name -MemberType Properties)) { throw "XML Element specified does not contain a Name property." } - if ( -not ( $argument | get-member -name operationMode -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name operationMode -MemberType Properties)) { throw "XML Element specified does not contain an OperationMode property." } - if ( -not ( $argument | get-member -name defaultPolicy -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name defaultPolicy -MemberType Properties)) { throw "XML Element specified does not contain a defaultPolicy property." } $True @@ -2998,20 +2997,20 @@ Function ValidateSpoofguardPolicy { Function ValidateSpoofguardNic { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag element if ($_ -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "XML Element specified does not contain an id property." } - if ( -not ( $argument | get-member -name vnicUuid -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name vnicUuid -MemberType Properties)) { throw "XML Element specified does not contain a vnicUuid property." } - if ( -not ( $argument | get-member -name policyId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name policyId -MemberType Properties)) { throw "XML Element specified does not contain a policyId property." } $True @@ -3024,12 +3023,12 @@ Function ValidateSpoofguardNic { Function ValidateVirtualMachine { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if (-not ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop] )) { - throw "Object is not a supported type. Specify a VirtualMachine object." + throw "Object is not a supported type. Specify a VirtualMachine object." } $true @@ -3037,35 +3036,34 @@ Function ValidateVirtualMachine { Function ValidateVirtualMachineOrTemplate { - Param ( - [Parameter (Mandatory=$true)] - [object]$argument - ) + Param ( + [Parameter (Mandatory = $true)] + [object]$argument + ) - if ( -not ( + if ( -not ( ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]) -or - ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.TemplateInterop]))) - { - throw "Object is not a supported type. Specify a VirtualMachine or Template object." - } - - $true + ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Inventory.TemplateInterop]))) { + throw "Object is not a supported type. Specify a VirtualMachine or Template object." } - Function ValidateTagAssignment { + $true +} + +Function ValidateTagAssignment { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like Security Tag Assignmenbt if ($argument -is [PSCustomObject] ) { - if ( -not ( $argument | get-member -name SecurityTag -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SecurityTag -MemberType Properties)) { throw "Specify a valid Security Tag Assignment. Specified object does not contain a SecurityTag property object." } - if ( -not ( $argument | get-member -name VirtualMachine -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name VirtualMachine -MemberType Properties)) { throw "Specify a valid Security Tag Assignment. Specified object does not contain a VirtualMachine property object." } if ( -not ( $argument.SecurityTag -is [System.Xml.XmlElement] )) { @@ -3083,7 +3081,7 @@ Function ValidateVirtualMachineOrTemplate { Function ValidateFwSourceDestFilter { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ( ($argument -as [ipaddress]) -or @@ -3101,13 +3099,13 @@ Function ValidateFwSourceDestFilter { Function ValidateController { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "Specify a valid Controller." } if ( -not ( $argument.id -match "controller-\d+")) { @@ -3123,22 +3121,22 @@ Function ValidateController { Function ValidateSecondaryManager { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name uuid -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name uuid -MemberType Properties)) { throw "Specify a valid secondary NSX manager." } - if ( -not ( $argument | get-member -name nsxManagerIp -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name nsxManagerIp -MemberType Properties)) { throw "Specify a valid secondary NSX manager." } - if ( -not ( $argument | get-member -name isPrimary -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name isPrimary -MemberType Properties)) { throw "Specify a valid secondary NSX manager." } - if ( $argument.isPrimary -eq 'true'){ + if ( $argument.isPrimary -eq 'true') { throw "The specified manager has the primary role. Specify a valid secondary NSX manager." } @@ -3152,19 +3150,19 @@ Function ValidateSecondaryManager { Function ValidateDynamicCriteriaSpec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name key -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name key -MemberType Properties)) { throw "XML Element specified does not contain a key property. Specify a valid Dynamic Criteria Spec." } - if ( -not ( $argument | get-member -name criteria -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name criteria -MemberType Properties)) { throw "XML Element specified does not contain a criteria property. Specify a valid Dynamic Criteria Spec." } - if ( -not ( $argument | get-member -name value -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name value -MemberType Properties)) { throw "XML Element specified does not contain a value property. Specify a valid Dynamic Criteria Spec." } $true @@ -3176,25 +3174,25 @@ Function ValidateDynamicCriteriaSpec { Function ValidateDynamicMemberSet { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [PSCustomObject] ) { - if ( -not ( $argument | get-member -name index -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name index -MemberType Properties)) { throw "Object specified does not contain an index property. Specify a valid Dynamic Member Set." } - if ( -not ( $argument | get-member -name SecurityGroupName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SecurityGroupName -MemberType Properties)) { throw "Object specified does not contain a SecurityGroup Name property. Specify a valid Dynamic Member Set." } - if ( -not ( $argument | get-member -name SecurityGroup -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SecurityGroup -MemberType Properties)) { throw "Object specified does not contain a SecurityGroup property. Specify a valid Dynamic Member Set." } - if ( -not ( $argument | get-member -name criteria -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name criteria -MemberType Properties)) { throw "Object specified does not contain a criteria property. Specify a valid Dynamic Member Set." } - if ( -not ( $argument | get-member -name SetOperator -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SetOperator -MemberType Properties)) { throw "Object specified does not contain a Set Operator property. Specify a valid Dynamic Member Set." } $true @@ -3206,31 +3204,31 @@ Function ValidateDynamicMemberSet { Function ValidateDynamicCriteria { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [PSCustomObject] ) { - if ( -not ( $argument | get-member -name index -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name index -MemberType Properties)) { throw "Object specified does not contain an index property. Specify a valid Dynamic Criteria object." } - if ( -not ( $argument | get-member -name MemberSetIndex -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name MemberSetIndex -MemberType Properties)) { throw "Object specified does not contain an index property. Specify a valid Dynamic Criteria object." } - if ( -not ( $argument | get-member -name SecurityGroupName -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SecurityGroupName -MemberType Properties)) { throw "Object specified does not contain a SecurityGroup Name property. Specify a valid Dynamic Criteria object." } - if ( -not ( $argument | get-member -name SecurityGroup -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name SecurityGroup -MemberType Properties)) { throw "Object specified does not contain a SecurityGroup property. Specify a valid Dynamic Criteria object." } - if ( -not ( $argument | get-member -name key -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name key -MemberType Properties)) { throw "Object specified does not contain a key property. Specify a valid Dynamic Criteria object." } - if ( -not ( $argument | get-member -name condition -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name condition -MemberType Properties)) { throw "Object specified does not contain a condition property. Specify a valid Dynamic Criteria object." } - if ( -not ( $argument | get-member -name key -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name key -MemberType Properties)) { throw "Object specified does not contain a value property. Specify a valid Dynamic Criteria object." } $true @@ -3242,16 +3240,16 @@ Function ValidateDynamicCriteria { Function ValidateServiceDefinition { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified contains no objectId property. Specify a valid Service Definition object." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "Object specified contains no type property. Specify a valid Service Definition object." } if ( -not ( $argument.type.typename -eq "Service" )) { @@ -3266,16 +3264,16 @@ Function ValidateServiceDefinition { Function ValidateServiceProfile { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified contains no objectId property. Specify a valid Service Profile object." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "Object specified contains no type property. Specify a valid Service Profile object." } if ( -not ( $argument.type.typename -eq "ServiceProfile" )) { @@ -3290,16 +3288,16 @@ Function ValidateServiceProfile { Function ValidateSecurityPolicy { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified contains no objectId property. Specify a valid Security Policy object." } - if ( -not ( $argument | get-member -name type -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name type -MemberType Properties)) { throw "Object specified contains no type property. Specify a valid Security Policy object." } if ( -not ( $argument.type.typename -eq "Policy" )) { @@ -3314,20 +3312,20 @@ Function ValidateSecurityPolicy { Function ValidateSecPolRule { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name objectId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name objectId -MemberType Properties)) { throw "Object specified contains no objectId property. Specify a valid Security Policy Rule object." } - if ( -not ( $argument | get-member -name class -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name class -MemberType Properties)) { throw "Object specified contains no class attribute. Specify a valid Security Policy Rule object." } if ( -not ( ($argument.class -eq "firewallSecurityAction") -or - ($argument.class -eq "endpointSecurityAction") -or - ($argument.class -eq "trafficSteeringSecurityAction") )) { + ($argument.class -eq "endpointSecurityAction") -or + ($argument.class -eq "trafficSteeringSecurityAction") )) { throw "Object specified is of the wrong class $($argument.class). Specify a valid Security Policy Rule object." } #Because we frequently rely on the parent node relationship to do editing of the parent policy xml, we have to make sure user hasnt concocted a rule out of thin air. @@ -3349,33 +3347,33 @@ Function ValidateSecPolRule { function ValidateFirewallDraft { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "XML Element specified does not contain an id property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain an name property." } - if ( -not ( $argument | get-member -name timestamp -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name timestamp -MemberType Properties)) { throw "XML Element specified does not contain an timestamp property." } - if ( -not ( $argument | get-member -name preserve -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name preserve -MemberType Properties)) { throw "XML Element specified does not contain an preserve property." } - if ( -not ( $argument | get-member -name user -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name user -MemberType Properties)) { throw "XML Element specified does not contain an user property." } - if ( -not ( $argument | get-member -name mode -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name mode -MemberType Properties)) { throw "XML Element specified does not contain an mode property." } @@ -3389,37 +3387,37 @@ function ValidateFirewallDraft { function ValidateFirewallSavedConfiguration { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name id -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name id -MemberType Properties)) { throw "XML Element specified does not contain an id property." } - if ( -not ( $argument | get-member -name name -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name name -MemberType Properties)) { throw "XML Element specified does not contain an name property." } - if ( -not ( $argument | get-member -name timestamp -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name timestamp -MemberType Properties)) { throw "XML Element specified does not contain an timestamp property." } - if ( -not ( $argument | get-member -name preserve -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name preserve -MemberType Properties)) { throw "XML Element specified does not contain an preserve property." } - if ( -not ( $argument | get-member -name user -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name user -MemberType Properties)) { throw "XML Element specified does not contain an user property." } - if ( -not ( $argument | get-member -name mode -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name mode -MemberType Properties)) { throw "XML Element specified does not contain an mode property." } - if ( -not ( $argument | get-member -name config -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name config -MemberType Properties)) { throw "XML Element specified does not contain an config property." } @@ -3434,29 +3432,29 @@ function ValidateFirewallSavedConfiguration { Function ValidateEdgeDns { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) #Check if it looks like an Edge routing element if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name cacheSize -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name cacheSize -MemberType Properties)) { throw "XML Element specified does not contain an cacheSize property." } - if ( -not ( $argument | get-member -name listeners -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name listeners -MemberType Properties)) { throw "XML Element specified does not contain an listeners property." } - if ( -not ( $argument | get-member -name dnsViews -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name dnsViews -MemberType Properties)) { throw "XML Element specified does not contain an dnsViews property." } - if ( -not ( $argument | get-member -name logging -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logging -MemberType Properties)) { throw "XML Element specified does not contain a logging property." } - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } $true @@ -3469,25 +3467,25 @@ Function ValidateEdgeDns { function ValidateCliSettings { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name edgeId -MemberType Properties)) { throw "XML Element specified does not contain an edgeId property." } - if ( -not ( $argument | get-member -name remoteAccess -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name remoteAccess -MemberType Properties)) { throw "XML Element specified does not contain an remoteAccess property." } - if ( -not ( $argument | get-member -name sshLoginBannerText -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name sshLoginBannerText -MemberType Properties)) { throw "XML Element specified does not contain an sshLoginBannerText property." } - if ( -not ( $argument | get-member -name passwordExpiry -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name passwordExpiry -MemberType Properties)) { throw "XML Element specified does not contain an passwordExpiry property." } @@ -3501,25 +3499,25 @@ function ValidateCliSettings { Function ValidateIPsec { Param ( - [Parameter (Mandatory=$true)] + [Parameter (Mandatory = $true)] [object]$argument ) if ($argument -is [System.Xml.XmlElement] ) { - if ( -not ( $argument | get-member -name enabled -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name enabled -MemberType Properties)) { throw "XML Element specified does not contain an enabled property." } - if ( -not ( $argument | get-member -name logging -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name logging -MemberType Properties)) { throw "XML Element specified does not contain an logging property." } - if ( -not ( $argument | get-member -name sites -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name sites -MemberType Properties)) { throw "XML Element specified does not contain an sites property." } - if ( -not ( $argument | get-member -name global -Membertype Properties)) { + if ( -not ( $argument | Get-Member -Name global -MemberType Properties)) { throw "XML Element specified does not contain an global property." } @@ -3569,16 +3567,16 @@ function Format-XML () { #is easily read by humans. Seriously - how is this not part of the dotnet system.xml classes? param ( - [Parameter (Mandatory=$false,ValueFromPipeline=$true,Position=1) ] - [ValidateNotNullorEmpty()] + [Parameter (Mandatory = $false, ValueFromPipeline = $true, Position = 1) ] + [ValidateNotNullorEmpty()] - #String object containing valid XML, or XMLElement or XMLDocument object - $xml="", - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] + #String object containing valid XML, or XMLElement or XMLDocument object + $xml = "", + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] - #Number of whitespace charaters to indent child nodes by when formatting - [int]$indent=2 + #Number of whitespace charaters to indent child nodes by when formatting + [int]$indent = 2 ) begin {} @@ -3600,7 +3598,7 @@ function Format-XML () { throw "Specified string cannot be cast to an XML document." } } - else{ + else { throw "Unknown data type specified as xml to Format-Xml." } @@ -3618,7 +3616,7 @@ function Format-XML () { Write-Output $StringWriter.ToString() } - end{} + end {} } function Export-NsxObject { @@ -3651,46 +3649,46 @@ function Export-NsxObject { $ImportedEdge. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] #Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] #Cant remove without breaking backward compatibility Param( - [Parameter (Mandatory=$true, ValueFromPipeline=$True)] - #PowerNSX Object to be exported - [System.Xml.XmlElement[]]$Object, - [Parameter (Mandatory=$true, Position=1)] - #Text Encoding used in export file. - [ValidateNotNullOrEmpty()] - [String]$FilePath, - [Parameter (Mandatory=$false)] - #Encoding type used in the output file. Defaults to utf-8 as the typical encoding for xml - [ValidateSet("ascii", - "bigendianunicode", - "default", - "oem", - "string", - "unicode", - "unknown", - "utf32", - "utf7", - "utf8" - )] - $Encoding="utf8", - [Parameter (Mandatory=$False)] - #Prevents overwriting an existing file. Defaults to $True - [switch]$NoClobber=$True - ) - - begin{ - $XmlDoc = New-object System.Xml.XmlDocument + [Parameter (Mandatory = $true, ValueFromPipeline = $True)] + #PowerNSX Object to be exported + [System.Xml.XmlElement[]]$Object, + [Parameter (Mandatory = $true, Position = 1)] + #Text Encoding used in export file. + [ValidateNotNullOrEmpty()] + [String]$FilePath, + [Parameter (Mandatory = $false)] + #Encoding type used in the output file. Defaults to utf-8 as the typical encoding for xml + [ValidateSet("ascii", + "bigendianunicode", + "default", + "oem", + "string", + "unicode", + "unknown", + "utf32", + "utf7", + "utf8" + )] + $Encoding = "utf8", + [Parameter (Mandatory = $False)] + #Prevents overwriting an existing file. Defaults to $True + [switch]$NoClobber = $True + ) + + begin { + $XmlDoc = New-Object System.Xml.XmlDocument $ExportElem = $XmlDoc.CreateElement("PowerNSXExport") } - process{ + process { foreach ( $xml in $Object ) { $ExportNode = $XmlDoc.ImportNode($xml, $true) $null = $ExportElem.AppendChild($ExportNode) } } - End{ - $ExportElem | Format-xml | out-file -FilePath $FilePath -Encoding $Encoding -NoClobber:$NoClobber + End { + $ExportElem | Format-XML | Out-File -FilePath $FilePath -Encoding $Encoding -NoClobber:$NoClobber } } @@ -3727,20 +3725,20 @@ function Import-NsxObject { Param( - [Parameter (Mandatory=$true, Position=1)] - #Text Encoding used in export file. - [ValidateScript( - {if ( -not (test-path $_)) { + [Parameter (Mandatory = $true, Position = 1)] + #Text Encoding used in export file. + [ValidateScript( + { if ( -not (Test-Path $_)) { Throw "File not found : $_" } - else { - $True - }} - )] - [String]$FilePath + else { + $True + } } + )] + [String]$FilePath ) - begin{ + begin { $XmlDoc = New-Object System.Xml.XmlDocument try { @@ -3750,11 +3748,11 @@ function Import-NsxObject { Throw "An error occured attempting to load the file $filepath. Ensure the file contains a valid PowerNSX object export and has not been modified or corrupted. $_" } - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlDoc -Query "/PowerNSXExport")) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlDoc -query "/PowerNSXExport")) { Throw "The XML content in $filepath is not a valid PowerNSX export format." } - $Children = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $xmldoc.PowerNSXExport -Query "*") + $Children = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $xmldoc.PowerNSXExport -query "*") foreach ($child in $Children) { $child @@ -3762,7 +3760,7 @@ function Import-NsxObject { } Process {} - End{} + End {} } @@ -3771,7 +3769,7 @@ function Import-NsxObject { # Core functions function Invoke-InternalWebRequest { - <# + <# .SYNOPSIS Constructs and performs REST call to NSX API while hiding platform specific limitations. @@ -3785,28 +3783,28 @@ function Invoke-InternalWebRequest { #> [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] #Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] #Cant remove without breaking backward compatibility param ( [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [Uri]$Uri, + [ValidateNotNullOrEmpty()] + [Uri]$Uri, [parameter(Mandatory = $true)] - [ValidateSet("get", "put", "post", "delete")] - [string]$Method, + [ValidateSet("get", "put", "post", "delete")] + [string]$Method, [parameter(Mandatory = $true)] - [hashtable]$Headers=@{}, + [hashtable]$Headers = @{}, [parameter(Mandatory = $true)] - [string]$ContentType, + [string]$ContentType, [parameter(Mandatory = $true)] - [int]$TimeoutSec=0, + [int]$TimeoutSec = 0, [parameter(Mandatory = $false)] - [string]$body, + [string]$body, [parameter(Mandatory = $false)] - [switch]$SkipCertificateCheck=$true + [switch]$SkipCertificateCheck = $true ) - write-debug "$($MyInvocation.MyCommand.Name) : Method : $method, Content-Type : $ContentType, SkipCertificateCheck : $SkipcertificateCheck" + Write-Debug "$($MyInvocation.MyCommand.Name) : Method : $method, Content-Type : $ContentType, SkipCertificateCheck : $SkipcertificateCheck" ################### # Below removed to fix Issue #215, Remove-NsxCluster (DELETE /2.0/nwfabric/configure) sends a body with a delete. @@ -3827,31 +3825,30 @@ function Invoke-InternalWebRequest { #Add any required headers. if-match in particular doesnt validate on httpclient. Using TryAddWithoutValidation to avoid exception thrown on Core. foreach ( $header in $headerDictionary.Keys) { - write-debug "$($MyInvocation.MyCommand.Name) : Adding Header : $header, $($headerDictionary.Item($header))" + Write-Debug "$($MyInvocation.MyCommand.Name) : Adding Header : $header, $($headerDictionary.Item($header))" $null = $httpClient.DefaultRequestHeaders.TryAddWithoutValidation( $header, $headerDictionary.item($header) ) } #Set Timeout - if ( $timeout -ne 0 ){ - $httpClient.Timeout = new-object Timespan(0,0,$TimeoutSec) + if ( $timeout -ne 0 ) { + $httpClient.Timeout = New-Object Timespan(0, 0, $TimeoutSec) } else { $httpClient.Timeout = [timespan]::MaxValue } #Encoding - $UTF8 = new-object System.Text.UTF8Encoding - try - { - write-debug "$($MyInvocation.MyCommand.Name) : Calling HTTPClient SendAsync" + $UTF8 = New-Object System.Text.UTF8Encoding + try { + Write-Debug "$($MyInvocation.MyCommand.Name) : Calling HTTPClient SendAsync" - $request = new-object System.Net.Http.HttpRequestMessage + $request = New-Object System.Net.Http.HttpRequestMessage $request.Method = $method.ToUpper() $request.RequestUri = $Uri $content = $null if ( $PSBoundParameters.ContainsKey("Body")) { $content = New-Object System.Net.Http.StringContent($body, $UTF8, $contentType) - write-debug "$($MyInvocation.MyCommand.Name) : Content Header $($content.Headers | out-string -stream)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Content Header $($content.Headers | Out-String -Stream)" } $request.Content = $content $task = $httpClient.SendAsync($request); @@ -3862,7 +3859,7 @@ function Invoke-InternalWebRequest { $response = $task.Result #Generate lookalike webresponseobject - caller is me, so it doesnt need to pass too close an inspection! - $WebResponse = new-object InternalWebResponse + $WebResponse = New-Object InternalWebResponse $WebResponse.StatusCode = $response.StatusCode.value__ $WebResponse.StatusDescription = $response.ReasonPhrase $WebResponse.Content = $response.Content.ReadAsStringAsync().Result @@ -3906,22 +3903,22 @@ function Invoke-InternalWebRequest { } $WebResponse } - catch [Exception]{ + catch [Exception] { # if ( $gettask.Exception ) { # throw $gettask.Exception # } # else { - $PSCmdlet.ThrowTerminatingError($_) + $PSCmdlet.ThrowTerminatingError($_) # } } - finally{ - if ( test-path variable:httpClient ) { + finally { + if ( Test-Path variable:httpClient ) { $httpClient.Dispose() } - if( test-path variable:response ){ + if ( Test-Path variable:response ) { $response.Dispose() } - if ( test-path variable:content ) { + if ( Test-Path variable:content ) { if ( $content -ne $null ) { $content.dispose() } @@ -3933,16 +3930,16 @@ function Invoke-InternalWebRequest { #For now, we continue to pass thru to the iwr cmdlet on desktop. For now... #Use splatting to build up the IWR params $iwrSplat = @{ - "method" = $method; - "headers" = $headerDictionary; - "ContentType" = $ContentType; - "uri" = $Uri; - "TimeoutSec" = $TimeoutSec; + "method" = $method; + "headers" = $headerDictionary; + "ContentType" = $ContentType; + "uri" = $Uri; + "TimeoutSec" = $TimeoutSec; "UseBasicParsing" = $True; } if ( $PsBoundParameters.ContainsKey('Body')) { - $iwrsplat.Add("body",$body) + $iwrsplat.Add("body", $body) } if (( -not $ValidateCertificate) -and ([System.Net.ServicePointManager]::CertificatePolicy.tostring() -ne 'TrustAllCertsPolicy')) { @@ -3951,7 +3948,7 @@ function Invoke-InternalWebRequest { } #Dont catch here - bubble exception up as there is enough in it for the caller. - invoke-webrequest @iwrsplat + Invoke-WebRequest @iwrsplat } } @@ -3992,49 +3989,49 @@ function Invoke-NsxRestMethod { #> - [CmdletBinding(DefaultParameterSetName="ConnectionObj")] - - param ( - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #PSCredential object containing authentication details to be used for connection to NSX Manager API - [System.Management.Automation.PSCredential]$cred, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #NSX Manager ip address or FQDN - [string]$server, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #TCP Port on -server to connect to - [int]$port, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #Protocol - HTTP/HTTPS - [string]$protocol, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #URI Prefix to support URI rewrite scenario - [AllowEmptyString()] - [string]$UriPrefix="", - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #Validates the certificate presented by NSX Manager for HTTPS connections - [bool]$ValidateCertificate, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - [Parameter (ParameterSetName="ConnectionObj")] - #REST method of call. Get, Put, Post, Delete, Patch etc - [string]$method, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - [Parameter (ParameterSetName="ConnectionObj")] - #URI of resource (/api/1.0/myresource). Should not include protocol, server or port. - [string]$URI, - [Parameter (Mandatory=$false,ParameterSetName="Parameter")] - [Parameter (ParameterSetName="ConnectionObj")] - #Content to be sent to server when method is Put/Post/Patch - [string]$body = "", - [Parameter (Mandatory=$false,ParameterSetName="ConnectionObj")] - #Pre-populated connection object as returned by Connect-NsxServer - [psObject]$connection, - [Parameter (Mandatory=$false,ParameterSetName="ConnectionObj")] - #Hashtable collection of KV pairs representing additional headers to send to the NSX Manager during REST call - [System.Collections.Hashtable]$extraheader, - [Parameter (Mandatory=$false,ParameterSetName="ConnectionObj")] - #Request timeout value - passed directly to underlying invoke-restmethod call - [int]$Timeout=600 + [CmdletBinding(DefaultParameterSetName = "ConnectionObj")] + + param ( + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #PSCredential object containing authentication details to be used for connection to NSX Manager API + [System.Management.Automation.PSCredential]$cred, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #NSX Manager ip address or FQDN + [string]$server, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #TCP Port on -server to connect to + [int]$port, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #Protocol - HTTP/HTTPS + [string]$protocol, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #URI Prefix to support URI rewrite scenario + [AllowEmptyString()] + [string]$UriPrefix = "", + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #Validates the certificate presented by NSX Manager for HTTPS connections + [bool]$ValidateCertificate, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + [Parameter (ParameterSetName = "ConnectionObj")] + #REST method of call. Get, Put, Post, Delete, Patch etc + [string]$method, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + [Parameter (ParameterSetName = "ConnectionObj")] + #URI of resource (/api/1.0/myresource). Should not include protocol, server or port. + [string]$URI, + [Parameter (Mandatory = $false, ParameterSetName = "Parameter")] + [Parameter (ParameterSetName = "ConnectionObj")] + #Content to be sent to server when method is Put/Post/Patch + [string]$body = "", + [Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")] + #Pre-populated connection object as returned by Connect-NsxServer + [psObject]$connection, + [Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")] + #Hashtable collection of KV pairs representing additional headers to send to the NSX Manager during REST call + [System.Collections.Hashtable]$extraheader, + [Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")] + #Request timeout value - passed directly to underlying invoke-restmethod call + [int]$Timeout = 600 ) Write-Debug "$($MyInvocation.MyCommand.Name) : ParameterSetName : $($pscmdlet.ParameterSetName)" @@ -4053,7 +4050,7 @@ function Invoke-NsxRestMethod { if ( $connection -eq $null) { #Now we need to assume that defaultnsxconnection does not exist... - if ( -not (test-path variable:global:DefaultNSXConnection) ) { + if ( -not (Test-Path variable:global:DefaultNSXConnection) ) { throw "Not connected. Connect to NSX manager with Connect-NsxServer first." } else { @@ -4079,10 +4076,10 @@ function Invoke-NsxRestMethod { if ( $extraHeader ) { foreach ($header in $extraHeader.GetEnumerator()) { - write-debug "$($MyInvocation.MyCommand.Name) : Adding extra header $($header.Key ) : $($header.Value)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Adding extra header $($header.Key ) : $($header.Value)" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) Extra Header being added to following REST call. Key: $($Header.Key), Value: $($Header.Value)" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) Extra Header being added to following REST call. Key: $($Header.Key), Value: $($Header.Value)" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } $headerDictionary.add($header.Key, $header.Value) @@ -4090,27 +4087,27 @@ function Invoke-NsxRestMethod { } $FullURI = "$($protocol)://$($server):$($Port)$($UriPrefix)$($URI)" - write-debug "$($MyInvocation.MyCommand.Name) : Method: $method, URI: $FullURI, URIPrefix: $UriPrefix, Body: `n$($body | Format-Xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Method: $method, URI: $FullURI, URIPrefix: $UriPrefix, Body: `n$($body | Format-XML)" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager via invoke-restmethod : Method: $method, URI: $FullURI, Body: `n$($body | Format-Xml)" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager via invoke-restmethod : Method: $method, URI: $FullURI, Body: `n$($body | Format-XML)" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } #Use splatting to build up the IRM params $irmSplat = @{ - "method" = $method; - "headers" = $headerDictionary; + "method" = $method; + "headers" = $headerDictionary; "ContentType" = "application/xml"; - "uri" = $FullURI; - "TimeoutSec" = $Timeout + "uri" = $FullURI; + "TimeoutSec" = $Timeout #Not supported on PowerShell 3 # "UseBasicParsing" = $True } if ( $PsBoundParameters.ContainsKey('Body')) { # If there is a body specified, add it to the invoke-restmethod args... - $irmSplat.Add("body",$body) + $irmSplat.Add("body", $body) } #Core (for now) uses a different mechanism to manipulating [System.Net.ServicePointManager]::CertificatePolicy @@ -4120,16 +4117,16 @@ function Invoke-NsxRestMethod { #do rest call try { - $response = invoke-restmethod @irmSplat + $response = Invoke-RestMethod @irmSplat } - #If its a webexception, we may have got a response from the server with more information... + #If its a webexception, we may have got a response from the server with more information... #Even if this happens on PoSH Core though, the ex is not a webexception and we cant get this info :( catch [System.Net.WebException] { #Check if there is a response populated in the response prop as we can return better detail. $response = $_.exception.response if ( $response ) { - $responseStream = $response.GetResponseStream() + $responseStream = $response.GetResponseStream() $reader = New-Object system.io.streamreader($responseStream) $responseBody = $reader.readtoend() $ErrorString = "$($MyInvocation.MyCommand.Name) : The NSX API response received indicates a failure. $($response.StatusCode.value__) : $($response.StatusDescription) : Response Body: $($responseBody)" @@ -4137,7 +4134,7 @@ function Invoke-NsxRestMethod { #Log the error with response detail. if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager failed: $ErrorString" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager failed: $ErrorString" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } throw $ErrorString @@ -4147,33 +4144,33 @@ function Invoke-NsxRestMethod { $ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager failed: $ErrorString" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager failed: $ErrorString" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } throw $_.exception.tostring() } } catch { - #Not a webexception (may be on PoSH core), log and throw the underlying ex string + #Not a webexception (may be on PoSH core), log and throw the underlying ex string $ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager failed: $ErrorString" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager failed: $ErrorString" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } throw $_.exception.tostring() } switch ( $response ) { - { $_ -is [xml] } { $FormattedResponse = "`n$($response.outerxml | Format-Xml)" } + { $_ -is [xml] } { $FormattedResponse = "`n$($response.outerxml | Format-XML)" } { $_ -is [System.String] } { $FormattedResponse = $response } default { $formattedResponse = "Response type unknown" } } - write-debug "$($MyInvocation.MyCommand.Name) : Response: $FormattedResponse" + Write-Debug "$($MyInvocation.MyCommand.Name) : Response: $FormattedResponse" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) Response: $FormattedResponse" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) Response: $FormattedResponse" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } @@ -4184,8 +4181,8 @@ function Invoke-NsxRestMethod { # and probably rewrite over time to use invoke-webrequest for all calls... PiTA!!!! :| $ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($FullURI) - $ServicePoint.CloseConnectionGroup("") | out-null - write-debug "$($MyInvocation.MyCommand.Name) : Closing connections to $FullURI." + $ServicePoint.CloseConnectionGroup("") | Out-Null + Write-Debug "$($MyInvocation.MyCommand.Name) : Closing connections to $FullURI." } #Return @@ -4224,49 +4221,49 @@ function Invoke-NsxWebRequest { #> - [CmdletBinding(DefaultParameterSetName="ConnectionObj")] - - param ( - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #PSCredential object containing authentication details to be used for connection to NSX Manager API - [System.Management.Automation.PSCredential]$cred, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #NSX Manager ip address or FQDN - [string]$server, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #TCP Port on -server to connect to - [int]$port, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #Protocol - HTTP/HTTPS - [string]$protocol, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #URI prefix to support URI rewrite scenario - [AllowEmptyString()] - [string]$UriPrefix="", - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - #Validates the certificate presented by NSX Manager for HTTPS connections - [bool]$ValidateCertificate, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - [Parameter (ParameterSetName="ConnectionObj")] - #REST method of call. Get, Put, Post, Delete, Patch etc - [string]$method, - [Parameter (Mandatory=$true,ParameterSetName="Parameter")] - [Parameter (ParameterSetName="ConnectionObj")] - #URI of resource (/api/1.0/myresource). Should not include protocol, server or port. - [string]$URI, - [Parameter (Mandatory=$false,ParameterSetName="Parameter")] - [Parameter (ParameterSetName="ConnectionObj")] - #Content to be sent to server when method is Put/Post/Patch - [string]$body = "", - [Parameter (Mandatory=$false,ParameterSetName="ConnectionObj")] - #Pre-populated connection object as returned by Connect-NsxServer - [psObject]$connection, - [Parameter (Mandatory=$false,ParameterSetName="ConnectionObj")] - #Hashtable collection of KV pairs representing additional headers to send to the NSX Manager during REST call - [System.Collections.Hashtable]$extraheader, - [Parameter (Mandatory=$false,ParameterSetName="ConnectionObj")] - #Request timeout value - passed directly to underlying invoke-restmethod call - [int]$Timeout=600 + [CmdletBinding(DefaultParameterSetName = "ConnectionObj")] + + param ( + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #PSCredential object containing authentication details to be used for connection to NSX Manager API + [System.Management.Automation.PSCredential]$cred, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #NSX Manager ip address or FQDN + [string]$server, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #TCP Port on -server to connect to + [int]$port, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #Protocol - HTTP/HTTPS + [string]$protocol, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #URI prefix to support URI rewrite scenario + [AllowEmptyString()] + [string]$UriPrefix = "", + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + #Validates the certificate presented by NSX Manager for HTTPS connections + [bool]$ValidateCertificate, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + [Parameter (ParameterSetName = "ConnectionObj")] + #REST method of call. Get, Put, Post, Delete, Patch etc + [string]$method, + [Parameter (Mandatory = $true, ParameterSetName = "Parameter")] + [Parameter (ParameterSetName = "ConnectionObj")] + #URI of resource (/api/1.0/myresource). Should not include protocol, server or port. + [string]$URI, + [Parameter (Mandatory = $false, ParameterSetName = "Parameter")] + [Parameter (ParameterSetName = "ConnectionObj")] + #Content to be sent to server when method is Put/Post/Patch + [string]$body = "", + [Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")] + #Pre-populated connection object as returned by Connect-NsxServer + [psObject]$connection, + [Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")] + #Hashtable collection of KV pairs representing additional headers to send to the NSX Manager during REST call + [System.Collections.Hashtable]$extraheader, + [Parameter (Mandatory = $false, ParameterSetName = "ConnectionObj")] + #Request timeout value - passed directly to underlying invoke-restmethod call + [int]$Timeout = 600 ) Write-Debug "$($MyInvocation.MyCommand.Name) : ParameterSetName : $($pscmdlet.ParameterSetName)" @@ -4277,7 +4274,7 @@ function Invoke-NsxWebRequest { if ( $connection -eq $null) { #Now we need to assume that defaultnsxconnection does not exist... - if ( -not (test-path variable:global:DefaultNSXConnection) ) { + if ( -not (Test-Path variable:global:DefaultNSXConnection) ) { throw "Not connected. Connect to NSX manager with Connect-NsxServer first." } else { @@ -4303,10 +4300,10 @@ function Invoke-NsxWebRequest { if ( $extraHeader ) { foreach ($header in $extraHeader.GetEnumerator()) { - write-debug "$($MyInvocation.MyCommand.Name) : Adding extra header $($header.Key ) : $($header.Value)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Adding extra header $($header.Key ) : $($header.Value)" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) Extra Header being added to following REST call. Key: $($Header.Key), Value: $($Header.Value)" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) Extra Header being added to following REST call. Key: $($Header.Key), Value: $($Header.Value)" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } $headerDictionary.add($header.Key, $header.Value) @@ -4314,31 +4311,31 @@ function Invoke-NsxWebRequest { } $FullURI = "$($protocol)://$($server):$($Port)$($UriPrefix)$($URI)" - write-debug "$($MyInvocation.MyCommand.Name) : Method: $method, URI: $FullURI, URIPrefix: $URIPrefix, Body: `n$($body | Format-Xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Method: $method, URI: $FullURI, URIPrefix: $URIPrefix, Body: `n$($body | Format-XML)" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager via invoke-webrequest : Method: $method, URI: $FullURI, Body: `n$($body | Format-Xml)" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager via invoke-webrequest : Method: $method, URI: $FullURI, Body: `n$($body | Format-XML)" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } #Use splatting to build up the IWR params $iwrSplat = @{ - "Method" = $method; - "Headers" = $headerDictionary; - "ContentType" = "application/xml"; - "Uri" = $FullURI; - "TimeoutSec" = $Timeout; + "Method" = $method; + "Headers" = $headerDictionary; + "ContentType" = "application/xml"; + "Uri" = $FullURI; + "TimeoutSec" = $Timeout; "SkipCertificateCheck" = !$ValidateCertificate } if ( $PsBoundParameters.ContainsKey('Body')) { # If there is a body specified, add it to the invoke-restmethod args... - $iwrSplat.Add("body",$body) + $iwrSplat.Add("body", $body) } #do rest call try { - $response = invoke-internalwebrequest @iwrsplat + $response = invoke-internalwebrequest @iwrsplat } #If its a webexception, we may have got a response from the server with more information... #Even if this happens on PoSH Core though, the ex is not a webexception and we cant get this info :( @@ -4359,11 +4356,11 @@ function Invoke-NsxWebRequest { } if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager failed: $ErrorString" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager failed: $ErrorString" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } - $exc = New-object InternalNsxApiException $ErrorString, $_.exception + $exc = New-Object InternalNsxApiException $ErrorString, $_.exception $errorID = 'NsxAPIFailureResult' $errorCategory = 'InvalidResult' $targetObject = 'Invoke-NsxWebRequest' @@ -4383,11 +4380,11 @@ function Invoke-NsxWebRequest { #Log the error with response detail. if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager failed: $ErrorString" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager failed: $ErrorString" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } - $exc = New-object InternalNsxApiException $ErrorString, $_.exception + $exc = New-Object InternalNsxApiException $ErrorString, $_.exception $errorID = 'NsxAPIFailureResult' $errorCategory = 'InvalidResult' $targetObject = 'Invoke-NsxWebRequest' @@ -4399,10 +4396,10 @@ function Invoke-NsxWebRequest { $ErrorString = "$($MyInvocation.MyCommand.Name) : An unknown exception occured calling invoke-internalwebrequest. $($_.exception.tostring()) `nStackTrace:`n$($_.ScriptStackTrace)" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) REST Call to NSX Manager failed: $ErrorString" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) REST Call to NSX Manager failed: $ErrorString" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } - $exc = New-object InternalNsxApiException $ErrorString, $_.exception + $exc = New-Object InternalNsxApiException $ErrorString, $_.exception $errorID = 'NsxAPIFailureResult' $errorCategory = 'InvalidResult' $targetObject = 'Invoke-NsxWebRequest' @@ -4412,10 +4409,10 @@ function Invoke-NsxWebRequest { #Output the response header dictionary foreach ( $key in $response.Headers.Keys) { - write-debug "$($MyInvocation.MyCommand.Name) : Response header item : $Key = $($Response.Headers.Item($key))" + Write-Debug "$($MyInvocation.MyCommand.Name) : Response header item : $Key = $($Response.Headers.Item($key))" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) Response header item : $Key = $($Response.Headers.Item($key))" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) Response header item : $Key = $($Response.Headers.Item($key))" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } } @@ -4425,31 +4422,31 @@ function Invoke-NsxWebRequest { switch ( $response.content ) { { $_ -is [System.String] } { - write-debug "$($MyInvocation.MyCommand.Name) : Response Body: $($response.content)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Response Body: $($response.content)" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) Response Body: $($response.content)" | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) Response Body: $($response.content)" | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } } default { - write-debug "$($MyInvocation.MyCommand.Name) : Response type unknown" + Write-Debug "$($MyInvocation.MyCommand.Name) : Response type unknown" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) Response type unknown ( $($Response.Content.gettype()) )." | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) Response type unknown ( $($Response.Content.gettype()) )." | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } } } } else { - write-debug "$($MyInvocation.MyCommand.Name) : No response content" + Write-Debug "$($MyInvocation.MyCommand.Name) : No response content" if ( $pscmdlet.ParameterSetName -eq "ConnectionObj" ) { if ( $connection.DebugLogging ) { - "$(Get-Date -format s) No response content." | out-file -Append -FilePath $Connection.DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) No response content." | Out-File -Append -FilePath $Connection.DebugLogfile -Encoding utf8 } } } @@ -4579,89 +4576,89 @@ function Connect-NsxServer { vCenter using the credentials specified. #> - [CmdletBinding(DefaultParameterSetName="Legacy")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - param ( - [Parameter (Mandatory=$true, Position=1, ParameterSetName="Legacy")] - #NSX Manager address or FQDN. Deprecated. Use -vCenterServer with SSO credentials as preferred method, or -NsxServer with appliance admin user if required. - [ValidateNotNullOrEmpty()] - [string]$Server, - [Parameter (Mandatory=$true,ParameterSetName="NSXServer")] - #NSX Manager address or FQDN. Recommended method is to use -vCenterServer with SSO credentials. Use this for cmdlets requiring local appliance credentials(Appliance Management and Central CLI). - [ValidateNotNullOrEmpty()] - [string]$NsxServer, - [Parameter (Mandatory=$true, ParameterSetName="vCenterServer")] - #vCenter Server address or FQDN (not NSX Manager!). Used to determine NSX Server endpoint and authenticate using SSO credentials. Recommended method. - [ValidateNotNullOrEmpty()] - [string]$vCenterServer, - [Parameter (Mandatory=$false, ParameterSetName="vCenterServer")] - #NSX Manager address used to override that registered in vCenter. Used for scenarios where NSX manager is behind a NAT device. - [ValidateNotNullOrEmpty()] - [string]$NsxServerHint, - [Parameter (Mandatory=$false)] - #TCP Port to connect to on -Server - [ValidateRange(1,65535)] - [int]$Port=443, - [Parameter (Mandatory=$false)] - #PSCredential object containing NSX API authentication credentials - [PSCredential]$Credential, - [Parameter (Mandatory=$false)] - #Username used to authenticate to NSX API - [ValidateNotNullOrEmpty()] - [string]$Username, - [Parameter (Mandatory=$false)] - #Password used to authenticate to NSX API - [ValidateNotNullOrEmpty()] - [string]$Password="", - [Parameter (Mandatory=$false)] - #Validates the certificate presented by NSX Manager for HTTPS connections. Defaults to False - [ValidateNotNullOrEmpty()] - [switch]$ValidateCertificate=$false, - [Parameter (Mandatory=$false)] - #NSX API transport protocol - HTTPS / HTTP . Defaults to HTTPS - [ValidateNotNullOrEmpty()] - [string]$Protocol="https", - [Parameter (Mandatory=$false)] - #NSX API URI prefix. Supports reverse proxy in between client and NSX doing URI rewrites so that uri is prepended with $UriPrefix - [ValidateNotNullOrEmpty()] - [string]$UriPrefix="", - [Parameter (Mandatory=$false)] - #If True, the $DefaultNsxConnection global variable is created and populated with connection details. - #All PowerNSX commands that use the NSX API will utilise this connection unless they are called with the -connection parameter. - #Defaults to True - [bool]$DefaultConnection=$true, - [Parameter (Mandatory=$false)] - #If False, and a PowerCLI connection needs to be established to the registered vCenter, the Connect-ViServer call made by PowerNSX will specify the -NotDefault switch (see Get-Help Connect-ViServer) - #Defaults to True - [bool]$VIDefaultConnection=$true, - [Parameter (Mandatory=$false,ParameterSetName="Legacy")] - [Parameter (Mandatory=$false,ParameterSetName="NSXServer")] - #If True, and the PowerNSX connection attempt is successful, an automatic PowerCLI connection to the registered vCenter server is not attempted. Defaults to False. - [switch]$DisableVIAutoConnect=$false, - [Parameter (Mandatory=$false,ParameterSetName="Legacy")] - [Parameter (Mandatory=$false,ParameterSetName="NSXServer")] - #UserName used in PowerCLI connection to registered vCenter. - [string]$VIUserName, - [Parameter (Mandatory=$false,ParameterSetName="Legacy")] - [Parameter (Mandatory=$false,ParameterSetName="NSXServer")] - #Password used in PowerCLI connection to registered vCenter. - [string]$VIPassword="", - [Parameter (Mandatory=$false,ParameterSetName="Legacy")] - [Parameter (Mandatory=$false,ParameterSetName="NSXServer")] - #PSCredential object containing credentials used in PowerCLI connection to registered vCenter. - [Alias ("ViCred")] - [PSCredential]$VICredential, - [Parameter (Mandatory=$false)] - #Enable DebugLogging of all API calls to $DebugLogFile. Can be enabled on esisting connections with $connection.DebugLogging = $true. Defaults to False. - [switch]$DebugLogging=$false, - [Parameter (Mandatory=$false)] - #If DebugLogging is enabled, specifies the file to which output is written. Defaults to $Env:temp\PowerNSXLog-@-.log - [string]$DebugLogFile, - [Parameter (Mandatory=$false)] - #Supresses warning output from PowerCLI connection attempts (typically invalid Certificate warnings) - [ValidateSet("Continue","Ignore")] - [string]$ViWarningAction="Continue" + [CmdletBinding(DefaultParameterSetName = "Legacy")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + param ( + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "Legacy")] + #NSX Manager address or FQDN. Deprecated. Use -vCenterServer with SSO credentials as preferred method, or -NsxServer with appliance admin user if required. + [ValidateNotNullOrEmpty()] + [string]$Server, + [Parameter (Mandatory = $true, ParameterSetName = "NSXServer")] + #NSX Manager address or FQDN. Recommended method is to use -vCenterServer with SSO credentials. Use this for cmdlets requiring local appliance credentials(Appliance Management and Central CLI). + [ValidateNotNullOrEmpty()] + [string]$NsxServer, + [Parameter (Mandatory = $true, ParameterSetName = "vCenterServer")] + #vCenter Server address or FQDN (not NSX Manager!). Used to determine NSX Server endpoint and authenticate using SSO credentials. Recommended method. + [ValidateNotNullOrEmpty()] + [string]$vCenterServer, + [Parameter (Mandatory = $false, ParameterSetName = "vCenterServer")] + #NSX Manager address used to override that registered in vCenter. Used for scenarios where NSX manager is behind a NAT device. + [ValidateNotNullOrEmpty()] + [string]$NsxServerHint, + [Parameter (Mandatory = $false)] + #TCP Port to connect to on -Server + [ValidateRange(1, 65535)] + [int]$Port = 443, + [Parameter (Mandatory = $false)] + #PSCredential object containing NSX API authentication credentials + [PSCredential]$Credential, + [Parameter (Mandatory = $false)] + #Username used to authenticate to NSX API + [ValidateNotNullOrEmpty()] + [string]$Username, + [Parameter (Mandatory = $false)] + #Password used to authenticate to NSX API + [ValidateNotNullOrEmpty()] + [string]$Password = "", + [Parameter (Mandatory = $false)] + #Validates the certificate presented by NSX Manager for HTTPS connections. Defaults to False + [ValidateNotNullOrEmpty()] + [switch]$ValidateCertificate = $false, + [Parameter (Mandatory = $false)] + #NSX API transport protocol - HTTPS / HTTP . Defaults to HTTPS + [ValidateNotNullOrEmpty()] + [string]$Protocol = "https", + [Parameter (Mandatory = $false)] + #NSX API URI prefix. Supports reverse proxy in between client and NSX doing URI rewrites so that uri is prepended with $UriPrefix + [ValidateNotNullOrEmpty()] + [string]$UriPrefix = "", + [Parameter (Mandatory = $false)] + #If True, the $DefaultNsxConnection global variable is created and populated with connection details. + #All PowerNSX commands that use the NSX API will utilise this connection unless they are called with the -connection parameter. + #Defaults to True + [bool]$DefaultConnection = $true, + [Parameter (Mandatory = $false)] + #If False, and a PowerCLI connection needs to be established to the registered vCenter, the Connect-ViServer call made by PowerNSX will specify the -NotDefault switch (see Get-Help Connect-ViServer) + #Defaults to True + [bool]$VIDefaultConnection = $true, + [Parameter (Mandatory = $false, ParameterSetName = "Legacy")] + [Parameter (Mandatory = $false, ParameterSetName = "NSXServer")] + #If True, and the PowerNSX connection attempt is successful, an automatic PowerCLI connection to the registered vCenter server is not attempted. Defaults to False. + [switch]$DisableVIAutoConnect = $false, + [Parameter (Mandatory = $false, ParameterSetName = "Legacy")] + [Parameter (Mandatory = $false, ParameterSetName = "NSXServer")] + #UserName used in PowerCLI connection to registered vCenter. + [string]$VIUserName, + [Parameter (Mandatory = $false, ParameterSetName = "Legacy")] + [Parameter (Mandatory = $false, ParameterSetName = "NSXServer")] + #Password used in PowerCLI connection to registered vCenter. + [string]$VIPassword = "", + [Parameter (Mandatory = $false, ParameterSetName = "Legacy")] + [Parameter (Mandatory = $false, ParameterSetName = "NSXServer")] + #PSCredential object containing credentials used in PowerCLI connection to registered vCenter. + [Alias ("ViCred")] + [PSCredential]$VICredential, + [Parameter (Mandatory = $false)] + #Enable DebugLogging of all API calls to $DebugLogFile. Can be enabled on esisting connections with $connection.DebugLogging = $true. Defaults to False. + [switch]$DebugLogging = $false, + [Parameter (Mandatory = $false)] + #If DebugLogging is enabled, specifies the file to which output is written. Defaults to $Env:temp\PowerNSXLog-@-.log + [string]$DebugLogFile, + [Parameter (Mandatory = $false)] + #Supresses warning output from PowerCLI connection attempts (typically invalid Certificate warnings) + [ValidateSet("Continue", "Ignore")] + [string]$ViWarningAction = "Continue" ) function TestvCenterConn { @@ -4673,7 +4670,7 @@ function Connect-NsxServer { $ConnectedViServerConnection = $null - if ((test-path variable:global:DefaultVIServer )) { + if ((Test-Path variable:global:DefaultVIServer )) { #Already have a PowerCLI connection - is it to the right place? @@ -4685,17 +4682,17 @@ function Connect-NsxServer { #Remembering we can have multiple vCenter connections too :| :outer foreach ( $VIServerConnection in $global:DefaultVIServer ) { - $ExistingVIConnectionIPs = [System.Net.Dns]::GetHostAddressesAsync($VIServerConnection.Name).Result + $ExistingVIConnectionIPs = [System.Net.Dns]::GetHostAddressesAsync($VIServerConnection.Name).Result foreach ( $ExistingVIConnectionIP in [IpAddress[]]$ExistingVIConnectionIPs ) { foreach ( $RegisteredvCenterIP in [IpAddress[]]$RegisteredvCenterIPs ) { if ( $ExistingVIConnectionIP -eq $RegisteredvCenterIP ) { if ( $VIServerConnection.IsConnected ) { $ConnectedViServerConnection = $ViServerConnection - write-host -foregroundcolor Green "Using existing PowerCLI connection to $($ExistingVIConnectionIP.IPAddresstoString)" + Write-Host -ForegroundColor Green "Using existing PowerCLI connection to $($ExistingVIConnectionIP.IPAddresstoString)" break outer } else { - write-host -foregroundcolor Yellow "Existing PowerCLI connection to $($ExistingVIConnectionIP.IPAddresstoString) is not connected." + Write-Host -ForegroundColor Yellow "Existing PowerCLI connection to $($ExistingVIConnectionIP.IPAddresstoString) is not connected." } } } @@ -4708,9 +4705,9 @@ function Connect-NsxServer { #Legacy mode warning if ( $PSCmdlet.ParameterSetName -eq "Legacy") { - write-warning "The -Server parameter in Connect-NsxServer is deprecated and will be made non-default in a future release." - write-warning "Recommended usage of Connect-NsxServer is to use the -vCenterServer parameter and valid SSO credentials (requires rights of at least Read-Only over vCenter Inventory and NSX Auditor role)." - write-warning "Use the -NsxServer parameter to continue using direct connection to NSX and either appliance local or Enterprise_Administrator (only) level SSO credentials." + Write-Warning "The -Server parameter in Connect-NsxServer is deprecated and will be made non-default in a future release." + Write-Warning "Recommended usage of Connect-NsxServer is to use the -vCenterServer parameter and valid SSO credentials (requires rights of at least Read-Only over vCenter Inventory and NSX Auditor role)." + Write-Warning "Use the -NsxServer parameter to continue using direct connection to NSX and either appliance local or Enterprise_Administrator (only) level SSO credentials." $NsxServer = $Server } #Preclude certain param combinations that we dont want to accept. @@ -4728,7 +4725,7 @@ function Connect-NsxServer { #Build cred object for default auth if user specified username/pass if ($PsBoundParameters.ContainsKey("UserName")) { - $Credential = new-object System.Management.Automation.PSCredential($Username, $(ConvertTo-SecureString $Password -AsPlainText -Force)) + $Credential = New-Object System.Management.Automation.PSCredential($Username, $(ConvertTo-SecureString $Password -AsPlainText -Force)) } elseif ( -not $PSBoundParameters.ContainsKey("Credential")) { @@ -4745,12 +4742,12 @@ function Connect-NsxServer { if ( -not $PsBoundParameters.ContainsKey('DebugLogFile' )) { #Generating logfile name regardless of initial user pref on debug. They can just flip the prop on the connection object at a later date to start logging... - $dtstring = get-date -format "yyyy_MM_dd_HH_mm_ss" + $dtstring = Get-Date -Format "yyyy_MM_dd_HH_mm_ss" $DebugLogFile = "$($env:TEMP)\PowerNSXLog-$($Credential.UserName)@$NSXServer-$dtstring.log" } #If debug is on, need to test we can create the debug file first and throw if not... - if ( $DebugLogging -and (-not ( new-item -path $DebugLogFile -Type file ))) { Throw "Unable to create logfile $DebugLogFile. Disable debugging or specify a valid DebugLogFile name."} + if ( $DebugLogging -and (-not ( New-Item -Path $DebugLogFile -Type file ))) { Throw "Unable to create logfile $DebugLogFile. Disable debugging or specify a valid DebugLogFile name." } #Defaults for vars we may not be able to set on the resulting connection object... $version = $null $buildnumber = $null @@ -4764,7 +4761,7 @@ function Connect-NsxServer { #Even though there is partial version info available in the feature info - we cant get the manager version from here, so Im reluctant to return anything. try { - $response = invoke-nsxrestmethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -uri $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix + $response = Invoke-NsxRestMethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -URI $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix } catch { Throw "Connection to NSX server $NsxServer failed : $_" @@ -4775,7 +4772,7 @@ function Connect-NsxServer { #Test NSX connection try { - $response = invoke-nsxrestmethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -uri $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix + $response = Invoke-NsxRestMethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -URI $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix # try to populate version information @@ -4795,7 +4792,7 @@ function Connect-NsxServer { } } else { - if ( get-member -InputObject $response -MemberType NoteProperty -Name versionInfo ) { + if ( Get-Member -InputObject $response -MemberType NoteProperty -Name versionInfo ) { $Version = $response.VersionInfo.majorVersion + "." + $response.VersionInfo.minorVersion + "." + $response.VersionInfo.patchVersion $BuildNumber = $response.VersionInfo.BuildNumber } @@ -4805,7 +4802,7 @@ function Connect-NsxServer { #supression excep in event of 403. Valid non local account credentias are not able to query the appliance-management API if ( $_ -match '403 : Forbidden|403 \(Forbidden\)') { - write-warning "A valid local admin account is required to access version information. This warning can be ignored if using SSO credentials to authenticate to NSX, however, appliance version information will not be available in the connection object. Use Connect-NsxServer -VCServer to avoid this warning." + Write-Warning "A valid local admin account is required to access version information. This warning can be ignored if using SSO credentials to authenticate to NSX, however, appliance version information will not be available in the connection object. Use Connect-NsxServer -VCServer to avoid this warning." # write-warning "A valid local admin account is required to access version information. This warning can be ignored if using SSO credentials to authenticate to NSX, however, appliance version information will not be available in the connection object." } else { @@ -4816,22 +4813,22 @@ function Connect-NsxServer { #Try and get the registered VC info from NSX so we can build a VIconnection... try { $URI = "/api/2.0/services/vcconfig" - $vcInfo = Invoke-NsxRestMethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -uri $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix - if ( $DebugLogging ) { "$(Get-Date -format s) New PowerNSX Connection to $($credential.UserName)@$($Protocol)://$($NsxServer):$port, version $($Connection.Version)" | out-file -Append -FilePath $DebugLogfile -Encoding utf8 } + $vcInfo = Invoke-NsxRestMethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -URI $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix + if ( $DebugLogging ) { "$(Get-Date -Format s) New PowerNSX Connection to $($credential.UserName)@$($Protocol)://$($NsxServer):$port, version $($Connection.Version)" | Out-File -Append -FilePath $DebugLogfile -Encoding utf8 } } catch { #Catch a forbidden as we may not be using an admin account - in which case, we cant query NSX for the registered vC... if ( $_ -match '403 : Forbidden|403 \(Forbidden\)') { - write-warning "The credentials used are not sufficiently privileged to be able to query NSX for the registered vCenter Server. Use Connect-NsxServer -VCServer to avoid this warning." + Write-Warning "The credentials used are not sufficiently privileged to be able to query NSX for the registered vCenter Server. Use Connect-NsxServer -VCServer to avoid this warning." } else { $_ } } - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $vcinfo -Query 'descendant::vcInfo/ipAddress')) { - if ( $DebugLogging ) { "$(Get-Date -format s) NSX Manager $NsxServer is not currently connected to any vCenter..." | out-file -Append -FilePath $DebugLogfile -Encoding utf8 } - write-warning "NSX Manager does not currently have a vCenter registration. Use Set-NsxManager to register a vCenter server." + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $vcinfo -query 'descendant::vcInfo/ipAddress')) { + if ( $DebugLogging ) { "$(Get-Date -Format s) NSX Manager $NsxServer is not currently connected to any vCenter..." | Out-File -Append -FilePath $DebugLogfile -Encoding utf8 } + Write-Warning "NSX Manager does not currently have a vCenter registration. Use Set-NsxManager to register a vCenter server." } else { $RegisteredvCenterIP = $vcInfo.vcInfo.ipAddress @@ -4849,7 +4846,7 @@ function Connect-NsxServer { #Ask the question and get creds. - $message = "PowerNSX requires a PowerCLI connection to the vCenter server NSX is registered against for proper operation." + $message = "PowerNSX requires a PowerCLI connection to the vCenter server NSX is registered against for proper operation." $question = "Automatically create PowerCLI connection to $($RegisteredvCenterIP)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -4861,20 +4858,20 @@ function Connect-NsxServer { } if ( $decision -eq 0 ) { - write-host - write-warning "Enter credentials for vCenter $RegisteredvCenterIP" - $VICredential = get-credential + Write-Host + Write-Warning "Enter credentials for vCenter $RegisteredvCenterIP" + $VICredential = Get-Credential $VIConnection = Connect-VIServer -Credential $VICredential $RegisteredvCenterIP -NotDefault:(-not $VIDefaultConnection) -WarningAction:$ViWarningAction } else { - write-host - write-warning "Some PowerNSX cmdlets will not be fully functional without a valid PowerCLI connection to vCenter server $RegisteredvCenterIP" + Write-Host + Write-Warning "Some PowerNSX cmdlets will not be fully functional without a valid PowerCLI connection to vCenter server $RegisteredvCenterIP" } } else { #User specified VI username/pwd or VI cred. Connect automatically to the registered vCenter - write-host "Creating PowerCLI connection to vCenter server $RegisteredvCenterIP" + Write-Host "Creating PowerCLI connection to vCenter server $RegisteredvCenterIP" if ( $VICredential ) { $VIConnection = Connect-VIServer -Credential $VICredential $RegisteredvCenterIP -NotDefault:(-not $VIDefaultConnection) -WarningAction:$ViWarningAction @@ -4885,7 +4882,7 @@ function Connect-NsxServer { } } if ( $DebugLogging ) { - "$(Get-Date -format s) NSX Manager $NsxServer is registered against vCenter server $RegisteredvCenterIP. PowerCLI connection established to registered vCenter : $(if ($ViConnection ) { $VIConnection.IsConnected } else { "False" })" | out-file -Append -FilePath $DebugLogfile -Encoding utf8 + "$(Get-Date -Format s) NSX Manager $NsxServer is registered against vCenter server $RegisteredvCenterIP. PowerCLI connection established to registered vCenter : $(if ($ViConnection ) { $VIConnection.IsConnected } else { "False" })" | Out-File -Append -FilePath $DebugLogfile -Encoding utf8 } } } @@ -4896,10 +4893,10 @@ function Connect-NsxServer { #Connect to specified VC using 'default credentials... $VIConnection = TestvCenterConn -RegisteredvCenterIp $vCenterServer if ( -not $VIConnection ) { - $VIConnection = Connect-VIServer -Credential $Credential -server $vCenterServer -NotDefault:(-not $VIDefaultConnection) -WarningAction:$ViWarningAction -erroraction Stop + $VIConnection = Connect-VIServer -Credential $Credential -Server $vCenterServer -NotDefault:(-not $VIDefaultConnection) -WarningAction:$ViWarningAction -ErrorAction Stop } $ExtensionManager = Get-View ExtensionManager -Server $ViConnection - $NSXExtension = $ExtensionManager.ExtensionList | where-object { $_.key -eq 'com.vmware.vShieldManager' } + $NSXExtension = $ExtensionManager.ExtensionList | Where-Object { $_.key -eq 'com.vmware.vShieldManager' } if ( -not $NSXExtension ) { throw "The connected vCenter server does not have a registered NSX solution." } @@ -4950,7 +4947,7 @@ function Connect-NsxServer { #Now we simply test the connection to NSX against a random unprivileged URI $URI = "/api/2.0/nwfabric/features" try { - $response = invoke-nsxrestmethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -uri $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix + $response = Invoke-NsxRestMethod -cred $Credential -server $NsxServer -port $port -protocol $Protocol -method "get" -URI $URI -ValidateCertificate:$ValidateCertificate -UriPrefix $uriprefix } catch { Throw "Connection to NSX server $NsxServer failed : $_" @@ -4959,21 +4956,21 @@ function Connect-NsxServer { #Setup the connection object $connection = [pscustomObject] @{ - "Version" = $version - "BuildNumber" = $BuildNumber - "Credential" = $Credential - "Server" = $NSXServer - "Port" = $port - "Protocol" = $Protocol - "UriPrefix" = $UriPrefix + "Version" = $version + "BuildNumber" = $BuildNumber + "Credential" = $Credential + "Server" = $NSXServer + "Port" = $port + "Protocol" = $Protocol + "UriPrefix" = $UriPrefix "ValidateCertificate" = $ValidateCertificate - "VIConnection" = $ViConnection - "DebugLogging" = $DebugLogging - "DebugLogfile" = $DebugLogFile + "VIConnection" = $ViConnection + "DebugLogging" = $DebugLogging + "DebugLogfile" = $DebugLogFile } #Set the default connection is required. - if ( $DefaultConnection) { set-variable -name DefaultNSXConnection -value $connection -scope Global } + if ( $DefaultConnection) { Set-Variable -Name DefaultNSXConnection -Value $connection -Scope Global } #Return the connection $connection @@ -4994,8 +4991,8 @@ function Disconnect-NsxServer { Connect-NsxServer -Server nsxserver -username admin -Password VMware1! #> - if (Get-Variable -Name DefaultNsxConnection -scope global ) { - Remove-Variable -name DefaultNsxConnection -scope global + if (Get-Variable -Name DefaultNsxConnection -Scope global ) { + Remove-Variable -Name DefaultNsxConnection -Scope global } } @@ -5013,7 +5010,7 @@ function Get-PowerNsxVersion { #> #Updated to take advantage of Manifest info. - Get-Module PowerNsx | select-object version, path, author, companyName + Get-Module PowerNsx | Select-Object version, path, author, companyName } function Update-PowerNsx { @@ -5029,11 +5026,11 @@ function Update-PowerNsx { param ( - [Parameter (Mandatory = $True, Position=1)] - #Valid Branches supported for upgrading to. - [ValidateScript({ ValidateUpdateBranch $_ })] - [string]$Branch, - [ValidateSet("CurrentUser","AllUsers")][string]$InstallType="CurrentUser" + [Parameter (Mandatory = $True, Position = 1)] + #Valid Branches supported for upgrading to. + [ValidateScript( { ValidateUpdateBranch $_ })] + [string]$Branch, + [ValidateSet("CurrentUser", "AllUsers")][string]$InstallType = "CurrentUser" ) @@ -5046,7 +5043,7 @@ function Update-PowerNsx { } else { #OS specific temp variable - if ( test-path env:TMPDIR ) { + if ( Test-Path env:TMPDIR ) { $tmpdir = $env:TMPDIR } else { $tmpdir = "/tmp" } @@ -5057,28 +5054,28 @@ function Update-PowerNsx { } if ( $Branch -eq "master" ) { - write-warning "Updating to latest $branch branch commit. Stability is not guaranteed." + Write-Warning "Updating to latest $branch branch commit. Stability is not guaranteed." } #Installer doesnt play nice in strict mode... - set-strictmode -Off + Set-StrictMode -Off try { try { - $filename = split-path $PNsxUrl -leaf - invoke-webrequest -uri $PNsxUrl -outfile "$tmpdir\$filename" + $filename = Split-Path $PNsxUrl -Leaf + Invoke-WebRequest -Uri $PNsxUrl -OutFile "$tmpdir\$filename" } catch { #TODO: Confirm Proxy handling works with change to iwr. if ( $_.exception.innerexception -match "(407)") { $ProxyCred = Get-Credential -Message "Proxy Authentication Required" - invoke-webrequest -uri $PNsxUrl -outfile "$tmpdir\$filename" -ProxyCredential $ProxyCred + Invoke-WebRequest -Uri $PNsxUrl -OutFile "$tmpdir\$filename" -ProxyCredential $ProxyCred } else { throw $_ } } - invoke-expression "& `"$tmpdir\$filename`" -Upgrade -InstallType $InstallType" + Invoke-Expression "& `"$tmpdir\$filename`" -Upgrade -InstallType $InstallType" } catch { throw $_ @@ -5086,20 +5083,20 @@ function Update-PowerNsx { ## Not reloading module now, too many issues unloading dependant modules exist to make this robust and clean on all platforms. # Import-Module PowerNSX -global -force - write-host -ForegroundColor Magenta "PowerNSX has been updated. Please restart PowerShell to use the updated version." + Write-Host -ForegroundColor Magenta "PowerNSX has been updated. Please restart PowerShell to use the updated version." #Check to make sure we dont have mutiple installs.... - if ( (get-module -ListAvailable PowerNSX | measure-object ).count -ne 1 ) { - write-warning "Mutiple PowerNSX installations found. It is recommended to remove one of them or the universe may implode! (Or you may end up using an older version without realising, which is nearly as bad!)" - foreach ( $mod in (get-module -ListAvailable PowerNSX) ) { - write-warning "PowerNSX Install found in $($mod.path | split-path -parent )" + if ( (Get-Module -ListAvailable PowerNSX | Measure-Object ).count -ne 1 ) { + Write-Warning "Mutiple PowerNSX installations found. It is recommended to remove one of them or the universe may implode! (Or you may end up using an older version without realising, which is nearly as bad!)" + foreach ( $mod in (Get-Module -ListAvailable PowerNSX) ) { + Write-Warning "PowerNSX Install found in $($mod.path | Split-Path -Parent )" } } if ( $PreviousProgPref ) { #reenable progress dialogs from iwr $global:ProgressPreference = $PreviousProgPref } - set-strictmode -Version Latest + Set-StrictMode -Version Latest } function Wait-NsxJob { @@ -5128,37 +5125,37 @@ function Wait-NsxJob { #> param ( - [Parameter (Mandatory=$true)] - #Job Id string as returned from the api - [string]$jobid, - [Parameter (Mandatory=$true)] - #Job Query URI. There are several job subsystems in NSX. Some of them overlap. - [string]$JobStatusUri, - [Parameter (Mandatory=$true)] - #ScriptBlock that is used to evaluate completion. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.status -eq "Success" } - [System.Management.Automation.ScriptBlock]$CompleteCriteria, - [Parameter (Mandatory=$true)] - #ScriptBlock that is used to evaluate completion. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.status -eq "Failure" }. Wait-NsxJob will return immediately if this tests true. - [System.Management.Automation.ScriptBlock]$FailCriteria, - [Parameter (Mandatory=$true)] - #Scriptblock that is used to retrieve a status string. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.status }. Used only in status output (not in job completion criteria.) - [System.Management.Automation.ScriptBlock]$StatusExpression, - [Parameter (Mandatory=$false)] - #ScriptBlock that is used to retrieve any error string. Defaults to $StatusExpression. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.ExceptionMessage }. This is only used in warning/error output (not in job completion criteria.) - [System.Management.Automation.ScriptBlock]$ErrorExpression = $StatusExpression, - [Parameter (Mandatory=$false)] - #Seconds to wait before declaring a timeout - [int]$WaitTimeout=300, - [Parameter (Mandatory=$false)] - #Do we prompt user an allow them to reset the timeout timer, or throw on timeout - [switch]$FailOnTimeout=$false, - [Parameter (Mandatory=$false)] - #Number of seconds to sleep between status checks - [int]$SleepSeconds=1, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true)] + #Job Id string as returned from the api + [string]$jobid, + [Parameter (Mandatory = $true)] + #Job Query URI. There are several job subsystems in NSX. Some of them overlap. + [string]$JobStatusUri, + [Parameter (Mandatory = $true)] + #ScriptBlock that is used to evaluate completion. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.status -eq "Success" } + [System.Management.Automation.ScriptBlock]$CompleteCriteria, + [Parameter (Mandatory = $true)] + #ScriptBlock that is used to evaluate completion. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.status -eq "Failure" }. Wait-NsxJob will return immediately if this tests true. + [System.Management.Automation.ScriptBlock]$FailCriteria, + [Parameter (Mandatory = $true)] + #Scriptblock that is used to retrieve a status string. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.status }. Used only in status output (not in job completion criteria.) + [System.Management.Automation.ScriptBlock]$StatusExpression, + [Parameter (Mandatory = $false)] + #ScriptBlock that is used to retrieve any error string. Defaults to $StatusExpression. $job is the xml object returned from the API, so this should be something like { $job.controllerDeploymentInfo.ExceptionMessage }. This is only used in warning/error output (not in job completion criteria.) + [System.Management.Automation.ScriptBlock]$ErrorExpression = $StatusExpression, + [Parameter (Mandatory = $false)] + #Seconds to wait before declaring a timeout + [int]$WaitTimeout = 300, + [Parameter (Mandatory = $false)] + #Do we prompt user an allow them to reset the timeout timer, or throw on timeout + [switch]$FailOnTimeout = $false, + [Parameter (Mandatory = $false)] + #Number of seconds to sleep between status checks + [int]$SleepSeconds = 1, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -5167,14 +5164,14 @@ function Wait-NsxJob { $yesnochoices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) function prompt_for_timeout { - write-debug "$($MyInvocation.MyCommand.Name) : Timeout waiting for job $jobid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Timeout waiting for job $jobid" if ( -not $FailOnTimeout) { - $message = "Waited more than $WaitTimeout seconds for job $jobid to complete. Recommend checking NSX Manager logs or vCenter tasks for the potential cause." + $message = "Waited more than $WaitTimeout seconds for job $jobid to complete. Recommend checking NSX Manager logs or vCenter tasks for the potential cause." $question = "Continue waiting for the job to complete?" $decision = $Host.UI.PromptForChoice($message, $question, $yesnochoices, 0) if ( $decision -eq 1 ) { - throw "Timeout waiting for job $jobid to complete." + throw "Timeout waiting for job $jobid to complete." } } else { @@ -5185,7 +5182,7 @@ function Wait-NsxJob { process { - write-debug "$($MyInvocation.MyCommand.Name) : Waiting for job $jobid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Waiting for job $jobid" $StatusString = "Unknown" $Timer = 0 @@ -5195,7 +5192,7 @@ function Wait-NsxJob { #Sleep Write-Progress -Activity "Waiting for NSX job $jobId to complete." -Status "$StatusString" - start-sleep -Seconds $SleepSeconds + Start-Sleep -Seconds $SleepSeconds $Timer += $SleepSeconds #Are we timed out? @@ -5206,15 +5203,15 @@ function Wait-NsxJob { #Get updated jobStatus try { - $response = invoke-nsxwebrequest -method "get" -uri "$JobStatusUri/$jobId" -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI "$JobStatusUri/$jobId" -connection $connection [xml]$job = $response.Content - write-debug "$($MyInvocation.MyCommand.Name) : Got job from $JobStatusUri for job $jobid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Got job from $JobStatusUri for job $jobid" } catch { #Can fail if query is too quick - write-warning "Unable to query for job $jobid at $JobStatusUri. Does the job exist?" + Write-Warning "Unable to query for job $jobid at $JobStatusUri. Does the job exist?" } #Try get our status string. Failure here should indicate that the user needs to tell us that the API returned something unexpected, and/or PowerNSX has a bug that needs fixing. @@ -5223,10 +5220,10 @@ function Wait-NsxJob { } catch { $StatusString = "Unknown" - write-warning "Failed to retrieve job status when waiting for job $jobId. Please report this error on the PowerNSX issues page. (github.com/vmware/PowerNSX/issues) : $_" + Write-Warning "Failed to retrieve job status when waiting for job $jobId. Please report this error on the PowerNSX issues page. (github.com/vmware/PowerNSX/issues) : $_" } if ( &$FailCriteria ) { - write-debug "$($MyInvocation.MyCommand.Name) : Failure criteria `"$FailCriteria`" evaluated to true." + Write-Debug "$($MyInvocation.MyCommand.Name) : Failure criteria `"$FailCriteria`" evaluated to true." #Try get our error string. Failure here should indicate that the user needs to tell us that the API returned something unexpected, and/or PowerNSX has a bug that needs fixing. try { @@ -5234,13 +5231,13 @@ function Wait-NsxJob { } catch { $ErrorString = "Unknown" - write-warning "Failed to retrieve job error output when job $jobId failed. Please report this error on the PowerNSX issues page. (github.com/vmware/PowerNSX/issues) : $_" + Write-Warning "Failed to retrieve job error output when job $jobId failed. Please report this error on the PowerNSX issues page. (github.com/vmware/PowerNSX/issues) : $_" } Throw "Job $jobid failed with Status: $StatusString. Error: $ErrorString" } } until ( &$CompleteCriteria ) - write-debug "$($MyInvocation.MyCommand.Name) : Completed criteria `"$CompleteCriteria`" evaluated to true." + Write-Debug "$($MyInvocation.MyCommand.Name) : Completed criteria `"$CompleteCriteria`" evaluated to true." Write-Progress -Activity "Waiting for NSX job $jobId to complete." -Status "$StatusString" -Completed } @@ -5279,34 +5276,34 @@ function Wait-NsxGenericJob { #> param ( - [Parameter (Mandatory=$true)] - #Job Id string as returned from the api - [string]$JobId, - [Parameter (Mandatory=$false)] - #Seconds to wait before declaring a timeout. Timeout defaults to 30 seconds. - [int]$WaitTimeout=30, - [Parameter (Mandatory=$false)] - #Do we prompt user an allow them to reset the timeout timer, or throw on timeout - [switch]$FailOnTimeout=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true)] + #Job Id string as returned from the api + [string]$JobId, + [Parameter (Mandatory = $false)] + #Seconds to wait before declaring a timeout. Timeout defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $false)] + #Do we prompt user an allow them to reset the timeout timer, or throw on timeout + [switch]$FailOnTimeout = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $WaitJobArgs = @{ - "jobid" = $jobid - "JobStatusUri" = "/api/2.0/services/taskservice/job" + "jobid" = $jobid + "JobStatusUri" = "/api/2.0/services/taskservice/job" "CompleteCriteria" = { $job.jobInstances.jobInstance.status -eq "COMPLETED" } - "FailCriteria" = { + "FailCriteria" = { $job.jobInstances.jobInstance.status -eq "FAILED" } "StatusExpression" = { $execTask = @() $StatusMessage = "" - $execTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | where-object { $_.taskStatus -eq "EXECUTING" }) + $execTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | Where-Object { $_.taskStatus -eq "EXECUTING" }) if ( $exectask.count -eq 1) { $StatusMessage = "$($execTask.name) - $($execTask.taskStatus)" } @@ -5315,10 +5312,10 @@ function Wait-NsxGenericJob { } $StatusMessage } - "ErrorExpression" = { + "ErrorExpression" = { $failTask = @() $failMessage = "" - $failTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | where-object { $_.taskStatus -eq "FAILED" }) + $failTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | Where-Object { $_.taskStatus -eq "FAILED" }) if ( $failTask.count -eq 1) { $failMessage = "Failed Task : $($failTask.name) - $($failTask.statusMessage)" } @@ -5327,9 +5324,9 @@ function Wait-NsxGenericJob { } $failMessage } - "WaitTimeout" = $WaitTimeout - "FailOnTimeout" = $FailOnTimeout - "Connection" = $Connection + "WaitTimeout" = $WaitTimeout + "FailOnTimeout" = $FailOnTimeout + "Connection" = $Connection } Wait-NsxJob @WaitJobArgs @@ -5366,25 +5363,25 @@ function Get-NsxClusterStatus { param ( - [Parameter ( Mandatory=$true,ValueFromPipeline=$true)] - #Cluster Object to retrieve status details for. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter ( Mandatory = $true, ValueFromPipeline = $true)] + #Cluster Object to retrieve status details for. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} - process{ + process { #Get resource status for given cluster - write-debug "$($MyInvocation.MyCommand.Name) : Query status for cluster $($cluster.name) ($($cluster.ExtensionData.Moref.Value))" + Write-Debug "$($MyInvocation.MyCommand.Name) : Query status for cluster $($cluster.name) ($($cluster.ExtensionData.Moref.Value))" $uri = "/api/2.0/nwfabric/status-without-alarms?resource=$($cluster.ExtensionData.Moref.Value)" try { - $response = invoke-nsxrestmethod -connection $connection -method get -uri $uri + $response = Invoke-NsxRestMethod -connection $connection -method get -URI $uri $response.resourceStatuses.resourceStatus.nwFabricFeatureStatus } @@ -5392,7 +5389,7 @@ function Get-NsxClusterStatus { throw "Unable to query resource status for cluster $($cluster.Name) ($($cluster.ExtensionData.Moref.Value)). $_" } } - end{} + end {} } function Invoke-NsxCli { @@ -5431,20 +5428,20 @@ function Invoke-NsxCli { param ( - [Parameter ( Mandatory=$true, Position=1) ] - #Free form query string that is sent to the NSX Central CLI API - [ValidateNotNullOrEmpty()] - [String]$Query, - [Parameter ( Mandatory=$false) ] - #Supress warning about experimental feature. Defaults to False - [switch]$SupressWarning, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection = $defaultNSXConnection, + [Parameter ( Mandatory = $true, Position = 1) ] + #Free form query string that is sent to the NSX Central CLI API + [ValidateNotNullOrEmpty()] + [String]$Query, + [Parameter ( Mandatory = $false) ] + #Supress warning about experimental feature. Defaults to False + [switch]$SupressWarning, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection, [Parameter(Mandatory = $false)] - # switch param to support throwing raw output to avoid errors with the parser - [switch]$RawOutput + # switch param to support throwing raw output to avoid errors with the parser + [switch]$RawOutput ) @@ -5467,7 +5464,7 @@ function Invoke-NsxCli { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlCli = $XMLDoc.CreateElement("nsxcli") - $xmlDoc.appendChild($xmlCli) | out-null + $xmlDoc.appendChild($xmlCli) | Out-Null Add-XmlElement -xmlRoot $xmlCli -xmlElementName "command" -xmlElementText $Query @@ -5479,21 +5476,23 @@ function Invoke-NsxCli { Write-Debug -Message "[$($MyInvocation.MyCommand.Name)] Invoking POST method. Entering 'try/catch' block" try { - $response = Invoke-NsxRestMethod -Connection $connection -Method post -Uri $uri -Body $Body -extraheader @{"Accept"="text/plain"} + $response = Invoke-NsxRestMethod -connection $connection -method post -URI $uri -body $Body -extraheader @{"Accept" = "text/plain" } if ($RawOutput) { Write-Verbose -Message "[$($MyInvocation.MyCommand.Name)] Returning Raw Output" $response - } else { + } + else { Write-Verbose -Message "[$($MyInvocation.MyCommand.Name)] Parsing Output" ParseCentralCliResponse $response } # end if/else - } catch { + } + catch { throw "[$($MyInvocation.MyCommand.Name)][ERROR] Unable to execute Centralized CLI query. $_.Exception.Message. Try re-running command with the -RawOutput parameter." @@ -5535,37 +5534,37 @@ function Get-NsxCliDfwFilter { #> Param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$True)] - #PowerCLI Virtual Machine object. - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + #PowerCLI Virtual Machine object. + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - begin{} + begin {} - process{ + process { $query = "show vm $($VirtualMachine.ExtensionData.Moref.Value)" - $filters = Invoke-NsxCli $query -SupressWarning -connection $connection + $filters = Invoke-NsxCli $query -SupressWarning -Connection $connection foreach ( $filter in $filters ) { #only match slot 2 filters if ( $filter -notmatch 'nic-\d+-eth\d-vmware-sfw.2' ) { - write-warning "Ignoring filter `'$($filter.Filters)`' on VM $($filter.VM)" + Write-Warning "Ignoring filter `'$($filter.Filters)`' on VM $($filter.VM)" } else { #Execute the appropriate CLI query against the VMs host for the current filter... $query = "show vnic $($Filter."Vnic Id")" - Invoke-NsxCli $query -connection $connection + Invoke-NsxCli $query -Connection $connection } } } - end{} + end {} } function Get-NsxCliDfwRule { @@ -5595,33 +5594,34 @@ function Get-NsxCliDfwRule { #> Param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$True)] - #PowerCLI VirtualMachine object - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + #PowerCLI VirtualMachine object + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - begin{} + begin {} - process{ + process { if ( $VirtualMachine.PowerState -eq 'PoweredOn' ) { #First we retrieve the filter names from the host that the VM is running on try { $query = "show vm $($VirtualMachine.ExtensionData.Moref.Value)" - $VMs = Invoke-NsxCli $query -connection $connection + $VMs = Invoke-NsxCli $query -Connection $connection } catch { #Invoke-nsxcli threw an exception. There are a couple we want to handle here... switch -regex ($_.tostring()) { "\( Error 100: \)" { - write-warning "Virtual Machine $($VirtualMachine.Name) has no DFW Filter active."; - return } - default {throw} + Write-Warning "Virtual Machine $($VirtualMachine.Name) has no DFW Filter active."; + return + } + default { throw } } } @@ -5629,16 +5629,17 @@ function Get-NsxCliDfwRule { foreach ( $VM in $VMs ) { #Execute the appropriate CLI query against the VMs host for the current filter... $query = "show dfw host $($VirtualMachine.VMHost.ExtensionData.MoRef.Value) filter $($VM.Filters) rules" - $rule = Invoke-NsxCli $query -SupressWarning -connection $connection - $rule | add-member -memberType NoteProperty -Name "VirtualMachine" -Value $VirtualMachine - $rule | add-member -memberType NoteProperty -Name "Filter" -Value $($VM.Filters) + $rule = Invoke-NsxCli $query -SupressWarning -Connection $connection + $rule | Add-Member -MemberType NoteProperty -Name "VirtualMachine" -Value $VirtualMachine + $rule | Add-Member -MemberType NoteProperty -Name "Filter" -Value $($VM.Filters) $rule } - } else { - write-warning "Virtual Machine $($VirtualMachine.Name) is not powered on." + } + else { + Write-Warning "Virtual Machine $($VirtualMachine.Name) is not powered on." } } - end{} + end {} } function Get-NsxCliDfwAddrSet { @@ -5668,38 +5669,38 @@ function Get-NsxCliDfwAddrSet { #> Param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$True)] - #PowerCLI VirtualMachine object - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + #PowerCLI VirtualMachine object + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - begin{} + begin {} - process{ + process { #First we retrieve the filter names from the host that the VM is running on $query = "show vm $($VirtualMachine.ExtensionData.Moref.Value)" - $Filters = Invoke-NsxCli $query -connection $connection + $Filters = Invoke-NsxCli $query -Connection $connection #Potentially there are multiple filters (VM with more than one NIC). foreach ( $filter in $filters ) { #only match slot 2 filters if ( $filter -notmatch 'nic-\d+-eth\d-vmware-sfw.2' ) { - write-warning "Ignoring filter `'$($filter.Filters)`' on VM $($filter.VM)" + Write-Warning "Ignoring filter `'$($filter.Filters)`' on VM $($filter.VM)" } else { #Execute the appropriate CLI query against the VMs host for the current filter... $query = "show dfw host $($VirtualMachine.VMHost.ExtensionData.MoRef.Value) filter $($Filter.Filters) addrset" - Invoke-NsxCli $query -SupressWarning -connection $connection + Invoke-NsxCli $query -SupressWarning -Connection $connection } } } - end{} + end {} } function Get-NsxHostUvsmLogging { @@ -5715,15 +5716,15 @@ function Get-NsxHostUvsmLogging { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VMHostInterop]$VMHost, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VMHostInterop]$VMHost, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -5736,16 +5737,16 @@ function Get-NsxHostUvsmLogging { #UVSM Logging URI $URI = "/api/1.0/usvmlogging/$($VMHost.Extensiondata.Moref.Value)/root" try { - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - [PSCustomobject]@{ - "LoggerName"=$response.LoggingLevel.LoggerName; - "LogLevel"=$response.LoggingLevel.Level; - "HostName"=$VMhost.Name; - "HostId"=$VMhost.Extensiondata.Moref.Value + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + [PSCustomobject]@{ + "LoggerName" = $response.LoggingLevel.LoggerName; + "LogLevel" = $response.LoggingLevel.Level; + "HostName" = $VMhost.Name; + "HostId" = $VMhost.Extensiondata.Moref.Value } } catch { - write-warning "Error querying host $($VMhost.Name) for UVSM logging status. Check Guest Introspection is enabled, and USVM is available." + Write-Warning "Error querying host $($VMhost.Name) for UVSM logging status. Check Guest Introspection is enabled, and USVM is available." } } @@ -5767,15 +5768,15 @@ function Set-NsxHostUvsmLogging { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VMHostInterop]$VMHost, - [Parameter (Mandatory=$true)] - [ValidateSet("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE",IgnoreCase=$false)] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VMHostInterop]$VMHost, + [Parameter (Mandatory = $true)] + [ValidateSet("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", IgnoreCase = $false)] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -5784,7 +5785,7 @@ function Set-NsxHostUvsmLogging { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("logginglevel") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "loggerName" -xmlElementText "root" Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "level" -xmlElementText $LogLevel @@ -5792,15 +5793,15 @@ function Set-NsxHostUvsmLogging { # #Do the post $body = $xmlroot.OuterXml $URI = "/api/1.0/usvmlogging/$($VMhost.Extensiondata.Moref.Value)/changelevel" - Write-Progress -activity "Updating log level on host $($VMhost.Name)" - invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection| out-null - Write-progress -activity "Updating log level on host $($VMhost.Name)" -completed + Write-Progress -Activity "Updating log level on host $($VMhost.Name)" + Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection | Out-Null + Write-Progress -Activity "Updating log level on host $($VMhost.Name)" -Completed } end {} } -function New-NsxManager{ +function New-NsxManager { <# .SYNOPSIS @@ -5861,100 +5862,100 @@ function New-NsxManager{ #> - [CmdletBinding(DefaultParameterSetName="Default")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [CmdletBinding(DefaultParameterSetName = "Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. param ( - [Parameter ( Mandatory=$True )] - #Local Path to NSX MAnager OVA - [ValidateScript({ - if ( -not (test-path $_)) { + [Parameter ( Mandatory = $True )] + #Local Path to NSX MAnager OVA + [ValidateScript( { + if ( -not (Test-Path $_)) { throw "NSX Manager OVF file not found: $_." } $true })] - [string]$NsxManagerOVF, - [Parameter ( Mandatory=$True )] - #The name of the deployed VM. - [ValidateNotNullOrEmpty()] - [String]$Name, - [Parameter ( Mandatory=$True )] - #Name of the vSphere Cluster to which the VM will be deployed. - [ValidateNotNullOrEmpty()] - [string]$ClusterName, - [Parameter ( Mandatory=$True )] - #Name of the portgroup to which the management interface of the VM will be connected. - [ValidateNotNullOrEmpty()] - [string]$ManagementPortGroupName, - [Parameter ( Mandatory=$True )] - #Name of the Datastore to which the VM will be deployed. - [ValidateNotNullOrEmpty()] - [string]$DatastoreName, - [Parameter ( Mandatory=$True )] - #Name of the vSphere VM Inventory folder to which the VM will be deployed. - [ValidateNotNullOrEmpty()] - [string]$FolderName, - [Parameter ( Mandatory=$True )] - #CLI Password for the deployed NSX Manager. - [ValidateNotNullOrEmpty()] - [string]$CliPassword, - [Parameter ( Mandatory=$True )] - #Enable password for the deployed NSX Manager. - [ValidateNotNullOrEmpty()] - [string]$CliEnablePassword, - [Parameter ( Mandatory=$True )] - #Guest Hostname for the deployed NSX Manager. - [ValidateNotNullOrEmpty()] - [string]$Hostname, - [Parameter ( Mandatory=$True )] - #IP Address assigned to the management interface. - [ValidateNotNullOrEmpty()] - [ipaddress]$IpAddress, - [Parameter ( Mandatory=$True )] - #Netmask for the management interface. - [ValidateNotNullOrEmpty()] - [ipaddress]$Netmask, - [Parameter ( Mandatory=$True )] - #Gateway Address for the deployed NSX Manager. - [ValidateNotNullOrEmpty()] - [ipaddress]$Gateway, - [Parameter ( Mandatory=$True )] - #DNS Server for the deployed NSX Manager - [ValidateNotNullOrEmpty()] - [ipaddress[]]$DnsServer, - [Parameter ( Mandatory=$True )] - #DNS Domain Name for the deployed NSX Manager. - [ValidateNotNullOrEmpty()] - [string]$DnsDomain, - [Parameter ( Mandatory=$True )] - #NTP Server for the deployed NSX Manager (One only.) - [ValidateNotNullOrEmpty()] - [ipAddress]$NtpServer, - [Parameter ( Mandatory=$False)] - #Configured Memory for the deployed VM. Overrides default in OVA. Non-Production use only! - [ValidateRange(8,16)] - [int]$ManagerMemoryGB, - [Parameter ( Mandatory=$True, ParameterSetName = "StartVM" )] - #Start the VM once deployment is completed. - [switch]$StartVM=$false, - [Parameter ( Mandatory=$False, ParameterSetName = "StartVM")] - #Wait for the NSX Manager API to become available once deployment is complete and the appliance is started. Requires -StartVM, and network reachability between this machine and the management interface of the NSX Manager. - [ValidateScript({ - If ( -not $StartVM ) { throw "Cant wait for Manager API unless -StartVM is enabled."} + [string]$NsxManagerOVF, + [Parameter ( Mandatory = $True )] + #The name of the deployed VM. + [ValidateNotNullOrEmpty()] + [String]$Name, + [Parameter ( Mandatory = $True )] + #Name of the vSphere Cluster to which the VM will be deployed. + [ValidateNotNullOrEmpty()] + [string]$ClusterName, + [Parameter ( Mandatory = $True )] + #Name of the portgroup to which the management interface of the VM will be connected. + [ValidateNotNullOrEmpty()] + [string]$ManagementPortGroupName, + [Parameter ( Mandatory = $True )] + #Name of the Datastore to which the VM will be deployed. + [ValidateNotNullOrEmpty()] + [string]$DatastoreName, + [Parameter ( Mandatory = $True )] + #Name of the vSphere VM Inventory folder to which the VM will be deployed. + [ValidateNotNullOrEmpty()] + [string]$FolderName, + [Parameter ( Mandatory = $True )] + #CLI Password for the deployed NSX Manager. + [ValidateNotNullOrEmpty()] + [string]$CliPassword, + [Parameter ( Mandatory = $True )] + #Enable password for the deployed NSX Manager. + [ValidateNotNullOrEmpty()] + [string]$CliEnablePassword, + [Parameter ( Mandatory = $True )] + #Guest Hostname for the deployed NSX Manager. + [ValidateNotNullOrEmpty()] + [string]$Hostname, + [Parameter ( Mandatory = $True )] + #IP Address assigned to the management interface. + [ValidateNotNullOrEmpty()] + [ipaddress]$IpAddress, + [Parameter ( Mandatory = $True )] + #Netmask for the management interface. + [ValidateNotNullOrEmpty()] + [ipaddress]$Netmask, + [Parameter ( Mandatory = $True )] + #Gateway Address for the deployed NSX Manager. + [ValidateNotNullOrEmpty()] + [ipaddress]$Gateway, + [Parameter ( Mandatory = $True )] + #DNS Server for the deployed NSX Manager + [ValidateNotNullOrEmpty()] + [ipaddress[]]$DnsServer, + [Parameter ( Mandatory = $True )] + #DNS Domain Name for the deployed NSX Manager. + [ValidateNotNullOrEmpty()] + [string]$DnsDomain, + [Parameter ( Mandatory = $True )] + #NTP Server for the deployed NSX Manager (One only.) + [ValidateNotNullOrEmpty()] + [ipAddress]$NtpServer, + [Parameter ( Mandatory = $False)] + #Configured Memory for the deployed VM. Overrides default in OVA. Non-Production use only! + [ValidateRange(8, 16)] + [int]$ManagerMemoryGB, + [Parameter ( Mandatory = $True, ParameterSetName = "StartVM" )] + #Start the VM once deployment is completed. + [switch]$StartVM = $false, + [Parameter ( Mandatory = $False, ParameterSetName = "StartVM")] + #Wait for the NSX Manager API to become available once deployment is complete and the appliance is started. Requires -StartVM, and network reachability between this machine and the management interface of the NSX Manager. + [ValidateScript( { + If ( -not $StartVM ) { throw "Cant wait for Manager API unless -StartVM is enabled." } $true - })] - [switch]$Wait=$false, - [Parameter ( Mandatory=$False, ParameterSetName = "StartVM")] - #How long to wait before timeout for NSX MAnager API to become available once the VM has been started. - [int]$WaitTimeout = 600, - [Parameter ( Mandatory=$False )] - #Enable SSH on the deployed NSX Manager. - [switch]$EnableSsh=$false, + })] + [switch]$Wait = $false, + [Parameter ( Mandatory = $False, ParameterSetName = "StartVM")] + #How long to wait before timeout for NSX MAnager API to become available once the VM has been started. + [int]$WaitTimeout = 600, + [Parameter ( Mandatory = $False )] + #Enable SSH on the deployed NSX Manager. + [switch]$EnableSsh = $false, [Parameter (Mandatory = $false)] - #Disk format on the deployed NSX Manager - [ValidateSet ("Thin2GB", "Thick", "Thick2GB", "Thin", "EagerZeroedThick")] - [string]$DiskStorageFormat="Thick" + #Disk format on the deployed NSX Manager + [ValidateSet ("Thin2GB", "Thick", "Thick2GB", "Thin", "EagerZeroedThick")] + [string]$DiskStorageFormat = "Thick" ) Begin { @@ -5968,7 +5969,7 @@ function New-NsxManager{ else { Write-Verbose -Message "PowerCLI connection discovered; validating connection state" if (($Global:defaultViServer).IsConnected -eq $true) { - Write-Verbose -Message "Currently connected to VI Server: $Global:defaultViServer" + Write-Verbose -Message "Currently connected to VI Server: $Global:defaultViServer" } else { throw "Connection to VI Server: $Global:defaultViServer is present, but not connected. You must be connected to a vCenter Server to continue." @@ -5979,7 +5980,7 @@ function New-NsxManager{ # Chose a target host that is not in Maintenance Mode and select based on available memory $TargetVMHost = $null - $TargetVMHost = Get-Cluster $ClusterName | Get-VMHost | Where-Object {$_.ConnectionState -eq 'Connected'} | Sort-Object MemoryUsageGB | select-object -first 1 + $TargetVMHost = Get-Cluster $ClusterName | Get-VMHost | Where-Object { $_.ConnectionState -eq 'Connected' } | Sort-Object MemoryUsageGB | Select-Object -First 1 # throw an error if there are not any hosts suitable for deployment (ie: all hosts are in maint. mode) if ($targetVmHost -eq $null) { @@ -6000,25 +6001,25 @@ function New-NsxManager{ #Network Mapping to portgroup need to be defined. #6.4.0 GA changed the name of the network that is mapped, so now we need to #determine what it is rather than assume it is vsmgmt - $networkobj = get-member -membertype CodeProperty -inputobject $OvfConfiguration.NetworkMapping + $networkobj = Get-Member -MemberType CodeProperty -InputObject $OvfConfiguration.NetworkMapping $networkname = $networkobj.name $OvfConfiguration.NetworkMapping.$networkname.Value = $ManagementPortGroupName # OVF Configuration values. - $OvfConfiguration.common.vsm_cli_passwd_0.value = $CliPassword + $OvfConfiguration.common.vsm_cli_passwd_0.value = $CliPassword $OvfConfiguration.common.vsm_cli_en_passwd_0.value = $CliEnablePassword - $OvfConfiguration.common.vsm_hostname.value = $Hostname - $OvfConfiguration.common.vsm_ip_0.value = $IpAddress - $OvfConfiguration.common.vsm_netmask_0.value = $Netmask - $OvfConfiguration.common.vsm_gateway_0.value = $Gateway - $OvfConfiguration.common.vsm_dns1_0.value = $DnsServer.IPAddressToString -join "," - $OvfConfiguration.common.vsm_domain_0.value = $DnsDomain - $OvfConfiguration.common.vsm_ntp_0.value = $NtpServer - $OvfConfiguration.common.vsm_isSSHEnabled.value = $EnableSsh + $OvfConfiguration.common.vsm_hostname.value = $Hostname + $OvfConfiguration.common.vsm_ip_0.value = $IpAddress + $OvfConfiguration.common.vsm_netmask_0.value = $Netmask + $OvfConfiguration.common.vsm_gateway_0.value = $Gateway + $OvfConfiguration.common.vsm_dns1_0.value = $DnsServer.IPAddressToString -join "," + $OvfConfiguration.common.vsm_domain_0.value = $DnsDomain + $OvfConfiguration.common.vsm_ntp_0.value = $NtpServer + $OvfConfiguration.common.vsm_isSSHEnabled.value = $EnableSsh # Deploy the OVA. Write-Progress -Activity "Deploying NSX Manager OVA" - $VM = Import-vApp -Source $NsxManagerOvf -OvfConfiguration $OvfConfiguration -Name $Name -Location $ClusterName -VMHost $TargetVMHost -Datastore $DatastoreName -DiskStorageFormat $DiskStorageFormat + $VM = Import-VApp -Source $NsxManagerOvf -OvfConfiguration $OvfConfiguration -Name $Name -Location $ClusterName -VMHost $TargetVMHost -Datastore $DatastoreName -DiskStorageFormat $DiskStorageFormat If ( $PSBoundParameters.ContainsKey('FolderName')) { @@ -6034,7 +6035,7 @@ function New-NsxManager{ Write-Warning -Message "Changing Memory configuration of NSX Manager VM to $ManagerMemoryGB GB. Not supported for Production Use!" # start Get-VM $Name | - Set-VM -MemoryGB $ManagerMemoryGB -confirm:$false | + Set-VM -MemoryGB $ManagerMemoryGB -Confirm:$false | Get-VMResourceConfiguration | Set-VMResourceConfiguration -MemReservationMB 0 -CpuReservationMhz 0 | Out-Null @@ -6044,7 +6045,7 @@ function New-NsxManager{ Write-Progress -Activity "Deploying NSX Manager OVA" -Completed - if ( $StartVM ) { + if ( $StartVM ) { Write-Progress -Activity "Starting NSX Manager" $VM | Start-VM @@ -6057,12 +6058,12 @@ function New-NsxManager{ # User wants to wait for Manager API to start. $waitStep = 30 $Timer = 0 - Write-Progress -Activity "Waiting for NSX Manager api to become available" -PercentComplete $(($Timer/$WaitTimeout)*100) + Write-Progress -Activity "Waiting for NSX Manager api to become available" -PercentComplete $(($Timer / $WaitTimeout) * 100) do { # sleep a while, the VM will take time to start fully.. - start-sleep $WaitStep + Start-Sleep $WaitStep $Timer += $WaitStep try { @@ -6080,28 +6081,30 @@ function New-NsxManager{ Connect-NsxServer @connectParams | Out-Null break - } catch { + } + catch { - Write-Progress -Activity "Waiting for NSX Manager api to become available" -PercentComplete $(($Timer/$WaitTimeout)*100) + Write-Progress -Activity "Waiting for NSX Manager api to become available" -PercentComplete $(($Timer / $WaitTimeout) * 100) } # end try/catch if ( $Timer -ge $WaitTimeout ) { # We exceeded the timeout - what does the user want to do? - $message = "Waited more than $WaitTimeout seconds for NSX Manager API to become available. Recommend checking boot process, network config etc." - $question = "Continue waiting for NSX Manager?" + $message = "Waited more than $WaitTimeout seconds for NSX Manager API to become available. Recommend checking boot process, network config etc." + $question = "Continue waiting for NSX Manager?" $yesnochoices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $yesnochoices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) $yesnochoices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) - $decision = $Host.UI.PromptForChoice($message, $question, $yesnochoices, 0) + $decision = $Host.UI.PromptForChoice($message, $question, $yesnochoices, 0) if ($decision -eq 0) { # User waits... $Timer = 0 - } else { + } + else { throw "Timeout waiting for NSX Manager appliance API to become available." @@ -6164,64 +6167,64 @@ function Set-NsxManager { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] #Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] #Cant remove without breaking backward compatibility Param ( - [Parameter (Mandatory=$True, ParameterSetName="Syslog")] - #Syslog server to which syslogs will be forwarded. - [ValidateNotNullOrEmpty()] - [string]$SyslogServer, - [Parameter (Mandatory=$False, ParameterSetName="Syslog")] - #TCP/UDP port on destination syslog server to connect to. - [ValidateRange (1,65535)] - [int]$SyslogPort=514, - [Parameter (Mandatory=$False, ParameterSetName="Syslog")] - #Syslog Protocol - either TCP or UDP. - [ValidateSet ("tcp","udp")] - [string]$SyslogProtocol="udp", - [Parameter (Mandatory=$True, ParameterSetName="Sso")] - #SSO Server to register this NSX Manager with. - [ValidateNotNullOrEmpty()] - [string]$SsoServer, - [Parameter (Mandatory=$False, ParameterSetName="Sso")] - #TCP Port on SSO server to connect to when registering. - [ValidateNotNullOrEmpty()] - [string]$SsoPort=443, - [Parameter (Mandatory=$True, ParameterSetName="Sso")] - #SSO Username used for registration. - [ValidateNotNullOrEmpty()] - [string]$SsoUserName, - [Parameter (Mandatory=$True, ParameterSetName="Sso")] - #SSO Password used for registration. - [ValidateNotNullOrEmpty()] - [string]$SsoPassword, - [Parameter (Mandatory=$True, ParameterSetName="vCenter")] - #vCenter server to register this NSX Manager with. - [ValidateNotNullOrEmpty()] - [string]$vCenterServer, - [Parameter (Mandatory=$True, ParameterSetName="vCenter")] - #UserName used for vCenter connection. - [ValidateNotNullOrEmpty()] - [string]$vCenterUserName, - [Parameter (Mandatory=$True, ParameterSetName="vCenter")] - #Password used for vCenter connection. - [ValidateNotNullOrEmpty()] - [string]$vCenterPassword, - [Parameter (Mandatory=$False, ParameterSetName="vCenter")] - [Parameter (Mandatory=$False, ParameterSetName="Sso")] - #SSL Thumbprint to validate certificate presented by SSO/vCenter server against. - [ValidateNotNullOrEmpty()] - [string]$SslThumbprint="", - [Parameter (Mandatory=$False, ParameterSetName="vCenter")] - [Parameter (Mandatory=$False, ParameterSetName="Sso")] - #Accept any SSL certificate presented by SSO/vCenter. - [switch]$AcceptAnyThumbprint=$True, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ParameterSetName = "Syslog")] + #Syslog server to which syslogs will be forwarded. + [ValidateNotNullOrEmpty()] + [string]$SyslogServer, + [Parameter (Mandatory = $False, ParameterSetName = "Syslog")] + #TCP/UDP port on destination syslog server to connect to. + [ValidateRange (1, 65535)] + [int]$SyslogPort = 514, + [Parameter (Mandatory = $False, ParameterSetName = "Syslog")] + #Syslog Protocol - either TCP or UDP. + [ValidateSet ("tcp", "udp")] + [string]$SyslogProtocol = "udp", + [Parameter (Mandatory = $True, ParameterSetName = "Sso")] + #SSO Server to register this NSX Manager with. + [ValidateNotNullOrEmpty()] + [string]$SsoServer, + [Parameter (Mandatory = $False, ParameterSetName = "Sso")] + #TCP Port on SSO server to connect to when registering. + [ValidateNotNullOrEmpty()] + [string]$SsoPort = 443, + [Parameter (Mandatory = $True, ParameterSetName = "Sso")] + #SSO Username used for registration. + [ValidateNotNullOrEmpty()] + [string]$SsoUserName, + [Parameter (Mandatory = $True, ParameterSetName = "Sso")] + #SSO Password used for registration. + [ValidateNotNullOrEmpty()] + [string]$SsoPassword, + [Parameter (Mandatory = $True, ParameterSetName = "vCenter")] + #vCenter server to register this NSX Manager with. + [ValidateNotNullOrEmpty()] + [string]$vCenterServer, + [Parameter (Mandatory = $True, ParameterSetName = "vCenter")] + #UserName used for vCenter connection. + [ValidateNotNullOrEmpty()] + [string]$vCenterUserName, + [Parameter (Mandatory = $True, ParameterSetName = "vCenter")] + #Password used for vCenter connection. + [ValidateNotNullOrEmpty()] + [string]$vCenterPassword, + [Parameter (Mandatory = $False, ParameterSetName = "vCenter")] + [Parameter (Mandatory = $False, ParameterSetName = "Sso")] + #SSL Thumbprint to validate certificate presented by SSO/vCenter server against. + [ValidateNotNullOrEmpty()] + [string]$SslThumbprint = "", + [Parameter (Mandatory = $False, ParameterSetName = "vCenter")] + [Parameter (Mandatory = $False, ParameterSetName = "Sso")] + #Accept any SSL certificate presented by SSO/vCenter. + [switch]$AcceptAnyThumbprint = $True, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -6239,7 +6242,7 @@ function Set-NsxManager { #Create the XMLRoot [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("syslogserver") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null #Create an Element and append it to the root Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "syslogServer" -xmlElementText $syslogServer.ToString() @@ -6247,7 +6250,7 @@ function Set-NsxManager { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "protocol" -xmlElementText $SyslogProtocol $uri = "/api/1.0/appliance-management/system/syslogserver" - Invoke-NsxRestMethod -Method "put" -body $xmlRoot.outerXml -uri $uri -Connection $Connection + Invoke-NsxRestMethod -method "put" -body $xmlRoot.outerXml -URI $uri -connection $Connection } "Sso" { @@ -6265,7 +6268,7 @@ function Set-NsxManager { #Create the XMLRoot [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("ssoConfig") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null #Create an Element and append it to the root $SsoLookupServiceUrl = "https://$($SsoServer.ToString()):$($SsoPort.ToString())/lookupservice/sdk" @@ -6276,16 +6279,16 @@ function Set-NsxManager { $uri = "/api/2.0/services/ssoconfig" try { - $null = Invoke-NsxWebRequest -Method "post" -body $xmlRoot.outerXml -uri $uri -Connection $Connection + $null = Invoke-NsxWebRequest -method "post" -body $xmlRoot.outerXml -URI $uri -connection $Connection } catch { #it sucks that at the moment I can't parse the response body as xml :( I really need to fix this. $thumbprintMatch = '[<"]details[>"]:*"*(([A-F0-9]{2}:)+[A-F0-9]{2})' - if (($AcceptAnyThumbprint) -and ($_ -match $thumbprintMatch)) { + if (($AcceptAnyThumbprint) -and ($_ -match $thumbprintMatch)) { #API responded with a thumbprint - write-warning "Using thumbprint presented by the SSO server: $($Matches[1])" + Write-Warning "Using thumbprint presented by the SSO server: $($Matches[1])" $xmlRoot.certificateThumbprint = $matches[1] - $null = Invoke-NsxWebRequest -Method "post" -body $xmlRoot.outerXml -uri $uri -Connection $Connection + $null = Invoke-NsxWebRequest -method "post" -body $xmlRoot.outerXml -URI $uri -connection $Connection } else { #rethrow @@ -6308,7 +6311,7 @@ function Set-NsxManager { #Build the XML [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("vcInfo") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "ipAddress" -xmlElementText $vCenterServer.ToString() Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "userName" -xmlElementText $vCenterUserName.ToString() @@ -6318,16 +6321,16 @@ function Set-NsxManager { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "pluginDownloadServer" -xmlElementText "" $uri = "/api/2.0/services/vcconfig" try { - $null = Invoke-NsxWebRequest -Method "put" -body $xmlRoot.outerXml -uri $uri -Connection $Connection + $null = Invoke-NsxWebRequest -method "put" -body $xmlRoot.outerXml -URI $uri -connection $Connection } catch { #it sucks that at the moment I can't parse the response body as xml :( I really need to fix this. $thumbprintMatch = '[<"]details[>"]:*"*(([A-F0-9]{2}:)+[A-F0-9]{2})' - if (($AcceptAnyThumbprint) -and ($_ -match $thumbprintMatch)) { + if (($AcceptAnyThumbprint) -and ($_ -match $thumbprintMatch)) { #API responded with a thumbprint - write-warning "Using thumbprint presented by the vCenter server: $($Matches[1])" + Write-Warning "Using thumbprint presented by the vCenter server: $($Matches[1])" $xmlRoot.certificateThumbprint = $matches[1] - $null = Invoke-NsxWebRequest -Method "put" -body $xmlRoot.outerXml -uri $uri -Connection $Connection + $null = Invoke-NsxWebRequest -method "put" -body $xmlRoot.outerXml -URI $uri -connection $Connection } else { #rethrow @@ -6365,10 +6368,10 @@ function Get-NsxManagerCertificate { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $role = Get-NsxUserRole $Connection.Credential.Username @@ -6378,9 +6381,9 @@ function Get-NsxManagerCertificate { $URI = "/api/1.0/appliance-management/certificatemanager/certificates/nsx" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::x509Certificates/x509certificate')) { + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::x509Certificates/x509certificate')) { $response.X509Certificates.x509certificate } } @@ -6408,23 +6411,23 @@ function Get-NsxManagerSsoConfig { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/services/ssoconfig" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::ssoConfig/vsmSolutionName')) { + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::ssoConfig/vsmSolutionName')) { $ssoConfig = $response.ssoConfig #Only if its configured do we get status $URI = "/api/2.0/services/ssoconfig/status" - [System.Xml.XmlDocument]$status = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$status = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection Add-XmlElement -xmlRoot $ssoConfig -xmlElementName "Connected" -xmlElementText $status.boolean #really? Boolean? What bonehead wrote this API? @@ -6455,23 +6458,23 @@ function Get-NsxManagerVcenterConfig { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/services/vcconfig" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::vcInfo/ipAddress')) { + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::vcInfo/ipAddress')) { $vcConfig = $response.vcInfo #Only if its configured do we get status $URI = "/api/2.0/services/vcconfig/status" - [System.Xml.XmlDocument]$status = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$status = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection Add-XmlElement -xmlRoot $vcConfig -xmlElementName "Connected" -xmlElementText $status.vcConfigStatus.Connected $vcConfig @@ -6497,21 +6500,21 @@ function Get-NsxManagerTimeSettings { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - $role = Get-NsxUserRole $Connection.Credential.Username -connection $connection + $role = Get-NsxUserRole $Connection.Credential.Username -Connection $connection if ( $role.role -ne 'super_user' ) { throw "Appliance Management APIs require a local NSX Manager account (super_user role access) " } $URI = "/api/1.0/appliance-management/system/timesettings" - $result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection #NSX 6.2.3/4 changed API schema here! :( Grrrr. Have to test and return consistent object if ( $result -is [System.Xml.XmlDocument]) { @@ -6522,10 +6525,10 @@ function Get-NsxManagerTimeSettings { #Pre 6.2.3 manager response. [System.XML.XMLDocument]$xmldoc = New-Object System.Xml.XmlDocument [System.XML.XMLElement]$xmlTimeSettings = $xmlDoc.CreateElement('timeSettings') - $xmldoc.AppendChild($xmlTimeSettings) | out-null + $xmldoc.AppendChild($xmlTimeSettings) | Out-Null [System.XML.XMLElement]$xmlNTPServerString = $xmlDoc.CreateElement('ntpServer') - $xmlTimeSettings.Appendchild($xmlNTPServerString) | out-null + $xmlTimeSettings.Appendchild($xmlNTPServerString) | Out-Null Add-XmlElement -xmlRoot $xmlNTPServerString -xmlElementName "string" -xmlElementText $result.ntpServer Add-XmlElement -xmlRoot $xmlTimeSettings -xmlElementName "datetime" -xmlElementText $result.datetime @@ -6557,18 +6560,18 @@ function Set-NsxManagerTimeSettings { Param ( - [Parameter (Mandatory=$False)] - #NTP server for time synchronization.. - [ValidateNotNullOrEmpty()] - [string[]]$NtpServer, - [Parameter (Mandatory=$False)] - #Time Zone, default UTC. - [ValidateNotNullOrEmpty()] - [string]$TimeZone="UTC", - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #NTP server for time synchronization.. + [ValidateNotNullOrEmpty()] + [string[]]$NtpServer, + [Parameter (Mandatory = $False)] + #Time Zone, default UTC. + [ValidateNotNullOrEmpty()] + [string]$TimeZone = "UTC", + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -6578,16 +6581,16 @@ function Set-NsxManagerTimeSettings { } $uri = "/api/1.0/appliance-management/system/timesettings" - [System.Xml.XmlDocument]$Existing = Invoke-NsxRestMethod -Method get -uri $uri -Connection $Connection + [System.Xml.XmlDocument]$Existing = Invoke-NsxRestMethod -method get -URI $uri -connection $Connection #Api barfs if we set the time with the value we get from it. And in a non intuitive way... sigh again... - $null = $Existing.timeSettings.RemoveChild((invoke-xpathquery -node $Existing -QueryMethod SelectSingleNode -query "child::timeSettings/datetime") ) + $null = $Existing.timeSettings.RemoveChild((Invoke-XpathQuery -Node $Existing -QueryMethod SelectSingleNode -query "child::timeSettings/datetime") ) If ( Invoke-XpathQuery -Node $Existing -QueryMethod SelectSingleNode -query "child::timeSettings") { if ( $PSBoundParameters.ContainsKey("ntpserver")) { if ( Invoke-XpathQuery -Node $Existing -QueryMethod SelectSingleNode -query "child::timeSettings/ntpServer" ) { - write-warning "Existing NTP servers are configured and will be retained. Use Clear-NsxManagerTimeSettings to remove them." + Write-Warning "Existing NTP servers are configured and will be retained. Use Clear-NsxManagerTimeSettings to remove them." #Api doesnt allow 'updates', so we have to save existing, then remove, then readd the union of old and new. Clear-NsxManagerTimeSettings -Connection $Connection @@ -6599,7 +6602,7 @@ function Set-NsxManagerTimeSettings { } else { [System.XML.XMLElement]$xmlNtpNode = $Existing.CreateElement('ntpServer') - $Existing.timeSettings.Appendchild($xmlNtpNode) | out-null + $Existing.timeSettings.Appendchild($xmlNtpNode) | Out-Null foreach ($Server in $ntpserver) { Add-XmlElement -xmlRoot $xmlNtpNode -xmlElementName "string" -xmlElementText $server.ToString() } @@ -6610,9 +6613,9 @@ function Set-NsxManagerTimeSettings { } $uri = "/api/1.0/appliance-management/system/timesettings" - $null = Invoke-NsxRestMethod -Method put -body $Existing.timeSettings.outerXml -uri $uri -Connection $Connection + $null = Invoke-NsxRestMethod -method put -body $Existing.timeSettings.outerXml -URI $uri -connection $Connection Get-NsxManagerTimeSettings -Connection $Connection - } + } else { throw "Unexpected response from API when querying existing time settings." } @@ -6641,11 +6644,11 @@ function Clear-NsxManagerTimeSettings { #> Param ( - [switch]$ClearTimeZone=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [switch]$ClearTimeZone = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $role = Get-NsxUserRole $Connection.Credential.Username -Connection $connection @@ -6657,7 +6660,7 @@ function Clear-NsxManagerTimeSettings { if ( Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Existing -query "child::ntpServer") { #API errors if you clear when there arent any existing NTP servers configured... sigh... $uri = "/api/1.0/appliance-management/system/timesettings/ntp" - $null = Invoke-NsxRestMethod -Method delete -uri $uri -Connection $Connection + $null = Invoke-NsxRestMethod -method delete -URI $uri -connection $Connection } if ($ClearTimeZone ) { @@ -6684,10 +6687,10 @@ function Get-NsxManagerSyslogServer { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -6698,7 +6701,7 @@ function Get-NsxManagerSyslogServer { $URI = "/api/1.0/appliance-management/system/syslogserver" - $result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection # Make sure we actually get a response. If there are no syslog servers # configured, then the API does not return any response body. @@ -6712,7 +6715,7 @@ function Get-NsxManagerSyslogServer { #Pre 6.2.3 manager response. [System.XML.XMLDocument]$xmldoc = New-Object System.Xml.XmlDocument [System.XML.XMLElement]$xmlSyslog = $xmlDoc.CreateElement('syslogserver') - $xmldoc.AppendChild($xmlSyslog) | out-null + $xmldoc.AppendChild($xmlSyslog) | Out-Null Add-XmlElement -xmlRoot $xmlSyslog -xmlElementName "syslogServer" -xmlElementText $result.syslogServer Add-XmlElement -xmlRoot $xmlSyslog -xmlElementName "port" -xmlElementText $result.port @@ -6741,10 +6744,10 @@ function Get-NsxManagerNetwork { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -6755,7 +6758,7 @@ function Get-NsxManagerNetwork { $URI = "/api/1.0/appliance-management/system/network" - $result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $result -is [System.Xml.XmlDocument]) { #Assume the child exists. @@ -6770,10 +6773,10 @@ function Get-NsxManagerNetwork { [System.XML.XMLDocument]$xmldoc = New-Object System.Xml.XmlDocument [System.XML.XMLElement]$xmlnetwork = $xmlDoc.CreateElement('network') [System.XML.XMLElement]$xmlnetworkIPv4AddressDto = $xmlDoc.CreateElement('networkIPv4AddressDto') - $xmldoc.AppendChild($xmlnetwork) | out-null + $xmldoc.AppendChild($xmlnetwork) | Out-Null if ( $result.networkIPv4AddressDto) { - $xmlnetwork.AppendChild($xmlnetworkIPv4AddressDto) | out-null + $xmlnetwork.AppendChild($xmlnetworkIPv4AddressDto) | Out-Null Add-XmlElement -xmlRoot $xmlnetworkIPv4AddressDto -xmlElementName "ipv4Address" -xmlElementText $result.networkIPv4AddressDto.ipv4Address Add-XmlElement -xmlRoot $xmlnetworkIPv4AddressDto -xmlElementName "ipv4NetMask" -xmlElementText $result.networkIPv4AddressDto.ipv4NetMask Add-XmlElement -xmlRoot $xmlnetworkIPv4AddressDto -xmlElementName "ipv4Gateway" -xmlElementText $result.networkIPv4AddressDto.ipv4Gateway @@ -6790,7 +6793,7 @@ function Get-NsxManagerNetwork { if ( $result.networkIPv6AddressDto) { [System.XML.XMLElement]$xmlnetworkIPv6AddressDto = $xmlDoc.CreateElement('networkIPv6AddressDto') - $xmlnetwork.AppendChild($xmlnetworkIPv6AddressDto) | out-null + $xmlnetwork.AppendChild($xmlnetworkIPv6AddressDto) | Out-Null Add-XmlElement -xmlRoot $xmlnetworkIPv6AddressDto -xmlElementName "ipv6Address" -xmlElementText $result.networkIPv4AddressDto.ipv6Address Add-XmlElement -xmlRoot $xmlnetworkIPv6AddressDto -xmlElementName "ipv6NetMask" -xmlElementText $result.networkIPv4AddressDto.ipv6NetMask Add-XmlElement -xmlRoot $xmlnetworkIPv6AddressDto -xmlElementName "ipv6Gateway" -xmlElementText $result.networkIPv4AddressDto.ipv6Gateway @@ -6799,7 +6802,7 @@ function Get-NsxManagerNetwork { if ( $result.dns ) { [System.XML.XMLElement]$xmldns = $xmlDoc.CreateElement('dns') - $xmlnetwork.AppendChild($xmldns) | out-null + $xmlnetwork.AppendChild($xmldns) | Out-Null foreach ( $server in $result.dns.ipv4Dns ) { Add-XmlElement -xmlRoot $xmldns -xmlElementName "ipv4Address" -xmlElementText $server } @@ -6835,10 +6838,10 @@ function Get-NsxManagerBackup { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -6849,7 +6852,7 @@ function Get-NsxManagerBackup { $URI = "/api/1.0/appliance-management/backuprestore/backupsettings" - $result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $result -is [System.Xml.XmlDocument]) { #Assume the child exists. @@ -6864,14 +6867,14 @@ function Get-NsxManagerBackup { [System.XML.XMLDocument]$xmldoc = New-Object System.Xml.XmlDocument [System.XML.XMLElement]$xmlbackupRestoreSettings = $xmlDoc.CreateElement('backupRestoreSettings') - foreach ( $Property in ($result | get-member -MemberType NoteProperty )) { + foreach ( $Property in ($result | Get-Member -MemberType NoteProperty )) { if ( $result."$($Property.Name)" -is [string]) { Add-XmlElement -xmlRoot $xmlbackupRestoreSettings -xmlElementName "$($Property.Name)" -xmlElementText $result."$($Property.Name)" } elseif ( $result."$($Property.Name)" -is [system.object]) { [System.XML.XMLElement]$xmlObjElement = $xmlDoc.CreateElement($Property.Name) - $xmlbackupRestoreSettings.AppendChild($xmlObjElement) | out-null - foreach ( $ElementProp in ($result."$($Property.Name)" | get-member -MemberType NoteProperty )) { + $xmlbackupRestoreSettings.AppendChild($xmlObjElement) | Out-Null + foreach ( $ElementProp in ($result."$($Property.Name)" | Get-Member -MemberType NoteProperty )) { Add-XmlElement -xmlRoot $xmlObjElement -xmlElementName "$($ElementProp.Name)" -xmlElementText $result."$($Property.Name)"."$($ElementProp.Name)" } } @@ -6899,10 +6902,10 @@ function Get-NsxManagerComponentSummary { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -6912,7 +6915,7 @@ function Get-NsxManagerComponentSummary { } $URI = "/api/1.0/appliance-management/summary/components" - $result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $result -is [System.Xml.XmlDocument]) { #Assume the child exists. @@ -6927,40 +6930,40 @@ function Get-NsxManagerComponentSummary { [System.XML.XMLDocument]$xmldoc = New-Object System.Xml.XmlDocument [System.XML.XMLElement]$xmlComponentsSummary = $xmlDoc.CreateElement('componentsSummary') [System.XML.XMLElement]$xmlComponentsByGroup = $xmlDoc.CreateElement('componentsByGroup') - $xmldoc.AppendChild($xmlComponentsSummary) | out-null - $xmlComponentsSummary.AppendChild($xmlComponentsByGroup) | out-null + $xmldoc.AppendChild($xmlComponentsSummary) | Out-Null + $xmlComponentsSummary.AppendChild($xmlComponentsByGroup) | Out-Null - foreach ( $NamedProperty in (get-member -InputObject $result.componentsByGroup -MemberType NoteProperty)) { + foreach ( $NamedProperty in (Get-Member -InputObject $result.componentsByGroup -MemberType NoteProperty)) { [System.XML.XMLElement]$xmlEntry = $xmlDoc.CreateElement('entry') - $xmlComponentsByGroup.AppendChild($xmlEntry) | out-null + $xmlComponentsByGroup.AppendChild($xmlEntry) | Out-Null Add-XmlElement -xmlRoot $xmlEntry -xmlElementName "string" -xmlElementText $NamedProperty.Name [System.XML.XMLElement]$xmlComponents = $xmlDoc.CreateElement('components') - $xmlEntry.AppendChild($xmlComponents) | out-null + $xmlEntry.AppendChild($xmlComponents) | Out-Null foreach ( $component in $result.componentsByGroup.($NamedProperty.name).components) { [System.XML.XMLElement]$xmlComponent = $xmlDoc.CreateElement('component') - $xmlComponents.AppendChild($xmlComponent) | out-null + $xmlComponents.AppendChild($xmlComponent) | Out-Null - foreach ( $NoteProp in ($component | Get-Member -Membertype NoteProperty) ) { + foreach ( $NoteProp in ($component | Get-Member -MemberType NoteProperty) ) { #Check if I actually have a value if ( $component.($NoteProp.Name) ) { $Property = $component.($NoteProp.Name) - write-debug "GetType: $($Property.gettype())" - write-debug "Is: $($Property -is [array])" + Write-Debug "GetType: $($Property.gettype())" + Write-Debug "Is: $($Property -is [array])" #Switch on my value - switch ( $Property.gettype() ) { + switch ( $Property.gettype() ) { "System.Object[]" { - write-debug "In: Array" + Write-Debug "In: Array" [System.XML.XMLElement]$xmlCompArray = $xmlDoc.CreateElement($NoteProp.Name) - $xmlComponent.AppendChild($xmlCompArray) | out-null + $xmlComponent.AppendChild($xmlCompArray) | Out-Null foreach ( $member in $Property ) { #All examples ive seen have strings, but not sure if this will stand up to scrutiny... Add-XmlElement -xmlRoot $xmlCompArray -xmlElementName $member.GetType().Name.tolower() -xmlElementText $member.ToString() @@ -6968,15 +6971,15 @@ function Get-NsxManagerComponentSummary { } "string" { - write-debug "In: String" + Write-Debug "In: String" Add-XmlElement -xmlRoot $xmlComponent -xmlElementName $NoteProp.Name -xmlElementText $Property } "bool" { - write-debug "In: Bool" + Write-Debug "In: Bool" Add-XmlElement -xmlRoot $xmlComponent -xmlElementName $NoteProp.Name -xmlElementText $Property.ToString().tolower() } - default { write-debug "Fuck it : $_" } + default { Write-Debug "Fuck it : $_" } } } } @@ -7005,10 +7008,10 @@ function Get-NsxManagerSystemSummary { #> param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -7019,7 +7022,7 @@ function Get-NsxManagerSystemSummary { $URI = "/api/1.0/appliance-management/summary/system" - $result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $result -is [System.Xml.XmlDocument]) { #Assume the child exists. @@ -7034,14 +7037,14 @@ function Get-NsxManagerSystemSummary { [System.XML.XMLDocument]$xmldoc = New-Object System.Xml.XmlDocument [System.XML.XMLElement]$xmlsystemSummary = $xmlDoc.CreateElement('systemSummary') - foreach ( $Property in ($result | get-member -MemberType NoteProperty )) { + foreach ( $Property in ($result | Get-Member -MemberType NoteProperty )) { if ( $result."$($Property.Name)" -is [string]) { Add-XmlElement -xmlRoot $xmlsystemSummary -xmlElementName "$($Property.Name)" -xmlElementText $result."$($Property.Name)" } elseif ( $result."$($Property.Name)" -is [system.object]) { [System.XML.XMLElement]$xmlObjElement = $xmlDoc.CreateElement($Property.Name) - $xmlsystemSummary.AppendChild($xmlObjElement) | out-null - foreach ( $ElementProp in ($result."$($Property.Name)" | get-member -MemberType NoteProperty )) { + $xmlsystemSummary.AppendChild($xmlObjElement) | Out-Null + foreach ( $ElementProp in ($result."$($Property.Name)" | Get-Member -MemberType NoteProperty )) { Add-XmlElement -xmlRoot $xmlObjElement -xmlElementName "$($ElementProp.Name)" -xmlElementText $result."$($Property.Name)"."$($ElementProp.Name)" } } @@ -7071,18 +7074,18 @@ function Get-NsxManagerRole { param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/universalsync/configuration/role" - [System.Xml.XmlDocument]$result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $result -Query 'child::universalSyncRole') { + if (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $result -query 'child::universalSyncRole') { $result.universalSyncRole } @@ -7128,38 +7131,38 @@ function Set-NsxManagerRole { param ( - [Parameter (Mandatory=$True)] - #New Role for connected NSX Manager - [ValidateSet("Primary", "StandAlone")] - [String]$Role, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True)] + #New Role for connected NSX Manager + [ValidateSet("Primary", "StandAlone")] + [String]$Role, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) switch ($role) { "Primary" { $URI = "/api/2.0/universalsync/configuration/role?action=set-as-primary" } "StandAlone" { $URI = "/api/2.0/universalsync/configuration/role?action=set-as-standalone" } - Default { Throw "Not Implemented"} + Default { Throw "Not Implemented" } } - try { - $null = invoke-nsxwebrequest -method "post" -uri $URI -connection $connection + try { + $null = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection } Catch { $ParsedXmlError = $false if ( $_ -match '.*(\<\?xml version="1\.0" encoding="UTF-8"\?\>\s.*)' ) { if ( $matches[1] -as [xml] ) { $Error = [xml]$matches[1] - $ErrorCode = invoke-xpathquery -Node $error -QueryMethod SelectSingleNode -query "child::error/errorCode" + $ErrorCode = Invoke-XpathQuery -Node $error -QueryMethod SelectSingleNode -query "child::error/errorCode" if ( $errorCode.'#text' -eq '125023') { - write-warning $Error.error.details + Write-Warning $Error.error.details $ParsedXmlError = $true } } } - if ( -not $ParsedXmlError ) { + if ( -not $ParsedXmlError ) { #If we didnt get some XML out of the error that we parsed as expected... Throw "Failed setting NSX Manager role. $_" } @@ -7193,16 +7196,16 @@ function Invoke-NsxManagerSync { param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/universalsync/sync?action=invoke" - try { - $null = invoke-nsxwebrequest -method "post" -uri $URI -connection $connection + try { + $null = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection } catch { Throw "Failed to invoke synchronisation. $_" @@ -7230,18 +7233,18 @@ function Get-NsxManagerSyncStatus { param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/universalsync/status" - [System.Xml.XmlDocument]$result = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$result = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $result -Query 'child::replicationStatus') { + if (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $result -query 'child::replicationStatus') { $result.replicationStatus } @@ -7280,39 +7283,39 @@ function Add-NsxSecondaryManager { Adds the NSX Manager nsx-m-01b as a secondary to the currently connected primary NSX Manager and validates that the thumbprint presented by the server is as specified. #> - [CmdletBinding(DefaultParameterSetName="Credential")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - - param ( - - [Parameter (Mandatory=$True)] - #Hostname or IPAddress of the Standalone NSX Manger to be added - [ValidateNotNullorEmpty()] - [String]$NsxManager, - [Parameter (Mandatory=$False)] - #SHA1 hash of the NSX Manager certificate. Required unless -AcceptPresentedThumprint is specified. - [ValidateNotNullorEmpty()] - [String]$Thumbprint, - [Parameter (Mandatory=$False)] - #Accept any thumbprint presented by the server specified with -NsxManager. Insecure. - [Switch]$AcceptPresentedThumbprint, - [Parameter (Mandatory=$False, ParameterSetName="UserPass")] - #Username for NSX Manager to be added. A local account with SuperUser privileges is required. Defaults to admin. - [ValidateNotNullorEmpty()] - [String]$Username="admin", - [Parameter (Mandatory=$True, ParameterSetName="UserPass")] - #Password for NSX Manager to be added. A local account with SuperUser privileges is required. - [ValidateNotNullorEmpty()] - [String]$Password, - [Parameter (Mandatory=$False, ParameterSetName="Credential")] - #Credential object for NSX Manager to be added. A local account with SuperUser privileges is required. - [ValidateNotNullorEmpty()] - [pscredential]$Credential, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdletBinding(DefaultParameterSetName = "Credential")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + + param ( + + [Parameter (Mandatory = $True)] + #Hostname or IPAddress of the Standalone NSX Manger to be added + [ValidateNotNullorEmpty()] + [String]$NsxManager, + [Parameter (Mandatory = $False)] + #SHA1 hash of the NSX Manager certificate. Required unless -AcceptPresentedThumprint is specified. + [ValidateNotNullorEmpty()] + [String]$Thumbprint, + [Parameter (Mandatory = $False)] + #Accept any thumbprint presented by the server specified with -NsxManager. Insecure. + [Switch]$AcceptPresentedThumbprint, + [Parameter (Mandatory = $False, ParameterSetName = "UserPass")] + #Username for NSX Manager to be added. A local account with SuperUser privileges is required. Defaults to admin. + [ValidateNotNullorEmpty()] + [String]$Username = "admin", + [Parameter (Mandatory = $True, ParameterSetName = "UserPass")] + #Password for NSX Manager to be added. A local account with SuperUser privileges is required. + [ValidateNotNullorEmpty()] + [String]$Password, + [Parameter (Mandatory = $False, ParameterSetName = "Credential")] + #Credential object for NSX Manager to be added. A local account with SuperUser privileges is required. + [ValidateNotNullorEmpty()] + [pscredential]$Credential, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) #Validate connected Manager is role Primary @@ -7323,7 +7326,7 @@ function Add-NsxSecondaryManager { #Build cred object for default auth if user specified username/pass if ($PSCmdlet.ParameterSetName -eq "UserPass" ) { - $Credential = new-object System.Management.Automation.PSCredential($Username, $(ConvertTo-SecureString $Password -AsPlainText -Force)) + $Credential = New-Object System.Management.Automation.PSCredential($Username, $(ConvertTo-SecureString $Password -AsPlainText -Force)) } else { #We need user/pass to generate the xml for the primary NSX Manager. @@ -7365,8 +7368,8 @@ function Add-NsxSecondaryManager { $URI = "/api/2.0/universalsync/configuration/nsxmanagers" - try { - $response = invoke-nsxwebrequest -method "post" -body $NsxManagerInfoElement.OuterXml -uri $URI -connection $connection + try { + $response = Invoke-NsxWebRequest -method "post" -body $NsxManagerInfoElement.OuterXml -URI $URI -connection $connection $content = [xml]$response.content $content.nsxManagerInfo } @@ -7414,31 +7417,31 @@ function Get-NsxSecondaryManager { #> - [CmdletBinding(DefaultParameterSetName="Default")] + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$True, ParameterSetName="uuid")] - #UUID of Nsx Secondary Manager to return - [ValidateNotNullOrEmpty()] - [string]$Uuid, - [Parameter (Mandatory=$True, ParameterSetName="Name", Position=1)] - #Name of Nsx Secondary Manager to return - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ParameterSetName = "uuid")] + #UUID of Nsx Secondary Manager to return + [ValidateNotNullOrEmpty()] + [string]$Uuid, + [Parameter (Mandatory = $True, ParameterSetName = "Name", Position = 1)] + #Name of Nsx Secondary Manager to return + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/universalsync/configuration/nsxmanagers" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection try { $content = [xml]$response.content - if ( invoke-xpathquery -querymethod SelectSingleNode -Query "child::nsxManagerInfos/nsxManagerInfo" -Node $content ) { + if ( Invoke-XpathQuery -QueryMethod SelectSingleNode -query "child::nsxManagerInfos/nsxManagerInfo" -Node $content ) { switch ( $PSCmdlet.ParameterSetName ) { - "Name" { $content.nsxManagerInfos.nsxManagerInfo | where-object { $_.nsxManagerIp -match $Name}} - "Uuid" { $content.nsxManagerInfos.nsxManagerInfo | where-object { $_.uuid -eq $uuid}} + "Name" { $content.nsxManagerInfos.nsxManagerInfo | Where-Object { $_.nsxManagerIp -match $Name } } + "Uuid" { $content.nsxManagerInfos.nsxManagerInfo | Where-Object { $_.uuid -eq $uuid } } default { $content.nsxManagerInfos.nsxManagerInfo } } } @@ -7478,30 +7481,30 @@ function Remove-NsxSecondaryManager { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] #Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] #Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$true)] - #Secondary NSX Manager object to be removed as returned by Get-NsxSecondaryManager - [ValidateScript( { ValidateSecondaryManager $_ })] - [System.Xml.XmlElement]$SecondaryManager, - [Parameter (Mandatory=$False)] - #Confirm removal. - [switch]$Confirm=$True, - [Parameter (Mandatory=$False)] - #Force removal of a missing secondary. - [switch]$Force, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ValueFromPipeline = $true)] + #Secondary NSX Manager object to be removed as returned by Get-NsxSecondaryManager + [ValidateScript( { ValidateSecondaryManager $_ })] + [System.Xml.XmlElement]$SecondaryManager, + [Parameter (Mandatory = $False)] + #Confirm removal. + [switch]$Confirm = $True, + [Parameter (Mandatory = $False)] + #Force removal of a missing secondary. + [switch]$Force, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { if ( $confirm ) { - $message = "Removal of a secondary NSX Manager will prevent synchronisation of universal objects to the manager being removed." + $message = "Removal of a secondary NSX Manager will prevent synchronisation of universal objects to the manager being removed." $question = "Proceed with removal of secondary NSX Manager $($SecondaryManager.nsxManagerIp)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -7515,12 +7518,12 @@ function Remove-NsxSecondaryManager { if ( $PSBoundParameters.ContainsKey("Force")) { $URI = "/api/2.0/universalsync/configuration/nsxmanagers/$($SecondaryManager.uuid)?force=true" } - else{ + else { $URI = "/api/2.0/universalsync/configuration/nsxmanagers/$($SecondaryManager.uuid)" } - try { - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection + try { + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection } Catch { Throw "Failed removing secondary NSX Manager. $_" @@ -7528,7 +7531,7 @@ function Remove-NsxSecondaryManager { } } - end{} + end {} } function Wait-NsxControllerJob { @@ -7560,19 +7563,19 @@ function Wait-NsxControllerJob { #> param ( - [Parameter (Mandatory=$true)] - #Job Id string as returned from the api - [string]$JobId, - [Parameter (Mandatory=$false)] - #Seconds to wait before declaring a timeout. Timeout defaults to 800 seconds, which is longer than the NSX internal timeout and rollback of a failed controller deployment of around 720 seconds. - [int]$WaitTimeout=800, - [Parameter (Mandatory=$false)] - #Do we prompt user an allow them to reset the timeout timer, or throw on timeout - [switch]$FailOnTimeout=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true)] + #Job Id string as returned from the api + [string]$JobId, + [Parameter (Mandatory = $false)] + #Seconds to wait before declaring a timeout. Timeout defaults to 800 seconds, which is longer than the NSX internal timeout and rollback of a failed controller deployment of around 720 seconds. + [int]$WaitTimeout = 800, + [Parameter (Mandatory = $false)] + #Do we prompt user an allow them to reset the timeout timer, or throw on timeout + [switch]$FailOnTimeout = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) # Seriously - the NSX Task framework is the work of the devil. @@ -7587,18 +7590,18 @@ function Wait-NsxControllerJob { # This really underscores the flexibility of having a generic Wait-NsxJob cmdlet I think :) FIGJAM... :) $WaitJobArgs = @{ - "jobid" = $jobid - "JobStatusUri" = "/api/2.0/services/taskservice/job" + "jobid" = $jobid + "JobStatusUri" = "/api/2.0/services/taskservice/job" "CompleteCriteria" = { $job.jobInstances.jobInstance.status -eq "COMPLETED" } - "FailCriteria" = { + "FailCriteria" = { $job.jobInstances.jobInstance.status -eq "FAILED" } "StatusExpression" = { $execTask = @() $StatusMessage = "" - $execTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | where-object { $_.taskStatus -eq "EXECUTING" }) + $execTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | Where-Object { $_.taskStatus -eq "EXECUTING" }) if ( $exectask.count -eq 1) { $StatusMessage = "$($execTask.name) - $($execTask.taskStatus)" } @@ -7607,10 +7610,10 @@ function Wait-NsxControllerJob { } $StatusMessage } - "ErrorExpression" = { + "ErrorExpression" = { $failTask = @() $failMessage = "" - $failTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | where-object { $_.taskStatus -eq "FAILED" }) + $failTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | Where-Object { $_.taskStatus -eq "FAILED" }) if ( $failTask.count -eq 1) { $failMessage = "Failed Task : $($failTask.name) - $($failTask.statusMessage)" } @@ -7619,9 +7622,9 @@ function Wait-NsxControllerJob { } $failMessage } - "WaitTimeout" = $WaitTimeout - "FailOnTimeout" = $FailOnTimeout - "Connection" = $Connection + "WaitTimeout" = $WaitTimeout + "FailOnTimeout" = $FailOnTimeout + "Connection" = $Connection } Wait-NsxJob @WaitJobArgs @@ -7660,64 +7663,64 @@ function New-NsxController { A secondary or tertiary controller requires a Password to NOT be defined. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$False)] - # Controller Name. Will be autogenerated in form of ControllerN if not provided. - [Alias ("Name")] - [string]$ControllerName, - [Parameter (Mandatory=$False)] - # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$True)] - # Pre Created IP Pool object from which controller IP will be allocated - [ValidateScript({ ValidateIpPool $_ })] - [System.Xml.XmlElement]$IpPool, - [Parameter (Mandatory=$true,ParameterSetName="ResourcePool")] - # vSphere DRS Resource Pool into which to deploy Controller VM - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, - [Parameter (Mandatory=$true,ParameterSetName="Cluster")] - # vSphere Cluster into which to deploy the Controller VM - [ValidateScript({ - if ( $_ -eq $null ) { throw "Must specify Cluster."} - if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled."} + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $False)] + # Controller Name. Will be autogenerated in form of ControllerN if not provided. + [Alias ("Name")] + [string]$ControllerName, + [Parameter (Mandatory = $False)] + # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $True)] + # Pre Created IP Pool object from which controller IP will be allocated + [ValidateScript( { ValidateIpPool $_ })] + [System.Xml.XmlElement]$IpPool, + [Parameter (Mandatory = $true, ParameterSetName = "ResourcePool")] + # vSphere DRS Resource Pool into which to deploy Controller VM + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, + [Parameter (Mandatory = $true, ParameterSetName = "Cluster")] + # vSphere Cluster into which to deploy the Controller VM + [ValidateScript( { + if ( $_ -eq $null ) { throw "Must specify Cluster." } + if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled." } $true })] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$true)] - # vSphere Datastore into which to deploy the Controller VM - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, - [Parameter (Mandatory=$true)] - # vSphere DVPortGroup OR NSX Logical Switch object to connect the Controller VM to - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$PortGroup, - [Parameter (Mandatory=$False)] - # Controller Password (Must be same on all controllers) - [string]$Password, - [Parameter ( Mandatory=$False)] - # Block until Controller deployment job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) - # Useful if automating the deployment of multiple controllers (first must be running before deploying second controller) - # so you dont have to write looping code to check status of controller before continuing. - # NOTE: Not waiting means we do NOT return a controller object! - [switch]$Wait=$false, - [Parameter ( Mandatory=$False)] - # Timeout waiting for controller to become 'RUNNING' before user is prompted to continue or cancel. Defaults to 800 seconds to exceed the normal NSX rollback timeout of 720 seconds. - [int]$WaitTimeout = 800, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $true)] + # vSphere Datastore into which to deploy the Controller VM + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, + [Parameter (Mandatory = $true)] + # vSphere DVPortGroup OR NSX Logical Switch object to connect the Controller VM to + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$PortGroup, + [Parameter (Mandatory = $False)] + # Controller Password (Must be same on all controllers) + [string]$Password, + [Parameter ( Mandatory = $False)] + # Block until Controller deployment job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) + # Useful if automating the deployment of multiple controllers (first must be running before deploying second controller) + # so you dont have to write looping code to check status of controller before continuing. + # NOTE: Not waiting means we do NOT return a controller object! + [switch]$Wait = $false, + [Parameter ( Mandatory = $False)] + # Timeout waiting for controller to become 'RUNNING' before user is prompted to continue or cancel. Defaults to 800 seconds to exceed the normal NSX rollback timeout of 720 seconds. + [int]$WaitTimeout = 800, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - $Ctrlcount = get-nsxcontroller -connection $Connection | measure-object + $Ctrlcount = Get-NsxController -Connection $Connection | Measure-Object if ( ($PSBoundParameters.ContainsKey("Password")) -and ($Ctrlcount.count -gt 0)) { - write-warning "A controller is already deployed but a password argument was specified to New-NsxController. The new controller will be configured with the same password as the initial one and the specified password ignored" + Write-Warning "A controller is already deployed but a password argument was specified to New-NsxController. The new controller will be configured with the same password as the initial one and the specified password ignored" } if ( -not ($PSBoundParameters.ContainsKey("Password")) -and ($Ctrlcount.count -eq 0)) { Throw "A password is required to deploy the inital controller. Try again and specify the -Password parameter." @@ -7726,7 +7729,7 @@ function New-NsxController { # AutoGen a sane controller name. NSX 6.4 api makes this mandatory, but I want the same requirement to avoid backward breaking change in PowerNSX. Eng take note! :| if ( -not $PsBoundParameters.ContainsKey("ControllerName")) { $ControllerName = "Controller$($Ctrlcount.count + 1)" - write-warning "Using autogenerated name for new controller : $ControllerName" + Write-Warning "Using autogenerated name for new controller : $ControllerName" } } @@ -7753,7 +7756,7 @@ function New-NsxController { } # Check for presence of optional controller name - if ($PSBoundParameters.ContainsKey("Password") -and ($Ctrlcount.count -eq 0)) {Add-XmlElement -xmlRoot $ControllerSpec -xmlElementName "password" -xmlElementText $Password.ToString()} + if ($PSBoundParameters.ContainsKey("Password") -and ($Ctrlcount.count -eq 0)) { Add-XmlElement -xmlRoot $ControllerSpec -xmlElementName "password" -xmlElementText $Password.ToString() } Add-XmlElement -xmlRoot $ControllerSpec -xmlElementName "datastoreId" -xmlElementText $DataStore.ExtensionData.Moref.value.ToString() Add-XmlElement -xmlRoot $ControllerSpec -xmlElementName "networkId" -xmlElementText $PortGroup.ExtensionData.Moref.Value.ToString() Add-XmlElement -xmlRoot $ControllerSpec -xmlElementName "name" -xmlElementText $ControllerName @@ -7762,7 +7765,7 @@ function New-NsxController { $body = $ControllerSpec.OuterXml if ( $confirm ) { - $message = "Adding a new controller to the NSX controller cluster. ONLY three controllers are supported. Then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who being naughty in My sight, shall snuff it." + $message = "Adding a new controller to the NSX controller cluster. ONLY three controllers are supported. Then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who being naughty in My sight, shall snuff it." $question = "Proceed with controller deployment?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -7772,9 +7775,9 @@ function New-NsxController { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Deploying NSX Controller" + Write-Progress -Activity "Deploying NSX Controller" try { - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection } catch { throw "Controller deployment failed. $_" @@ -7786,16 +7789,16 @@ function New-NsxController { #The post is ansync - the controller deployment can fail after the api accepts the post. we need to check on the status of the job. if ( $Wait ) { - #Get the new controller id so we can get its status later... + #Get the new controller id so we can get its status later... $controllerid = $response.Headers["location"] -replace "/api/2.0/vdn/controller/" $jobid = $response.content - write-debug "$($MyInvocation.MyCommand.Name) : Controller deployment job $jobid returned in post response" + Write-Debug "$($MyInvocation.MyCommand.Name) : Controller deployment job $jobid returned in post response" #First we wait for NSX job framework to give us the needful try { - Wait-NsxControllerJob -Jobid $JobID -Connection $Connection -WaitTimeout $WaitTimeout - Get-NsxController -connection $connection -objectid $controllerId + Wait-NsxControllerJob -JobId $JobID -Connection $Connection -WaitTimeout $WaitTimeout + Get-NsxController -Connection $connection -ObjectId $controllerId } catch { throw "Controller deployment job failed. $_" @@ -7832,24 +7835,25 @@ function Get-NsxController { #> param ( - [Parameter (Mandatory=$false,Position=1)] - #ObjectId of the NSX Controller to return. - [string]$ObjectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, Position = 1)] + #ObjectId of the NSX Controller to return. + [string]$ObjectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/vdn/controller" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::controllers/controller')) { + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::controllers/controller')) { if ( $PsBoundParameters.containsKey('objectId')) { - $response.controllers.controller | where-object { $_.Id -eq $ObjectId } - } else { + $response.controllers.controller | Where-Object { $_.Id -eq $ObjectId } + } + else { $response.controllers.controller } } @@ -7879,33 +7883,33 @@ function Remove-NsxController { Removes the controller with id controller-3 #> - [CmdletBinding(DefaultParameterSetName="Object")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true, ValueFromPipeline=$true,Position=1, ParameterSetName="Object")] - #PowerNSX Controller object obtained via Get-NsxController - [ValidateScript({ ValidateController $_ })] - [System.Xml.XmlElement]$Controller, - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - #ObjectID of the controller to remove - [ValidateNotNullorEmpty()] - [string]$objectId, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter ( Mandatory=$False)] - #Block until Controller Removal job is COMPLETED (Will timeout with prompt after 720 seconds) - #Useful if automating the removal of multiple controllers (first must be removed before removing second controller) - #so you dont have to write looping code to check status of controller before continuing. - [switch]$Wait=$false, - [Parameter (Mandatory=$false)] - #Force the removal of the last controller. WARNING THIS WILL IMPACT LOGICAL SWITCHING AND ROUTING FUNCTIONALITY - [switch]$Force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdletBinding(DefaultParameterSetName = "Object")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1, ParameterSetName = "Object")] + #PowerNSX Controller object obtained via Get-NsxController + [ValidateScript( { ValidateController $_ })] + [System.Xml.XmlElement]$Controller, + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + #ObjectID of the controller to remove + [ValidateNotNullorEmpty()] + [string]$objectId, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter ( Mandatory = $False)] + #Block until Controller Removal job is COMPLETED (Will timeout with prompt after 720 seconds) + #Useful if automating the removal of multiple controllers (first must be removed before removing second controller) + #so you dont have to write looping code to check status of controller before continuing. + [switch]$Wait = $false, + [Parameter (Mandatory = $false)] + #Force the removal of the last controller. WARNING THIS WILL IMPACT LOGICAL SWITCHING AND ROUTING FUNCTIONALITY + [switch]$Force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -7917,7 +7921,7 @@ function Remove-NsxController { } if ( $confirm ) { - $message = "Controller removal will impact the high availability of the NSX control plane." + $message = "Controller removal will impact the high availability of the NSX control plane." $question = "Proceed with removal of Controller $($objectId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -7929,9 +7933,9 @@ function Remove-NsxController { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/2.0/vdn/controller/$($objectId)?forceRemoval=$force" - Write-Progress -activity "Remove Controller $objectId" + Write-Progress -Activity "Remove Controller $objectId" try { - $response = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection } catch { throw "Controller deployment failed. $_" @@ -7944,17 +7948,17 @@ function Remove-NsxController { #The post is ansync - the controller deployment can fail after the api accepts the post. we need to check on the status of the job. if ( $Wait ) { $jobid = $response.content - write-debug "$($MyInvocation.MyCommand.Name) : Controller deployment job $jobid returned in post response" + Write-Debug "$($MyInvocation.MyCommand.Name) : Controller deployment job $jobid returned in post response" #First we wait for NSX job framework to give us the needful try { - Wait-NsxControllerJob -Jobid $JobID -Connection $Connection + Wait-NsxControllerJob -JobId $JobID -Connection $Connection } catch { throw "Controller removal job failed. $_" } } - Write-Progress -activity "Remove Controller $objectId" -completed + Write-Progress -Activity "Remove Controller $objectId" -Completed } } @@ -7995,28 +7999,28 @@ function Invoke-NsxControllerStateUpdate { param ( - [Parameter ( Mandatory=$False)] - # Block until the job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) - # Useful if automating the re-deployment of the controller cluster so you dont have to write - # looping code to check status of the job before continuing. - [switch]$Wait=$false, - [Parameter(Mandatory=$false)] - # If job reaches -WaitTimeout without failing or completing, do we prompt, or fail with error? - [switch]$FailOnTimeout=$false, - [Parameter(Mandatory=$false)] - # Seconds to wait for connection job to complete. Defaults to 30 seconds. - [int]$WaitTimeout=30, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter ( Mandatory = $False)] + # Block until the job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) + # Useful if automating the re-deployment of the controller cluster so you dont have to write + # looping code to check status of the job before continuing. + [switch]$Wait = $false, + [Parameter(Mandatory = $false)] + # If job reaches -WaitTimeout without failing or completing, do we prompt, or fail with error? + [switch]$FailOnTimeout = $false, + [Parameter(Mandatory = $false)] + # Seconds to wait for connection job to complete. Defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/vdn/controller/synchronize" - try { - $response = invoke-nsxwebrequest -method "put" -uri $URI -connection $connection + try { + $response = Invoke-NsxWebRequest -method "put" -URI $URI -connection $connection } catch { Throw "Failed to invoke controller state update. $_" @@ -8030,17 +8034,17 @@ function Invoke-NsxControllerStateUpdate { if ( $Wait ) { $jobid = $response.content - write-debug "$($MyInvocation.MyCommand.Name) : Controller Update State job $jobid returned in post response" + Write-Debug "$($MyInvocation.MyCommand.Name) : Controller Update State job $jobid returned in post response" #First we wait for NSX job framework to give us the needful try { - Wait-NsxGenericJob -Jobid $response.Content -Connection $Connection -WaitTimeout $WaitTimeout -FailOnTimeout:$FailOnTimeout + Wait-NsxGenericJob -JobId $response.Content -Connection $Connection -WaitTimeout $WaitTimeout -FailOnTimeout:$FailOnTimeout } catch { throw "Controller Update State failed. $_" } } - Write-progress -activity "Controller Update State." -completed + Write-Progress -Activity "Controller Update State." -Completed } function New-NsxIpPool { @@ -8067,44 +8071,44 @@ function New-NsxIpPool { #> - param ( - - [Parameter (Mandatory=$true, Position=1)] - #Name of IP Pool - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true)] - #Gateway address - [ValidateNotNullOrEmpty()] - [ipAddress]$Gateway, - [Parameter (Mandatory=$true)] - #Prefix length of network address (1-31) - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - #IP Address of first DNS Server - [ValidateNotNullOrEmpty()] - [ipAddress]$DnsServer1, - [Parameter (Mandatory=$false)] - #IP Address of second DNS Server - [ValidateNotNullOrEmpty()] - [ipAddress]$DnsServer2, - [Parameter (Mandatory=$false)] - #DNS Domain Name - [ValidateNotNullOrEmpty()] - [string]$DnsSuffix, - [Parameter (Mandatory=$true)] - #First Valid Address in the pool - [ValidateNotNullOrEmpty()] - [ipaddress]$StartAddress, - [Parameter (Mandatory=$true)] - #Last Valid Address in the pool - [ValidateNotNullOrEmpty()] - [ipaddress]$EndAddress, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + param ( + + [Parameter (Mandatory = $true, Position = 1)] + #Name of IP Pool + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true)] + #Gateway address + [ValidateNotNullOrEmpty()] + [ipAddress]$Gateway, + [Parameter (Mandatory = $true)] + #Prefix length of network address (1-31) + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + #IP Address of first DNS Server + [ValidateNotNullOrEmpty()] + [ipAddress]$DnsServer1, + [Parameter (Mandatory = $false)] + #IP Address of second DNS Server + [ValidateNotNullOrEmpty()] + [ipAddress]$DnsServer2, + [Parameter (Mandatory = $false)] + #DNS Domain Name + [ValidateNotNullOrEmpty()] + [string]$DnsSuffix, + [Parameter (Mandatory = $true)] + #First Valid Address in the pool + [ValidateNotNullOrEmpty()] + [ipaddress]$StartAddress, + [Parameter (Mandatory = $true)] + #Last Valid Address in the pool + [ValidateNotNullOrEmpty()] + [ipaddress]$EndAddress, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -8113,7 +8117,7 @@ function New-NsxIpPool { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlPool = $XMLDoc.CreateElement("ipamAddressPool") - $xmlDoc.Appendchild($xmlPool) | out-null + $xmlDoc.Appendchild($xmlPool) | Out-Null #Mandatory and default params Add-XmlElement -xmlRoot $xmlPool -xmlElementName "name" -xmlElementText $Name @@ -8123,8 +8127,8 @@ function New-NsxIpPool { #Start/End of range $xmlIpRanges = $xmlDoc.CreateElement("ipRanges") $xmlIpRange = $xmlDoc.CreateElement("ipRangeDto") - $xmlPool.Appendchild($xmlIpRanges) | out-null - $xmlIpRanges.Appendchild($xmlIpRange) | out-null + $xmlPool.Appendchild($xmlIpRanges) | Out-Null + $xmlIpRanges.Appendchild($xmlIpRange) | Out-Null Add-XmlElement -xmlRoot $xmlIpRange -xmlElementName "startAddress" -xmlElementText $StartAddress Add-XmlElement -xmlRoot $xmlIpRange -xmlElementName "endAddress" -xmlElementText $EndAddress @@ -8143,11 +8147,11 @@ function New-NsxIpPool { # #Do the post $body = $xmlPool.OuterXml $URI = "/api/2.0/services/ipam/pools/scope/globalroot-0" - Write-Progress -activity "Creating IP Pool." - $response = invoke-NsxWebRequest -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Creating IP Pool." -completed + Write-Progress -Activity "Creating IP Pool." + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating IP Pool." -Completed - Get-NsxIpPool -objectId $response.content -connection $connection + Get-NsxIpPool -ObjectId $response.content -Connection $connection } @@ -8177,40 +8181,40 @@ function Get-NsxIpPool { #> - [CmdletBinding(DefaultParameterSetName="Name")] + [CmdletBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$false,Position=1,ParameterSetName = "Name")] - #Name of the Pool to retrieve - [string]$Name, - [Parameter (Mandatory=$false, ParameterSetName = "ObjectId")] - #ObjectID of the Pool to retrieve - [string]$ObjectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Name")] + #Name of the Pool to retrieve + [string]$Name, + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + #ObjectID of the Pool to retrieve + [string]$ObjectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) if ( $PsBoundParameters.ContainsKey('ObjectId')) { $URI = "/api/2.0/services/ipam/pools/$ObjectId" - $response = invoke-NsxWebRequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection [system.xml.xmlDocument]$content = $response.content - if (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $content -Query 'child::ipamAddressPool'){ + if (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $content -query 'child::ipamAddressPool') { $content.ipamAddressPool } } else { $URI = "/api/2.0/services/ipam/pools/scope/globalroot-0" - $response = invoke-NsxWebRequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection [system.xml.xmlDocument]$content = $response.content - if (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $content -Query 'child::ipamAddressPools/ipamAddressPool'){ + if (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $content -query 'child::ipamAddressPools/ipamAddressPool') { If ( $PsBoundParameters.ContainsKey("Name")) { - $content.ipamAddressPools.ipamAddressPool | where-object { $_.name -eq $Name } + $content.ipamAddressPools.ipamAddressPool | Where-Object { $_.name -eq $Name } } else { $content.ipamAddressPools.ipamAddressPool @@ -8234,47 +8238,47 @@ function Get-NsxVdsContext { #> - [CmdletBinding(DefaultParameterSetName="Name")] + [CmdletBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$false,Position=1,ParameterSetName = "Name")] - #Name of VDS context to retrieve - [string]$Name, - [Parameter (Mandatory=$false, ParameterSetName = "ObjectId")] - #ObjectId of VDS context to retrieve - [string]$ObjectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Name")] + #Name of VDS context to retrieve + [string]$Name, + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + #ObjectId of VDS context to retrieve + [string]$ObjectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) if ( $PsBoundParameters.ContainsKey('ObjectId')) { $URI = "/api/2.0/vdn/switches/$ObjectId" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - If ( $response | get-member -memberType properties vdsContext ) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + If ( $response | Get-Member -MemberType properties vdsContext ) { $response.vdsContext } } else { $URI = "/api/2.0/vdn/switches" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection If ( $PsBoundParameters.ContainsKey("Name")) { if ( $response.vdsContexts -as [system.xml.xmlelement]) { - If ( $response | get-member -memberType properties vdsContexts ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response.vdsContexts -Query "descendant::vdsContext")) { - $response.vdsContexts.vdsContext | where-object { $_.switch.name -eq $Name } + If ( $response | Get-Member -MemberType properties vdsContexts ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response.vdsContexts -query "descendant::vdsContext")) { + $response.vdsContexts.vdsContext | Where-Object { $_.switch.name -eq $Name } } } } } else { if ( $response.vdsContexts -as [system.xml.xmlelement]) { - If ( $response | get-member -memberType properties vdsContexts ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response.vdsContexts -Query "descendant::vdsContext")) { + If ( $response | Get-Member -MemberType properties vdsContexts ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response.vdsContexts -query "descendant::vdsContext")) { $response.vdsContexts.vdsContext } } @@ -8298,24 +8302,24 @@ function New-NsxVdsContext { #> - param ( + param ( - [Parameter (Mandatory=$true, Position=1)] - #PowerCLI VDSwitch Object to configure for NSX - [ValidateScript({ ValidateDistributedSwitch $_ })] - [object]$VirtualDistributedSwitch, - [Parameter (Mandatory=$true)] - #Teaming configuration for NSX Logical Switches - [ValidateSet("FAILOVER_ORDER", "ETHER_CHANNEL", "LACP_ACTIVE", "LACP_PASSIVE","LOADBALANCE_LOADBASED", "LOADBALANCE_SRCID", "LOADBALANCE_SRCMAC", "LACP_V2",IgnoreCase=$false)] - [string]$Teaming, - [Parameter (Mandatory=$true)] - #MTU of VTEP interfaces created on the specified VDS. Minimum of 1600 bytes is required. - [ValidateRange(1600,9000)] - [int]$Mtu, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, Position = 1)] + #PowerCLI VDSwitch Object to configure for NSX + [ValidateScript( { ValidateDistributedSwitch $_ })] + [object]$VirtualDistributedSwitch, + [Parameter (Mandatory = $true)] + #Teaming configuration for NSX Logical Switches + [ValidateSet("FAILOVER_ORDER", "ETHER_CHANNEL", "LACP_ACTIVE", "LACP_PASSIVE", "LOADBALANCE_LOADBASED", "LOADBALANCE_SRCID", "LOADBALANCE_SRCMAC", "LACP_V2", IgnoreCase = $false)] + [string]$Teaming, + [Parameter (Mandatory = $true)] + #MTU of VTEP interfaces created on the specified VDS. Minimum of 1600 bytes is required. + [ValidateRange(1600, 9000)] + [int]$Mtu, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -8324,22 +8328,22 @@ function New-NsxVdsContext { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlContext = $XMLDoc.CreateElement("nwFabricFeatureConfig") - $xmlDoc.Appendchild($xmlContext) | out-null + $xmlDoc.Appendchild($xmlContext) | Out-Null Add-XmlElement -xmlRoot $xmlContext -xmlElementName "featureId" -xmlElementText "com.vmware.vshield.vsm.vxlan" #configSpec $xmlResourceConfig = $xmlDoc.CreateElement("resourceConfig") $xmlConfigSpec = $xmlDoc.CreateElement("configSpec") - $xmlConfigSpec.SetAttribute("class","vdsContext") - $xmlContext.Appendchild($xmlResourceConfig) | out-null - $xmlResourceConfig.Appendchild($xmlConfigSpec) | out-null + $xmlConfigSpec.SetAttribute("class", "vdsContext") + $xmlContext.Appendchild($xmlResourceConfig) | Out-Null + $xmlResourceConfig.Appendchild($xmlConfigSpec) | Out-Null Add-XmlElement -xmlRoot $xmlConfigSpec -xmlElementName "teaming" -xmlElementText $Teaming.toString() Add-XmlElement -xmlRoot $xmlConfigSpec -xmlElementName "mtu" -xmlElementText $Mtu.ToString() $xmlSwitch = $xmlDoc.CreateElement("switch") - $xmlConfigSpec.Appendchild($xmlSwitch) | out-null + $xmlConfigSpec.Appendchild($xmlSwitch) | Out-Null Add-XmlElement -xmlRoot $xmlSwitch -xmlElementName "objectId" -xmlElementText $VirtualDistributedSwitch.Extensiondata.Moref.Value.ToString() @@ -8348,11 +8352,11 @@ function New-NsxVdsContext { # #Do the post $body = $xmlContext.OuterXml $URI = "/api/2.0/nwfabric/configure" - Write-Progress -activity "Configuring VDS context on VDS $($VirtualDistributedSwitch.Name)." - $null = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Configuring VDS context on VDS $($VirtualDistributedSwitch.Name)." -completed + Write-Progress -Activity "Configuring VDS context on VDS $($VirtualDistributedSwitch.Name)." + $null = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Configuring VDS context on VDS $($VirtualDistributedSwitch.Name)." -Completed - Get-NsxVdsContext -objectId $VirtualDistributedSwitch.Extensiondata.Moref.Value -connection $connection + Get-NsxVdsContext -ObjectId $VirtualDistributedSwitch.Extensiondata.Moref.Value -Connection $connection } @@ -8374,20 +8378,20 @@ function Remove-NsxVdsContext { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #NSX VDS Context Object ID to remove - [ValidateScript({ ValidateVdsContext $_ })] - [System.Xml.XmlElement]$VdsContext, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #NSX VDS Context Object ID to remove + [ValidateScript( { ValidateVdsContext $_ })] + [System.Xml.XmlElement]$VdsContext, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -8398,7 +8402,7 @@ function Remove-NsxVdsContext { process { if ( $confirm ) { - $message = "Vds Context removal is permanent." + $message = "Vds Context removal is permanent." $question = "Proceed with removal of Vds Context for Vds $($VdsContext.Switch.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8410,9 +8414,9 @@ function Remove-NsxVdsContext { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/2.0/vdn/switches/$($VdsContext.Switch.ObjectId)" - Write-Progress -activity "Remove Vds Context for Vds $($VdsContext.Switch.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Remove Vds Context for Vds $($VdsContext.Switch.Name)" -completed + Write-Progress -Activity "Remove Vds Context for Vds $($VdsContext.Switch.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Vds Context for Vds $($VdsContext.Switch.Name)" -Completed } } @@ -8448,27 +8452,27 @@ function New-NsxClusterVxlanConfig { param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateDistributedSwitch $_ })] - [object]$VirtualDistributedSwitch, - [Parameter (Mandatory=$False)] - [ValidateScript({ ValidateIpPool $_ })] - [System.Xml.XmlElement]$IpPool, - [Parameter (Mandatory=$False)] - [int]$VlanId="", - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [int]$VtepCount, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [int]$VxlanPrepTimeout=120, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateDistributedSwitch $_ })] + [object]$VirtualDistributedSwitch, + [Parameter (Mandatory = $False)] + [ValidateScript( { ValidateIpPool $_ })] + [System.Xml.XmlElement]$IpPool, + [Parameter (Mandatory = $False)] + [int]$VlanId = "", + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [int]$VtepCount, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [int]$VxlanPrepTimeout = 120, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -8478,7 +8482,7 @@ function New-NsxClusterVxlanConfig { #Check that the VDS has a VDS context in NSX and is configured. try { - $vdscontext = Get-NsxVdsContext -objectId $VirtualDistributedSwitch.Extensiondata.MoRef.Value -connection $connection + $vdscontext = Get-NsxVdsContext -ObjectId $VirtualDistributedSwitch.Extensiondata.MoRef.Value -Connection $connection } catch { throw "Specified VDS is not configured for NSX. Use New-NsxVdsContext to configure the VDS and try again." @@ -8487,16 +8491,16 @@ function New-NsxClusterVxlanConfig { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlContext = $XMLDoc.CreateElement("nwFabricFeatureConfig") - $xmlDoc.Appendchild($xmlContext) | out-null + $xmlDoc.Appendchild($xmlContext) | Out-Null Add-XmlElement -xmlRoot $xmlContext -xmlElementName "featureId" -xmlElementText "com.vmware.vshield.vsm.vxlan" #cluster configSpec $xmlResourceConfig = $xmlDoc.CreateElement("resourceConfig") $xmlConfigSpec = $xmlDoc.CreateElement("configSpec") - $xmlConfigSpec.SetAttribute("class","clusterMappingSpec") - $xmlContext.Appendchild($xmlResourceConfig) | out-null - $xmlResourceConfig.Appendchild($xmlConfigSpec) | out-null + $xmlConfigSpec.SetAttribute("class", "clusterMappingSpec") + $xmlContext.Appendchild($xmlResourceConfig) | Out-Null + $xmlResourceConfig.Appendchild($xmlConfigSpec) | Out-Null if ( $PSBoundParameters.ContainsKey('IpPool')) { Add-XmlElement -xmlRoot $xmlConfigSpec -xmlElementName "ipPoolId" -xmlElementText $IpPool.objectId.toString() @@ -8505,7 +8509,7 @@ function New-NsxClusterVxlanConfig { Add-XmlElement -xmlRoot $xmlConfigSpec -xmlElementName "vmknicCount" -xmlElementText $VtepCount.ToString() $xmlSwitch = $xmlDoc.CreateElement("switch") - $xmlConfigSpec.Appendchild($xmlSwitch) | out-null + $xmlConfigSpec.Appendchild($xmlSwitch) | Out-Null Add-XmlElement -xmlRoot $xmlSwitch -xmlElementName "objectId" -xmlElementText $VirtualDistributedSwitch.Extensiondata.Moref.Value.ToString() Add-XmlElement -xmlRoot $xmlResourceConfig -xmlElementName "resourceId" -xmlElementText $Cluster.Extensiondata.Moref.Value.ToString() @@ -8514,29 +8518,29 @@ function New-NsxClusterVxlanConfig { # switch configSpec $xmlvdsResourceConfig = $xmlDoc.CreateElement("resourceConfig") $xmlvdsConfigSpec = $xmlDoc.CreateElement("configSpec") - $xmlvdsConfigSpec.SetAttribute("class","vdsContext") - $xmlContext.Appendchild($xmlvdsResourceConfig) | out-null - $xmlvdsResourceConfig.Appendchild($xmlvdsConfigSpec) | out-null + $xmlvdsConfigSpec.SetAttribute("class", "vdsContext") + $xmlContext.Appendchild($xmlvdsResourceConfig) | Out-Null + $xmlvdsResourceConfig.Appendchild($xmlvdsConfigSpec) | Out-Null Add-XmlElement -xmlRoot $xmlvdsConfigSpec -xmlElementName "mtu" -xmlElementText $vdsContext.mtu Add-XmlElement -xmlRoot $xmlvdsConfigSpec -xmlElementName "teaming" -xmlElementText $vdsContext.teaming $xmlvdsSwitch = $xmlDoc.CreateElement("switch") - $xmlvdsConfigSpec.Appendchild($xmlvdsSwitch) | out-null + $xmlvdsConfigSpec.Appendchild($xmlvdsSwitch) | Out-Null Add-XmlElement -xmlRoot $xmlvdsSwitch -xmlElementName "objectId" -xmlElementText $VirtualDistributedSwitch.Extensiondata.Moref.Value.ToString() Add-XmlElement -xmlRoot $xmlvdsResourceConfig -xmlElementName "resourceId" -xmlElementText $VirtualDistributedSwitch.Extensiondata.Moref.Value.ToString() - Write-Progress -id 1 -activity "Configuring VXLAN on cluster $($Cluster.Name)." -status "In Progress..." + Write-Progress -Id 1 -Activity "Configuring VXLAN on cluster $($Cluster.Name)." -Status "In Progress..." # #Do the post $body = $xmlContext.OuterXml $URI = "/api/2.0/nwfabric/configure" - $null = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection + $null = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection #Get Initial Status - $status = $cluster | get-NsxClusterStatus -connection $connection + $status = $cluster | Get-NsxClusterStatus -Connection $connection $hostprep = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.nwfabric.hostPrep' -statusxml $status $fw = Get-FeatureStatus -featurestring 'com.vmware.vshield.firewall' -statusxml $status $messagingInfra = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.messagingInfra' -statusxml $status @@ -8544,36 +8548,36 @@ function New-NsxClusterVxlanConfig { $timer = 0 while ( ($hostprep -ne 'GREEN') -or - ($fw -ne 'GREEN') -or - ($messagingInfra -ne 'GREEN') -or - ($VxlanConfig -ne 'GREEN')) { + ($fw -ne 'GREEN') -or + ($messagingInfra -ne 'GREEN') -or + ($VxlanConfig -ne 'GREEN')) { - start-sleep $VxlanWaitTime + Start-Sleep $VxlanWaitTime $timer += $VxlanWaitTime #Get Status - $status = $cluster | get-NsxClusterStatus -connection $connection + $status = $cluster | Get-NsxClusterStatus -Connection $connection $hostprep = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.nwfabric.hostPrep' -statusxml $status $fw = Get-FeatureStatus -featurestring 'com.vmware.vshield.firewall' -statusxml $status $messagingInfra = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.messagingInfra' -statusxml $status $VxlanConfig = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.vxlan' -statusxml $status #Check Status - if ( $hostprep -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 2 -activity "Vib Install Status: $hostprep" -status $status + if ( $hostprep -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 2 -Activity "Vib Install Status: $hostprep" -Status $status - if ( $fw -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 3 -activity "Firewall Install Status: $fw" -status $status + if ( $fw -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 3 -Activity "Firewall Install Status: $fw" -Status $status - if ( $messagingInfra -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 4 -activity "Messaging Infra Status: $messagingInfra" -status $status + if ( $messagingInfra -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 4 -Activity "Messaging Infra Status: $messagingInfra" -Status $status - if ( $VxlanConfig -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 5 -activity "VXLAN Config Status: $VxlanConfig" -status $status + if ( $VxlanConfig -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 5 -Activity "VXLAN Config Status: $VxlanConfig" -Status $status if ($Timer -ge $VxlanPrepTimeout) { - $message = "Cluster $($cluster.name) preparation has not completed within the timeout period." + $message = "Cluster $($cluster.name) preparation has not completed within the timeout period." $question = "Continue waiting (y) or quit (n)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8588,12 +8592,12 @@ function New-NsxClusterVxlanConfig { } } - Write-Progress -parentid 1 -id 2 -activity "Vib Install Status: $hostprep" -completed - Write-Progress -parentid 1 -id 3 -activity "Firewall Install Status: $fw" -completed - Write-Progress -parentid 1 -id 4 -activity "Messaging Infra Status: $messagingInfra" -completed - Write-Progress -parentid 1 -id 5 -activity "VXLAN Config Status: $VxlanConfig" -completed - Write-Progress -id 1 -activity "Configuring VXLAN on cluster $($Cluster.Name)." -completed - $cluster | get-NsxClusterStatus -connection $connection + Write-Progress -ParentId 1 -Id 2 -Activity "Vib Install Status: $hostprep" -Completed + Write-Progress -ParentId 1 -Id 3 -Activity "Firewall Install Status: $fw" -Completed + Write-Progress -ParentId 1 -Id 4 -Activity "Messaging Infra Status: $messagingInfra" -Completed + Write-Progress -ParentId 1 -Id 5 -Activity "VXLAN Config Status: $VxlanConfig" -Completed + Write-Progress -Id 1 -Activity "Configuring VXLAN on cluster $($Cluster.Name)." -Completed + $cluster | Get-NsxClusterStatus -Connection $connection } @@ -8617,16 +8621,16 @@ function Install-NsxCluster { param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [PArameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [int]$VxlanPrepTimeout=120, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [PArameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [int]$VxlanPrepTimeout = 120, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -8637,53 +8641,53 @@ function Install-NsxCluster { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlContext = $XMLDoc.CreateElement("nwFabricFeatureConfig") - $xmlDoc.Appendchild($xmlContext) | out-null + $xmlDoc.Appendchild($xmlContext) | Out-Null #configSpec $xmlResourceConfig = $xmlDoc.CreateElement("resourceConfig") - $xmlContext.Appendchild($xmlResourceConfig) | out-null + $xmlContext.Appendchild($xmlResourceConfig) | Out-Null Add-XmlElement -xmlRoot $xmlResourceConfig -xmlElementName "resourceId" -xmlElementText $Cluster.Extensiondata.Moref.Value.ToString() - Write-Progress -id 1 -activity "Preparing cluster $($Cluster.Name)." -status "In Progress..." + Write-Progress -Id 1 -Activity "Preparing cluster $($Cluster.Name)." -Status "In Progress..." # #Do the post $body = $xmlContext.OuterXml $URI = "/api/2.0/nwfabric/configure" - $null = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection + $null = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection #Get Initial Status - $status = $cluster | get-NsxClusterStatus -connection $Connection + $status = $cluster | Get-NsxClusterStatus -Connection $Connection $hostprep = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.nwfabric.hostPrep' -statusxml $status $fw = Get-FeatureStatus -featurestring 'com.vmware.vshield.firewall' -statusxml $status $messagingInfra = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.messagingInfra' -statusxml $status $timer = 0 while ( ($hostprep -ne 'GREEN') -or - ($fw -ne 'GREEN') -or - ($messagingInfra -ne 'GREEN') ) { + ($fw -ne 'GREEN') -or + ($messagingInfra -ne 'GREEN') ) { - start-sleep $VxlanWaitTime + Start-Sleep $VxlanWaitTime $timer += $VxlanWaitTime #Get Status - $status = $cluster | get-NsxClusterStatus -connection $Connection + $status = $cluster | Get-NsxClusterStatus -Connection $Connection $hostprep = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.nwfabric.hostPrep' -statusxml $status $fw = Get-FeatureStatus -featurestring 'com.vmware.vshield.firewall' -statusxml $status $messagingInfra = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.messagingInfra' -statusxml $status #Check Status - if ( $hostprep -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 2 -activity "Vib Install Status: $hostprep" -status $status + if ( $hostprep -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 2 -Activity "Vib Install Status: $hostprep" -Status $status - if ( $fw -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 3 -activity "Firewall Install Status: $fw" -status $status + if ( $fw -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 3 -Activity "Firewall Install Status: $fw" -Status $status - if ( $messagingInfra -eq 'GREEN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 4 -activity "Messaging Infra Status: $messagingInfra" -status $status + if ( $messagingInfra -eq 'GREEN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 4 -Activity "Messaging Infra Status: $messagingInfra" -Status $status if ($Timer -ge $VxlanPrepTimeout) { - $message = "Cluster $($cluster.name) preparation has not completed within the timeout period." + $message = "Cluster $($cluster.name) preparation has not completed within the timeout period." $question = "Continue waiting (y) or quit (n)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8698,11 +8702,11 @@ function Install-NsxCluster { } } - Write-Progress -parentid 1 -id 2 -activity "Vib Install Status: $hostprep" -completed - Write-Progress -parentid 1 -id 3 -activity "Firewall Install Status: $fw" -completed - Write-Progress -parentid 1 -id 4 -activity "Messaging Infra Status: $messagingInfra" -completed - Write-Progress -id 1 -activity "Preparing cluster $($Cluster.Name)." -status "In Progress..." -completed - $cluster | get-NsxClusterStatus -connection $connection + Write-Progress -ParentId 1 -Id 2 -Activity "Vib Install Status: $hostprep" -Completed + Write-Progress -ParentId 1 -Id 3 -Activity "Firewall Install Status: $fw" -Completed + Write-Progress -ParentId 1 -Id 4 -Activity "Messaging Infra Status: $messagingInfra" -Completed + Write-Progress -Id 1 -Activity "Preparing cluster $($Cluster.Name)." -Status "In Progress..." -Completed + $cluster | Get-NsxClusterStatus -Connection $connection } end {} @@ -8723,22 +8727,22 @@ function Remove-NsxCluster { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [int]$VxlanPrepTimeout=120, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [int]$VxlanPrepTimeout = 120, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -8749,16 +8753,16 @@ function Remove-NsxCluster { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlContext = $XMLDoc.CreateElement("nwFabricFeatureConfig") - $xmlDoc.Appendchild($xmlContext) | out-null + $xmlDoc.Appendchild($xmlContext) | Out-Null #configSpec $xmlResourceConfig = $xmlDoc.CreateElement("resourceConfig") - $xmlContext.Appendchild($xmlResourceConfig) | out-null + $xmlContext.Appendchild($xmlResourceConfig) | Out-Null Add-XmlElement -xmlRoot $xmlResourceConfig -xmlElementName "resourceId" -xmlElementText $Cluster.Extensiondata.Moref.Value.ToString() if ( $confirm ) { - $message = "Unpreparation of cluster $($Cluster.Name) will result in unconfiguration of VXLAN, removal of Distributed Firewall and uninstallation of all NSX VIBs." + $message = "Unpreparation of cluster $($Cluster.Name) will result in unconfiguration of VXLAN, removal of Distributed Firewall and uninstallation of all NSX VIBs." $question = "Proceed with un-preparation of cluster $($Cluster.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8774,52 +8778,52 @@ function Remove-NsxCluster { #Even though it *usually* unconfigures VXLAN automatically, ive had several instances where an unprepped #cluster had VXLAN config still present, and prevented future prep attempts from succeeding. #This may not resolve this issue, but hopefully will... - $cluster | Remove-NsxClusterVxlanConfig -confirm:$false -connection $connection| out-null + $cluster | Remove-NsxClusterVxlanConfig -Confirm:$false -Connection $connection | Out-Null #Now we actually do the unprep... ############## - Write-Progress -id 1 -activity "Unpreparing cluster $($Cluster.Name)." -status "In Progress..." + Write-Progress -Id 1 -Activity "Unpreparing cluster $($Cluster.Name)." -Status "In Progress..." # #Do the post $body = $xmlContext.OuterXml $URI = "/api/2.0/nwfabric/configure" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -body $body -connection $connection + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -body $body -connection $connection #Get Initial Status - $status = $cluster | get-NsxClusterStatus -connection $connection + $status = $cluster | Get-NsxClusterStatus -Connection $connection $hostprep = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.nwfabric.hostPrep' -statusxml $status $fw = Get-FeatureStatus -featurestring 'com.vmware.vshield.firewall' -statusxml $status $messagingInfra = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.messagingInfra' -statusxml $status $timer = 0 while ( ($hostprep -ne 'UNKNOWN') -or - ($fw -ne 'UNKNOWN') -or - ($messagingInfra -ne 'UNKNOWN') ) { + ($fw -ne 'UNKNOWN') -or + ($messagingInfra -ne 'UNKNOWN') ) { - start-sleep $VxlanWaitTime + Start-Sleep $VxlanWaitTime $timer += $VxlanWaitTime #Get Status - $status = $cluster | get-NsxClusterStatus -connection $connection + $status = $cluster | Get-NsxClusterStatus -Connection $connection $hostprep = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.nwfabric.hostPrep' -statusxml $status $fw = Get-FeatureStatus -featurestring 'com.vmware.vshield.firewall' -statusxml $status $messagingInfra = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.messagingInfra' -statusxml $status #Check Status - if ( $hostprep -eq 'UNKNOWN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 2 -activity "Vib Install Status: $hostprep" -status $status + if ( $hostprep -eq 'UNKNOWN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 2 -Activity "Vib Install Status: $hostprep" -Status $status - if ( $fw -eq 'UNKNOWN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 3 -activity "Firewall Install Status: $fw" -status $status + if ( $fw -eq 'UNKNOWN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 3 -Activity "Firewall Install Status: $fw" -Status $status - if ( $messagingInfra -eq 'UNKNOWN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 4 -activity "Messaging Infra Status: $messagingInfra" -status $status + if ( $messagingInfra -eq 'UNKNOWN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 4 -Activity "Messaging Infra Status: $messagingInfra" -Status $status if ($Timer -ge $VxlanPrepTimeout) { #Need to do some detection of hosts needing reboot here and prompt to do it automatically... - $message = "Cluster $($cluster.name) unpreparation has not completed within the timeout period." + $message = "Cluster $($cluster.name) unpreparation has not completed within the timeout period." $question = "Continue waiting (y) or quit (n)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8830,14 +8834,15 @@ function Remove-NsxCluster { if ( $decision -eq 1 ) { Throw "$($cluster.name) cluster unpreparation failed or timed out." } - $Timer = 0 } + $Timer = 0 + } } - Write-Progress -parentid 1 -id 2 -activity "Vib Install Status: $hostprep" -completed - Write-Progress -parentid 1 -id 3 -activity "Firewall Install Status: $fw" -completed - Write-Progress -parentid 1 -id 4 -activity "Messaging Infra Status: $messagingInfra" -completed - Write-Progress -id 1 -activity "Unpreparing cluster $($Cluster.Name)." -status "In Progress..." -completed - $cluster | get-NsxClusterStatus -connection $connection + Write-Progress -ParentId 1 -Id 2 -Activity "Vib Install Status: $hostprep" -Completed + Write-Progress -ParentId 1 -Id 3 -Activity "Firewall Install Status: $fw" -Completed + Write-Progress -ParentId 1 -Id 4 -Activity "Messaging Infra Status: $messagingInfra" -Completed + Write-Progress -Id 1 -Activity "Unpreparing cluster $($Cluster.Name)." -Status "In Progress..." -Completed + $cluster | Get-NsxClusterStatus -Connection $connection } } @@ -8860,22 +8865,22 @@ function Remove-NsxClusterVxlanConfig { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [int]$VxlanPrepTimeout=120, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [int]$VxlanPrepTimeout = 120, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -8886,19 +8891,19 @@ function Remove-NsxClusterVxlanConfig { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlContext = $XMLDoc.CreateElement("nwFabricFeatureConfig") - $xmlDoc.Appendchild($xmlContext) | out-null + $xmlDoc.Appendchild($xmlContext) | Out-Null #ResourceID (must specific explicitly VXLAN) Add-XmlElement -xmlRoot $xmlContext -xmlElementName "featureId" -xmlElementText "com.vmware.vshield.vsm.vxlan" #configSpec $xmlResourceConfig = $xmlDoc.CreateElement("resourceConfig") - $xmlContext.Appendchild($xmlResourceConfig) | out-null + $xmlContext.Appendchild($xmlResourceConfig) | Out-Null Add-XmlElement -xmlRoot $xmlResourceConfig -xmlElementName "resourceId" -xmlElementText $Cluster.Extensiondata.Moref.Value.ToString() if ( $confirm ) { - $message = "Unconfiguration of VXLAN for cluster $($Cluster.Name) will result in loss of communication for any VMs connected to logical switches running in this cluster." + $message = "Unconfiguration of VXLAN for cluster $($Cluster.Name) will result in loss of communication for any VMs connected to logical switches running in this cluster." $question = "Proceed with unconfiguration of VXLAN for cluster $($Cluster.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8910,33 +8915,33 @@ function Remove-NsxClusterVxlanConfig { else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -id 1 -activity "Unconfiguring VXLAN on $($Cluster.Name)." -status "In Progress..." + Write-Progress -Id 1 -Activity "Unconfiguring VXLAN on $($Cluster.Name)." -Status "In Progress..." # #Do the post $body = $xmlContext.OuterXml $URI = "/api/2.0/nwfabric/configure" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -body $body -connection $connection + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -body $body -connection $connection #Get Initial Status - $status = $cluster | get-NsxClusterStatus -connection $connection + $status = $cluster | Get-NsxClusterStatus -Connection $connection $VxlanConfig = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.vxlan' -statusxml $status $timer = 0 while ( $VxlanConfig -ne 'UNKNOWN' ) { - start-sleep $VxlanWaitTime + Start-Sleep $VxlanWaitTime $timer += $VxlanWaitTime #Get Status - $status = $cluster | get-NsxClusterStatus -connection $connection + $status = $cluster | Get-NsxClusterStatus -Connection $connection $VxlanConfig = Get-FeatureStatus -featurestring 'com.vmware.vshield.vsm.vxlan' -statusxml $status #Check Status - if ( $VxlanConfig -eq 'UNKNOWN' ) { $status = "Complete"} else { $status = "Waiting" } - Write-Progress -parentid 1 -id 5 -activity "VXLAN Config Status: $VxlanConfig" -status $status + if ( $VxlanConfig -eq 'UNKNOWN' ) { $status = "Complete" } else { $status = "Waiting" } + Write-Progress -ParentId 1 -Id 5 -Activity "VXLAN Config Status: $VxlanConfig" -Status $status if ($Timer -ge $VxlanPrepTimeout) { - $message = "Cluster $($cluster.name) VXLAN unconfiguration has not completed within the timeout period." + $message = "Cluster $($cluster.name) VXLAN unconfiguration has not completed within the timeout period." $question = "Continue waiting (y) or quit (n)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -8951,9 +8956,9 @@ function Remove-NsxClusterVxlanConfig { } } - Write-Progress -parentid 1 -id 5 -activity "VXLAN Config Status: $VxlanConfig" -completed - Write-Progress -id 1 -activity "Unconfiguring VXLAN on $($Cluster.Name)." -status "In Progress..." -completed - $cluster | get-NsxClusterStatus -connection $connection | where-object { $_.featureId -eq "com.vmware.vshield.vsm.vxlan" } + Write-Progress -ParentId 1 -Id 5 -Activity "VXLAN Config Status: $VxlanConfig" -Completed + Write-Progress -Id 1 -Activity "Unconfiguring VXLAN on $($Cluster.Name)." -Status "In Progress..." -Completed + $cluster | Get-NsxClusterStatus -Connection $connection | Where-Object { $_.featureId -eq "com.vmware.vshield.vsm.vxlan" } } } @@ -8989,26 +8994,26 @@ function New-NsxSegmentIdRange { #> - param ( + param ( - [Parameter (Mandatory=$true, Position=1)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$Description, - [Parameter (Mandatory=$true)] - [ValidateRange(5000,16777215)] - [int]$Begin, - [Parameter (Mandatory=$true)] - [ValidateRange(5000,16777215)] - [int]$End, - [Parameter (Mandatory=$false)] - [switch]$Universal=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Description, + [Parameter (Mandatory = $true)] + [ValidateRange(5000, 16777215)] + [int]$Begin, + [Parameter (Mandatory = $true)] + [ValidateRange(5000, 16777215)] + [int]$End, + [Parameter (Mandatory = $false)] + [switch]$Universal = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -9017,7 +9022,7 @@ function New-NsxSegmentIdRange { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRange = $XMLDoc.CreateElement("segmentRange") - $xmlDoc.Appendchild($xmlRange) | out-null + $xmlDoc.Appendchild($xmlRange) | Out-Null #Mandatory and default params Add-XmlElement -xmlRoot $xmlRange -xmlElementName "name" -xmlElementText $Name.ToString() @@ -9032,11 +9037,11 @@ function New-NsxSegmentIdRange { # #Do the post $body = $xmlRange.OuterXml $URI = "/api/2.0/vdn/config/segments?isUniversal=$($Universal.ToString().ToLower())" - Write-Progress -activity "Creating Segment Id Range" - $response = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Creating Segment Id Range" -completed + Write-Progress -Activity "Creating Segment Id Range" + $response = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating Segment Id Range" -Completed - Get-NsxSegmentIdRange -objectId $response.segmentRange.id -connection $connection + Get-NsxSegmentIdRange -ObjectId $response.segmentRange.id -Connection $connection } @@ -9058,27 +9063,27 @@ function Get-NsxSegmentIdRange { #> - [CmdletBinding(DefaultParameterSetName="Default")] + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$false,Position=1,ParameterSetName = "Name")] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] - #Name of the segment ID range to return - [string]$Name, - [Parameter (Mandatory=$false, ParameterSetName = "ObjectId")] - #ObjectId of the segment ID range to return - [string]$ObjectId, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] - #Return only Universal objects - [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] - #Return only Locally scoped objects - [switch]$LocalOnly, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Name")] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] + #Name of the segment ID range to return + [string]$Name, + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + #ObjectId of the segment ID range to return + [string]$ObjectId, + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] + #Return only Universal objects + [switch]$UniversalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] + #Return only Locally scoped objects + [switch]$LocalOnly, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -9087,18 +9092,18 @@ function Get-NsxSegmentIdRange { if ( $PsBoundParameters.ContainsKey('ObjectId')) { $URI = "/api/2.0/vdn/config/segments/$ObjectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $response.segmentRange } else { $URI = "/api/2.0/vdn/config/segments" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if(([bool](($response.segmentRanges).PSobject.Properties.name -match "segmentRange"))){ + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if (([bool](($response.segmentRanges).PSobject.Properties.name -match "segmentRange"))) { switch ( $PSCmdlet.ParameterSetName ) { - "Name" { $response.segmentRanges.segmentRange | where-object { $_.name -eq $Name } } - "UniversalOnly" { $response.segmentRanges.segmentRange | where-object { $_.isUniversal -eq "true" } } - "LocalOnly" { $response.segmentRanges.segmentRange | where-object { $_.isUniversal -eq "false" } } + "Name" { $response.segmentRanges.segmentRange | Where-Object { $_.name -eq $Name } } + "UniversalOnly" { $response.segmentRanges.segmentRange | Where-Object { $_.isUniversal -eq "true" } } + "LocalOnly" { $response.segmentRanges.segmentRange | Where-Object { $_.isUniversal -eq "false" } } Default { $response.segmentRanges.segmentRange } } } @@ -9121,19 +9126,19 @@ function Remove-NsxSegmentIdRange { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateSegmentIdRange $_ })] - [System.Xml.XmlElement]$SegmentIdRange, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateSegmentIdRange $_ })] + [System.Xml.XmlElement]$SegmentIdRange, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -9144,7 +9149,7 @@ function Remove-NsxSegmentIdRange { process { if ( $confirm ) { - $message = "Segment Id Range removal is permanent." + $message = "Segment Id Range removal is permanent." $question = "Proceed with removal of Segment Id Range $($SegmentIdRange.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -9156,9 +9161,9 @@ function Remove-NsxSegmentIdRange { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/2.0/vdn/config/segments/$($SegmentIdRange.Id)" - Write-Progress -activity "Remove Segment Id Range $($SegmentIdRange.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Remove Segment Id Range $($SegmentIdRange.Name)" -completed + Write-Progress -Activity "Remove Segment Id Range $($SegmentIdRange.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Segment Id Range $($SegmentIdRange.Name)" -Completed } } @@ -9195,29 +9200,29 @@ function Get-NsxTransportZone { Get all Universal NSX Transport Zones configured #> - [CmdLetBinding(DefaultParameterSetName="Default")] + [CmdLetBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,Position=1,ParameterSetName = "Name")] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] - #TransportZoneName - [string]$name, - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - #NSX ObjectId - [ValidateNotNullOrEmpty()] - [string]$objectId, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] - #Return only Universal objects - [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] - #Return only Locally scoped objects - [switch]$LocalOnly, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "Name")] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] + #TransportZoneName + [string]$name, + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + #NSX ObjectId + [ValidateNotNullOrEmpty()] + [string]$objectId, + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] + #Return only Universal objects + [switch]$UniversalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] + #Return only Locally scoped objects + [switch]$LocalOnly, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -9225,25 +9230,25 @@ function Get-NsxTransportZone { #Just getting a single Transport Zone by ID $URI = "/api/2.0/vdn/scopes/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $response.vdnscope } else { #Getting all TZ and optionally filtering on name $URI = "/api/2.0/vdn/scopes" - [system.xml.xmldocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [system.xml.xmldocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query "child::vdnScopes/vdnScope")) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::vdnScopes/vdnScope")) { $return = $response.vdnscopes.vdnscope if ( $psboundParameters.ContainsKey("Name") ) { - $return = $return | where-object { $_.name -eq $name } + $return = $return | Where-Object { $_.name -eq $name } } if ( $UniversalOnly ) { - $return | where-object { $_.isUniversal -eq 'True' } + $return | Where-Object { $_.isUniversal -eq 'True' } } elseif ( $LocalOnly ) { - $return | where-object { $_.isUniversal -eq 'False' } + $return | Where-Object { $_.isUniversal -eq 'False' } } else { $return @@ -9272,25 +9277,25 @@ function New-NsxTransportZone { #> - param ( + param ( - [Parameter (Mandatory=$true, Position=1)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$Description, - [Parameter (Mandatory=$true)] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop[]]$Cluster, - [Parameter (Mandatory=$true)] - [ValidateSet("UNICAST_MODE","MULTICAST_MODE","HYBRID_MODE",IgnoreCase=$false)] - [string]$ControlPlaneMode, - [Parameter (Mandatory=$false)] - [switch]$Universal=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Description, + [Parameter (Mandatory = $true)] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop[]]$Cluster, + [Parameter (Mandatory = $true)] + [ValidateSet("UNICAST_MODE", "MULTICAST_MODE", "HYBRID_MODE", IgnoreCase = $false)] + [string]$ControlPlaneMode, + [Parameter (Mandatory = $false)] + [switch]$Universal = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -9299,7 +9304,7 @@ function New-NsxTransportZone { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlScope = $XMLDoc.CreateElement("vdnScope") - $xmlDoc.Appendchild($xmlScope) | out-null + $xmlDoc.Appendchild($xmlScope) | Out-Null #Mandatory and default params Add-XmlElement -xmlRoot $xmlScope -xmlElementName "name" -xmlElementText $Name.ToString() @@ -9307,12 +9312,12 @@ function New-NsxTransportZone { #Dont ask me, I just work here :| [System.XML.XMLElement]$xmlClusters = $XMLDoc.CreateElement("clusters") - $xmlScope.Appendchild($xmlClusters) | out-null + $xmlScope.Appendchild($xmlClusters) | Out-Null foreach ( $instance in $cluster ) { [System.XML.XMLElement]$xmlCluster1 = $XMLDoc.CreateElement("cluster") - $xmlClusters.Appendchild($xmlCluster1) | out-null + $xmlClusters.Appendchild($xmlCluster1) | Out-Null [System.XML.XMLElement]$xmlCluster2 = $XMLDoc.CreateElement("cluster") - $xmlCluster1.Appendchild($xmlCluster2) | out-null + $xmlCluster1.Appendchild($xmlCluster2) | Out-Null Add-XmlElement -xmlRoot $xmlCluster2 -xmlElementName "objectId" -xmlElementText $Instance.ExtensionData.Moref.Value } @@ -9324,11 +9329,11 @@ function New-NsxTransportZone { # #Do the post $body = $xmlScope.OuterXml $URI = "/api/2.0/vdn/scopes?isUniversal=$($Universal.ToString().ToLower())" - Write-Progress -activity "Creating Transport Zone." - $response = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Creating Transport Zone." -completed + Write-Progress -Activity "Creating Transport Zone." + $response = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating Transport Zone." -Completed - Get-NsxTransportZone -objectId $response -connection $connection + Get-NsxTransportZone -objectId $response -Connection $connection } @@ -9365,34 +9370,34 @@ function Wait-NsxTransportZoneJob { #> param ( - [Parameter (Mandatory=$true)] - #Job Id string as returned from the api - [string]$JobId, - [Parameter (Mandatory=$false)] - #Seconds to wait before declaring a timeout. Timeout defaults to 30 seconds. - [int]$WaitTimeout=30, - [Parameter (Mandatory=$false)] - #Do we prompt user an allow them to reset the timeout timer, or throw on timeout - [switch]$FailOnTimeout=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true)] + #Job Id string as returned from the api + [string]$JobId, + [Parameter (Mandatory = $false)] + #Seconds to wait before declaring a timeout. Timeout defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $false)] + #Do we prompt user an allow them to reset the timeout timer, or throw on timeout + [switch]$FailOnTimeout = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $WaitJobArgs = @{ - "jobid" = $jobid - "JobStatusUri" = "/api/2.0/services/taskservice/job" + "jobid" = $jobid + "JobStatusUri" = "/api/2.0/services/taskservice/job" "CompleteCriteria" = { $job.jobInstances.jobInstance.status -eq "COMPLETED" } - "FailCriteria" = { + "FailCriteria" = { $job.jobInstances.jobInstance.status -eq "FAILED" } "StatusExpression" = { $execTask = @() $StatusMessage = "" - $execTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | where-object { $_.taskStatus -eq "EXECUTING" }) + $execTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | Where-Object { $_.taskStatus -eq "EXECUTING" }) if ( $exectask.count -eq 1) { $StatusMessage = "$($execTask.name) - $($execTask.taskStatus)" } @@ -9401,10 +9406,10 @@ function Wait-NsxTransportZoneJob { } $StatusMessage } - "ErrorExpression" = { + "ErrorExpression" = { $failTask = @() $failMessage = "" - $failTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | where-object { $_.taskStatus -eq "FAILED" }) + $failTask = @($job.jobinstances.jobInstance.taskInstances.taskInstance | Where-Object { $_.taskStatus -eq "FAILED" }) if ( $failTask.count -eq 1) { $failMessage = "Failed Task : $($failTask.name) - $($failTask.statusMessage)" } @@ -9413,9 +9418,9 @@ function Wait-NsxTransportZoneJob { } $failMessage } - "WaitTimeout" = $WaitTimeout - "FailOnTimeout" = $FailOnTimeout - "Connection" = $Connection + "WaitTimeout" = $WaitTimeout + "FailOnTimeout" = $FailOnTimeout + "Connection" = $Connection } Wait-NsxJob @WaitJobArgs @@ -9454,28 +9459,28 @@ function Add-NsxTransportZoneMember { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #PowerNSX Transport Zone object to be updated - [ValidateScript({ ValidateTransportZone $_ })] - [System.Xml.XmlElement]$TransportZone, - [Parameter (Mandatory=$true)] - #Cluster to be added to the Transport Zone - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop[]]$Cluster, - [Parameter ( Mandatory=$False)] - #Block until transport zone update job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) - #Useful if automating the tz modification so you dont have to write looping code to check status of the tz before continuing. - #NOTE: Not waiting means we do NOT return an updated tz object! - [switch]$Wait=$True, - [Parameter ( Mandatory=$False)] - #Timeout waiting for tz update job to complete before user is prompted to continue or cancel. Defaults to 30 seconds. - [int]$WaitTimeout = 30, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #PowerNSX Transport Zone object to be updated + [ValidateScript( { ValidateTransportZone $_ })] + [System.Xml.XmlElement]$TransportZone, + [Parameter (Mandatory = $true)] + #Cluster to be added to the Transport Zone + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop[]]$Cluster, + [Parameter ( Mandatory = $False)] + #Block until transport zone update job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) + #Useful if automating the tz modification so you dont have to write looping code to check status of the tz before continuing. + #NOTE: Not waiting means we do NOT return an updated tz object! + [switch]$Wait = $True, + [Parameter ( Mandatory = $False)] + #Timeout waiting for tz update job to complete before user is prompted to continue or cancel. Defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -9484,25 +9489,25 @@ function Add-NsxTransportZoneMember { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlScope = $XMLDoc.CreateElement("vdnScope") - $xmlDoc.Appendchild($xmlScope) | out-null + $xmlDoc.Appendchild($xmlScope) | Out-Null Add-XmlElement -xmlRoot $xmlScope -xmlElementName "objectId" -xmlElementText $TransportZone.objectId [System.XML.XMLElement]$xmlClusters = $XMLDoc.CreateElement("clusters") - $xmlScope.Appendchild($xmlClusters) | out-null + $xmlScope.Appendchild($xmlClusters) | Out-Null foreach ( $instance in $cluster ) { [System.XML.XMLElement]$xmlCluster1 = $XMLDoc.CreateElement("cluster") - $xmlClusters.Appendchild($xmlCluster1) | out-null + $xmlClusters.Appendchild($xmlCluster1) | Out-Null [System.XML.XMLElement]$xmlCluster2 = $XMLDoc.CreateElement("cluster") - $xmlCluster1.Appendchild($xmlCluster2) | out-null + $xmlCluster1.Appendchild($xmlCluster2) | Out-Null Add-XmlElement -xmlRoot $xmlCluster2 -xmlElementName "objectId" -xmlElementText $Instance.ExtensionData.Moref.Value } #Do the post $body = $xmlScope.OuterXml $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)?action=expand" - Write-Progress -activity "Updating Transport Zone." + Write-Progress -Activity "Updating Transport Zone." try { - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection } catch { throw "Transport Zone update failed. $_" @@ -9515,19 +9520,19 @@ function Add-NsxTransportZoneMember { if ( $Wait ) { $jobid = $response.content - write-debug "$($MyInvocation.MyCommand.Name) : TZ update job $jobid returned in post response" + Write-Debug "$($MyInvocation.MyCommand.Name) : TZ update job $jobid returned in post response" #First we wait for NSX job framework to give us the needful try { Wait-NsxTransportZoneJob -Jobid $JobID -Connection $Connection -WaitTimeout $WaitTimeout - Get-NsxTransportZone -connection $connection -objectid $TransportZone.objectId + Get-NsxTransportZone -Connection $connection -objectId $TransportZone.objectId } catch { throw "Cluster addition to Transport Zone $($TransportZone.Name) failed. $_" } } - Write-progress -activity "Updating Transport Zone." -completed + Write-Progress -Activity "Updating Transport Zone." -Completed } end {} @@ -9557,28 +9562,28 @@ function Remove-NsxTransportZoneMember { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #PowerNSX Transport Zone object to be updated - [ValidateScript({ ValidateTransportZone $_ })] - [System.Xml.XmlElement]$TransportZone, - [Parameter (Mandatory=$true)] - #Cluster to be added to the Transport Zone - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop[]]$Cluster, - [Parameter ( Mandatory=$False)] - #Block until transport zone update job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) - #Useful if automating the tz modification so you dont have to write looping code to check status of the tz before continuing. - #NOTE: Not waiting means we do NOT return an updated tz object! - [switch]$Wait=$True, - [Parameter ( Mandatory=$False)] - #Timeout waiting for tz update job to complete before user is prompted to continue or cancel. Defaults to 30 seconds. - [int]$WaitTimeout = 30, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #PowerNSX Transport Zone object to be updated + [ValidateScript( { ValidateTransportZone $_ })] + [System.Xml.XmlElement]$TransportZone, + [Parameter (Mandatory = $true)] + #Cluster to be added to the Transport Zone + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop[]]$Cluster, + [Parameter ( Mandatory = $False)] + #Block until transport zone update job is 'COMPLETED' (Will timeout with prompt after -WaitTimeout seconds) + #Useful if automating the tz modification so you dont have to write looping code to check status of the tz before continuing. + #NOTE: Not waiting means we do NOT return an updated tz object! + [switch]$Wait = $True, + [Parameter ( Mandatory = $False)] + #Timeout waiting for tz update job to complete before user is prompted to continue or cancel. Defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) #Todo: Improve to accept cluster name as arg instead of PowerCLI object. @@ -9588,25 +9593,25 @@ function Remove-NsxTransportZoneMember { #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlScope = $XMLDoc.CreateElement("vdnScope") - $xmlDoc.Appendchild($xmlScope) | out-null + $xmlDoc.Appendchild($xmlScope) | Out-Null Add-XmlElement -xmlRoot $xmlScope -xmlElementName "objectId" -xmlElementText $TransportZone.objectId [System.XML.XMLElement]$xmlClusters = $XMLDoc.CreateElement("clusters") - $xmlScope.Appendchild($xmlClusters) | out-null + $xmlScope.Appendchild($xmlClusters) | Out-Null foreach ( $instance in $cluster ) { [System.XML.XMLElement]$xmlCluster1 = $XMLDoc.CreateElement("cluster") - $xmlClusters.Appendchild($xmlCluster1) | out-null + $xmlClusters.Appendchild($xmlCluster1) | Out-Null [System.XML.XMLElement]$xmlCluster2 = $XMLDoc.CreateElement("cluster") - $xmlCluster1.Appendchild($xmlCluster2) | out-null + $xmlCluster1.Appendchild($xmlCluster2) | Out-Null Add-XmlElement -xmlRoot $xmlCluster2 -xmlElementName "objectId" -xmlElementText $Instance.ExtensionData.Moref.Value } #Do the post $body = $xmlScope.OuterXml $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)?action=shrink" - Write-Progress -activity "Updating Transport Zone." + Write-Progress -Activity "Updating Transport Zone." try { - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection } catch { throw "Transport Zone update failed. $_" @@ -9619,18 +9624,18 @@ function Remove-NsxTransportZoneMember { if ( $Wait ) { $jobid = $response.content - write-debug "$($MyInvocation.MyCommand.Name) : TZ update job $jobid returned in post response" + Write-Debug "$($MyInvocation.MyCommand.Name) : TZ update job $jobid returned in post response" #First we wait for NSX job framework to give us the needful try { Wait-NsxTransportZoneJob -Jobid $JobID -Connection $Connection -WaitTimeout $WaitTimeout - Get-NsxTransportZone -connection $connection -objectid $TransportZone.objectId + Get-NsxTransportZone -Connection $connection -objectId $TransportZone.objectId } catch { throw "Cluster removal from Transport Zone $($TransportZone.Name) failed. $_" } } - Write-progress -activity "Updating Transport Zone." -completed + Write-Progress -Activity "Updating Transport Zone." -Completed } end {} @@ -9656,19 +9661,19 @@ function Remove-NsxTransportZone { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateTransportZone $_ })] - [System.Xml.XmlElement]$TransportZone, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateTransportZone $_ })] + [System.Xml.XmlElement]$TransportZone, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -9679,7 +9684,7 @@ function Remove-NsxTransportZone { process { if ( $confirm ) { - $message = "Transport Zone removal is permanent." + $message = "Transport Zone removal is permanent." $question = "Proceed with removal of Transport Zone $($TransportZone.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -9691,9 +9696,9 @@ function Remove-NsxTransportZone { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)" - Write-Progress -activity "Remove Transport Zone $($TransportZone.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Remove Transport Zone $($TransportZone.Name)" -completed + Write-Progress -Activity "Remove Transport Zone $($TransportZone.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Transport Zone $($TransportZone.Name)" -Completed } } @@ -9721,18 +9726,18 @@ function Add-NsxLicense { param ( - [Parameter (Mandatory=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [string]$LicenseKey, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [string]$LicenseKey, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - If ( -not ( get-member -InputObject $Connection -MemberType Properties -Name VIConnection ) -or (-not ( $Connection.ViConnection.IsConnected)) ) { + If ( -not ( Get-Member -InputObject $Connection -MemberType Properties -Name VIConnection ) -or (-not ( $Connection.ViConnection.IsConnected)) ) { throw "Specified connection has no associated vCenter server, or server is not connected." } } @@ -9740,10 +9745,10 @@ function Add-NsxLicense { process { if ( [version]$Connection.Version -gt [version]"6.2.3") { try { - $ServiceInstance = Get-View ServiceInstance -server $Connection.VIConnection + $ServiceInstance = Get-View ServiceInstance -Server $Connection.VIConnection $LicenseManager = Get-View $ServiceInstance.Content.licenseManager -Server $connection.VIConnection $LicenseAssignmentManager = Get-View $LicenseManager.licenseAssignmentManager -Server $connection.VIConnection - $LicenseAssignmentManager.UpdateAssignedLicense("nsx-netsec",$LicenseKey,$NULL) + $LicenseAssignmentManager.UpdateAssignedLicense("nsx-netsec", $LicenseKey, $NULL) } catch { throw "Unable to configure NSX license. Check the license is valid and try again. $_" @@ -9774,14 +9779,14 @@ function Get-NsxLicense { param ( - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - If ( -not ( get-member -InputObject $Connection -MemberType Properties -Name VIConnection ) -or (-not ( $Connection.ViConnection.IsConnected)) ) { + If ( -not ( Get-Member -InputObject $Connection -MemberType Properties -Name VIConnection ) -or (-not ( $Connection.ViConnection.IsConnected)) ) { throw "Specified connection has no associated vCenter server, or server is not connected." } } @@ -9789,9 +9794,9 @@ function Get-NsxLicense { process { if ( [version]$Connection.Version -gt [version]"6.2.3") { try { - $ServiceInstance = Get-View ServiceInstance -server $Connection.VIConnection + $ServiceInstance = Get-View ServiceInstance -Server $Connection.VIConnection $LicenseManager = Get-View $ServiceInstance.Content.licenseManager -Server $connection.VIConnection - $LicenseManager.Licenses | where-object { $_.EditionKey -match 'nsx' } + $LicenseManager.Licenses | Where-Object { $_.EditionKey -match 'nsx' } } catch { throw "Unable to retrieve NSX license. $_" @@ -9827,14 +9832,14 @@ function Invoke-NsxClusterResolveAll { #> param ( - [Parameter ( Mandatory=$true,ValueFromPipeline=$true)] - #Cluster to trigger resolve on. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter ( Mandatory = $true, ValueFromPipeline = $true)] + #Cluster to trigger resolve on. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -9842,9 +9847,9 @@ function Invoke-NsxClusterResolveAll { process { #Get the agency Id for the cluster - $response = Invoke-NsxWebRequest -method Get -Uri "/api/2.0/vdn/config/cluster/agency/$($cluster.extensiondata.moref.value)" + $response = Invoke-NsxWebRequest -method Get -URI "/api/2.0/vdn/config/cluster/agency/$($cluster.extensiondata.moref.value)" [xml]$Content = $response.content - $null = Invoke-NsxWebRequest -method Post -Uri "/api/2.0/vdn/config/agency/$($Content.AgencyInfo.Agencyid)?action=resolveAll" + $null = Invoke-NsxWebRequest -method Post -URI "/api/2.0/vdn/config/agency/$($Content.AgencyInfo.Agencyid)?action=resolveAll" } end {} @@ -9869,20 +9874,20 @@ function Get-NsxUserRole { #> param ( - [Parameter(Mandatory=$true, Position=1)] - #Username to query role details. - [ValidateNotNullorEmpty()] - [string]$UserName, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter(Mandatory = $true, Position = 1)] + #Username to query role details. + [ValidateNotNullorEmpty()] + [string]$UserName, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { try { - $result = Invoke-NsxRestMethod -method get -uri "/api/2.0/services/usermgmt/role/$UserName" -connection $connection + $result = Invoke-NsxRestMethod -method get -URI "/api/2.0/services/usermgmt/role/$UserName" -connection $connection } catch { throw "Unable to retrieve role details from NSX. $_" @@ -9933,24 +9938,24 @@ function Get-NsxLogicalSwitch { #> - [CmdletBinding(DefaultParameterSetName="vdnscope")] + [CmdletBinding(DefaultParameterSetName = "vdnscope")] param ( - [Parameter (Mandatory=$false,ValueFromPipeline=$true,ParameterSetName="vdnscope")] - [ValidateScript({ ValidateTransportZone $_ })] - [alias("vdnScope")] - [System.Xml.XmlElement]$TransportZone, - [Parameter (Mandatory=$false,Position=1)] - [string]$Name, - [Parameter (Mandatory=$true,ParameterSetName="virtualWire")] - [ValidateNotNullOrEmpty()] - [alias("virtualWireId")] - [string]$ObjectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, ValueFromPipeline = $true, ParameterSetName = "vdnscope")] + [ValidateScript( { ValidateTransportZone $_ })] + [alias("vdnScope")] + [System.Xml.XmlElement]$TransportZone, + [Parameter (Mandatory = $false, Position = 1)] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "virtualWire")] + [ValidateNotNullOrEmpty()] + [alias("virtualWireId")] + [string]$ObjectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -9964,7 +9969,7 @@ function Get-NsxLogicalSwitch { #Just getting a single named Logical Switch $URI = "/api/2.0/vdn/virtualwires/$ObjectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $response.virtualWire } @@ -9973,41 +9978,41 @@ function Get-NsxLogicalSwitch { #Getting all LS in a given VDNScope $lspagesize = 10 if ( $PSBoundParameters.ContainsKey('TransportZone')) { - $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)/virtualwires?pagesize=$lspagesize&startindex=00" + $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)/virtualwires?pagesize=$lspagesize&startindex=00" } else { $URI = "/api/2.0/vdn/virtualwires?pagesize=$lspagesize&startindex=00" } - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $logicalSwitches = @() #LS XML is returned as paged data, means we have to handle it. #May refactor this later, depending on where else I find this in the NSX API (its not really documented in the API guide) - $itemIndex = 0 + $itemIndex = 0 $startingIndex = 0 $pagingInfo = $response.virtualWires.dataPage.pagingInfo if ( [int]$paginginfo.totalCount -ne 0 ) { - write-debug "$($MyInvocation.MyCommand.Name) : Logical Switches count non zero" + Write-Debug "$($MyInvocation.MyCommand.Name) : Logical Switches count non zero" do { - write-debug "$($MyInvocation.MyCommand.Name) : In paging loop. PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : In paging loop. PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" while (($itemindex -lt ([int]$paginginfo.pagesize + $startingIndex)) -and ($itemIndex -lt [int]$paginginfo.totalCount )) { - write-debug "$($MyInvocation.MyCommand.Name) : In Item Processing Loop: ItemIndex: $itemIndex" - write-debug "$($MyInvocation.MyCommand.Name) : $(@($response.virtualwires.datapage.virtualwire)[($itemIndex - $startingIndex)].objectId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : In Item Processing Loop: ItemIndex: $itemIndex" + Write-Debug "$($MyInvocation.MyCommand.Name) : $(@($response.virtualwires.datapage.virtualwire)[($itemIndex - $startingIndex)].objectId)" #Need to wrap the virtualwire prop of the datapage in case we get exactly 1 item - #which powershell annoyingly unwraps to a single xml element rather than an array... $logicalSwitches += @($response.virtualwires.datapage.virtualwire)[($itemIndex - $startingIndex)] $itemIndex += 1 } - write-debug "$($MyInvocation.MyCommand.Name) : Out of item processing - PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Out of item processing - PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" if ( [int]$paginginfo.totalcount -gt $itemIndex) { - write-debug "$($MyInvocation.MyCommand.Name) : PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" $startingIndex += $lspagesize if ( $PSBoundParameters.ContainsKey('vndScope')) { $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)/virtualwires?pagesize=$lspagesize&startindex=$startingIndex" @@ -10015,18 +10020,19 @@ function Get-NsxLogicalSwitch { else { $URI = "/api/2.0/vdn/virtualwires?pagesize=$lspagesize&startindex=$startingIndex" } - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $pagingInfo = $response.virtualWires.dataPage.pagingInfo } } until ( [int]$paginginfo.totalcount -le $itemIndex ) - write-debug "$($MyInvocation.MyCommand.Name) : Completed page processing: ItemIndex: $itemIndex" + Write-Debug "$($MyInvocation.MyCommand.Name) : Completed page processing: ItemIndex: $itemIndex" } if ( $name ) { - $logicalSwitches | where-object { $_.name -eq $name } - } else { + $logicalSwitches | Where-Object { $_.name -eq $name } + } + else { $logicalSwitches } } @@ -10036,7 +10042,7 @@ function Get-NsxLogicalSwitch { } } -function New-NsxLogicalSwitch { +function New-NsxLogicalSwitch { <# .SYNOPSIS @@ -10071,25 +10077,25 @@ function New-NsxLogicalSwitch { [CmdletBinding()] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateNotNullOrEmpty()] - [alias("vdnScope")] - [System.XML.XMLElement]$TransportZone, - [Parameter (Mandatory=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$Description = "", - [Parameter (Mandatory=$false)] - [string]$TenantId = "", - [Parameter (Mandatory=$false)] - [ValidateSet("UNICAST_MODE","MULTICAST_MODE","HYBRID_MODE",IgnoreCase=$false)] - [string]$ControlPlaneMode, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateNotNullOrEmpty()] + [alias("vdnScope")] + [System.XML.XMLElement]$TransportZone, + [Parameter (Mandatory = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Description = "", + [Parameter (Mandatory = $false)] + [string]$TenantId = "", + [Parameter (Mandatory = $false)] + [ValidateSet("UNICAST_MODE", "MULTICAST_MODE", "HYBRID_MODE", IgnoreCase = $false)] + [string]$ControlPlaneMode, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -10098,7 +10104,7 @@ function New-NsxLogicalSwitch { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("virtualWireCreateSpec") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null #Create an Element and append it to the root Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name @@ -10109,10 +10115,10 @@ function New-NsxLogicalSwitch { #Do the post $body = $xmlroot.OuterXml $URI = "/api/2.0/vdn/scopes/$($TransportZone.objectId)/virtualwires" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection #response only contains the vwire id, we have to query for it to get output consisten with get-nsxlogicalswitch - Get-NsxLogicalSwitch -virtualWireId $response.content -connection $connection + Get-NsxLogicalSwitch -virtualWireId $response.content -Connection $connection } end {} } @@ -10148,19 +10154,19 @@ function Remove-NsxLogicalSwitch { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$virtualWire, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$virtualWire, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -10171,7 +10177,7 @@ function Remove-NsxLogicalSwitch { process { if ( $confirm ) { - $message = "Logical Switch removal is permanent." + $message = "Logical Switch removal is permanent." $question = "Proceed with removal of Logical Switch $($virtualWire.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -10183,9 +10189,9 @@ function Remove-NsxLogicalSwitch { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/2.0/vdn/virtualwires/$($virtualWire.ObjectId)" - Write-Progress -activity "Remove Logical Switch $($virtualWire.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Logical Switch $($virtualWire.Name)" -completed + Write-Progress -Activity "Remove Logical Switch $($virtualWire.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Logical Switch $($virtualWire.Name)" -Completed } } @@ -10219,22 +10225,22 @@ function Set-NsxLogicalSwitch { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$virtualWire, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$description, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$virtualWire, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$description, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -10258,8 +10264,8 @@ function Set-NsxLogicalSwitch { } $uri = "/api/2.0/vdn/virtualwires/$($ObjectId)" - $null = Invoke-NsxWebRequest -method put -Uri $uri -body $_virtualWire.OuterXml -connection $connection - Get-NsxlogicalSwitch -ObjectId $ObjectId -connection $connection + $null = Invoke-NsxWebRequest -method put -URI $uri -body $_virtualWire.OuterXml -connection $connection + Get-NsxLogicalSwitch -ObjectId $ObjectId -Connection $connection } @@ -10281,36 +10287,36 @@ function Connect-NsxLogicalSwitch { specified LogicalSwitch. #> - [CmdLetBinding(DefaultParameterSetName="VM")] + [CmdLetBinding(DefaultParameterSetName = "VM")] param( - [Parameter(Mandatory=$true, ParameterSetName="VM", ValueFromPipeline=$true)] - #VM or collection of VMs to attach to specified logical switch. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop[]]$VirtualMachine, - [Parameter(Mandatory=$true, ParameterSetName="NIC", ValueFromPipeline=$true)] - #Network Adapter or collection of Network Adapters to attach to specified logical switch. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop[]]$NetworkAdapter, - [Parameter(Mandatory=$true, Position=1)] - #Logical Switch to connect NICs or VMs to. - [ValidateScript({ ValidateLogicalSwitch $_ })] - [System.Xml.XmlElement]$LogicalSwitch, - [Parameter(Mandatory=$false)] - #If specified VM is multi homed, connect all NICs to the same network. Defaults to $false - [switch]$ConnectMultipleNics=$false, - [Parameter(Mandatory=$false)] - #If job reaches -WaitTimeout without failing or completing, do we prompt, or fail with error? - [switch]$FailOnTimeout=$false, - [Parameter(Mandatory=$false)] - #Seconds to wait for connection job to complete. Defaults to 30 seconds. - [int]$WaitTimeout = 30, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) - - begin{ + [Parameter(Mandatory = $true, ParameterSetName = "VM", ValueFromPipeline = $true)] + #VM or collection of VMs to attach to specified logical switch. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop[]]$VirtualMachine, + [Parameter(Mandatory = $true, ParameterSetName = "NIC", ValueFromPipeline = $true)] + #Network Adapter or collection of Network Adapters to attach to specified logical switch. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop[]]$NetworkAdapter, + [Parameter(Mandatory = $true, Position = 1)] + #Logical Switch to connect NICs or VMs to. + [ValidateScript( { ValidateLogicalSwitch $_ })] + [System.Xml.XmlElement]$LogicalSwitch, + [Parameter(Mandatory = $false)] + #If specified VM is multi homed, connect all NICs to the same network. Defaults to $false + [switch]$ConnectMultipleNics = $false, + [Parameter(Mandatory = $false)] + #If job reaches -WaitTimeout without failing or completing, do we prompt, or fail with error? + [switch]$FailOnTimeout = $false, + [Parameter(Mandatory = $false)] + #Seconds to wait for connection job to complete. Defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) + + begin { function ProcessNic { @@ -10320,7 +10326,7 @@ function Connect-NsxLogicalSwitch { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($nic.parent | get-view).config.instanceuuid + $vmUuid = ($nic.parent | Get-View).config.instanceuuid $vnicUuid = "$vmUuid.$($nic.id.substring($nic.id.length-3))" #Construct XML @@ -10335,17 +10341,17 @@ function Connect-NsxLogicalSwitch { $body = $xmlroot.OuterXml $URI = "/api/2.0/vdn/virtualwires/vm/vnic" Write-Progress -Activity "Processing" -Status "Connecting $vnicuuid to logical switch $($LogicalSwitch.objectId)" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection Write-Progress -Activity "Processing" -Status "Connecting $vnicuuid to logical switch $($LogicalSwitch.objectId)" -Completed #api returns a task id. $job = [xml]$response.content $jobId = $job."com.vmware.vshield.vsm.vdn.dto.ui.ReconfigureVMTaskResultDto".jobId - Wait-NsxGenericJob -Jobid $JobID -Connection $Connection -WaitTimeout $WaitTimeout -FailOnTimeout:$FailOnTimeout + Wait-NsxGenericJob -JobId $JobID -Connection $Connection -WaitTimeout $WaitTimeout -FailOnTimeout:$FailOnTimeout } } - process{ + process { switch ( $PSCmdlet.ParameterSetName ) { @@ -10353,8 +10359,9 @@ function Connect-NsxLogicalSwitch { foreach ( $vm in $VirtualMachine ) { [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop[]]$nics = $vm | Get-NetworkAdapter switch ($nics.count) { - 0 { write-warning "Virtual Machine $($vm.name) ($($vm.extensiondata.moref.value)) has no network adapters. Nothing to do." } - 1 { #do nothing + 0 { Write-Warning "Virtual Machine $($vm.name) ($($vm.extensiondata.moref.value)) has no network adapters. Nothing to do." } + 1 { + #do nothing } default { if ( -not $ConnectMultipleNics ) { Throw "Virtual Machine $($vm.name) ($($vm.extensiondata.moref.value)) has more than one network adapter. Specify -ConnectMultipleNics switch if this is really what you want." } @@ -10362,19 +10369,19 @@ function Connect-NsxLogicalSwitch { } foreach ( $nic in $nics ) { - ProcessNic $nic + ProcessNic $nic } } } "NIC" { foreach ( $nic in $NetworkAdapter ) { - ProcessNic $nic + ProcessNic $nic } } } } - end{} + end {} } function Disconnect-NsxLogicalSwitch { @@ -10392,36 +10399,36 @@ function Disconnect-NsxLogicalSwitch { the specified LogicalSwitch. #> - [CmdLetBinding(DefaultParameterSetName="VM")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [CmdLetBinding(DefaultParameterSetName = "VM")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param( - [Parameter(Mandatory=$true, ParameterSetName="VM", ValueFromPipeline=$true)] - #VM or collection of VMs to attach to specified logical switch. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop[]]$VirtualMachine, - [Parameter(Mandatory=$true, ParameterSetName="NIC", ValueFromPipeline=$true)] - #Network Adapter or collection of Network Adapters to attach to specified logical switch. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop[]]$NetworkAdapter, - [Parameter(Mandatory=$false)] - #If specified VM is multi homed, disconnect all NICs from the same network. Defaults to $false - [switch]$DisconnectMultipleNics=$false, - [Parameter(Mandatory=$false)] - #Prompt for confirmation. - [switch]$Confirm=$true, - [Parameter(Mandatory=$false)] - #If job reaches -WaitTimeout without failing or completing, do we prompt, or fail with error? - [switch]$FailOnTimeout=$false, - [Parameter(Mandatory=$false)] - #Seconds to wait for connection job to complete. Defaults to 30 seconds. - [int]$WaitTimeout = 30, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) - - begin{ + [Parameter(Mandatory = $true, ParameterSetName = "VM", ValueFromPipeline = $true)] + #VM or collection of VMs to attach to specified logical switch. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop[]]$VirtualMachine, + [Parameter(Mandatory = $true, ParameterSetName = "NIC", ValueFromPipeline = $true)] + #Network Adapter or collection of Network Adapters to attach to specified logical switch. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop[]]$NetworkAdapter, + [Parameter(Mandatory = $false)] + #If specified VM is multi homed, disconnect all NICs from the same network. Defaults to $false + [switch]$DisconnectMultipleNics = $false, + [Parameter(Mandatory = $false)] + #Prompt for confirmation. + [switch]$Confirm = $true, + [Parameter(Mandatory = $false)] + #If job reaches -WaitTimeout without failing or completing, do we prompt, or fail with error? + [switch]$FailOnTimeout = $false, + [Parameter(Mandatory = $false)] + #Seconds to wait for connection job to complete. Defaults to 30 seconds. + [int]$WaitTimeout = 30, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) + + begin { function ProcessNic { @@ -10431,7 +10438,7 @@ function Disconnect-NsxLogicalSwitch { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($nic.parent | get-view).config.instanceuuid + $vmUuid = ($nic.parent | Get-View).config.instanceuuid $vnicUuid = "$vmUuid.$($nic.id.substring($nic.id.length-3))" #Construct XML @@ -10446,7 +10453,7 @@ function Disconnect-NsxLogicalSwitch { $body = $xmlroot.OuterXml $URI = "/api/2.0/vdn/virtualwires/vm/vnic" if ( $confirm ) { - $message = "Disconnecting $($nic.Parent.Name)'s network adapter from a logical switch will cause network connectivity loss." + $message = "Disconnecting $($nic.Parent.Name)'s network adapter from a logical switch will cause network connectivity loss." $question = "Proceed with disconnection?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -10458,19 +10465,19 @@ function Disconnect-NsxLogicalSwitch { else { $decision = 0 } if ($decision -eq 0) { Write-Progress -Activity "Processing" -Status "Disconnecting $vnicuuid from logical switch" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection Write-Progress -Activity "Processing" -Status "Disconnecting $vnicuuid from logical switch" -Completed $job = [xml]$response.content $jobId = $job."com.vmware.vshield.vsm.vdn.dto.ui.ReconfigureVMTaskResultDto".jobId - Wait-NsxGenericJob -Jobid $JobID -Connection $Connection -WaitTimeout $WaitTimeout -FailOnTimeout:$FailOnTimeout + Wait-NsxGenericJob -JobId $JobID -Connection $Connection -WaitTimeout $WaitTimeout -FailOnTimeout:$FailOnTimeout } } } - process{ + process { switch ( $PSCmdlet.ParameterSetName ) { @@ -10478,8 +10485,9 @@ function Disconnect-NsxLogicalSwitch { foreach ( $vm in $VirtualMachine ) { [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop[]]$nics = $vm | Get-NetworkAdapter switch ($nics.count) { - 0 { write-warning "Virtual Machine $($vm.name) ($($vm.extensiondata.moref.value)) has no network adapters. Nothing to do." } - 1 { #do nothing + 0 { Write-Warning "Virtual Machine $($vm.name) ($($vm.extensiondata.moref.value)) has no network adapters. Nothing to do." } + 1 { + #do nothing } default { if ( -not $DisconnectMultipleNics ) { Throw "Virtual Machine $($vm.name) ($($vm.extensiondata.moref.value)) has more than one network adapter. Specify -ConnectMultipleNics switch if this is really what you want." } @@ -10487,19 +10495,19 @@ function Disconnect-NsxLogicalSwitch { } foreach ( $nic in $nics ) { - ProcessNic $nic + ProcessNic $nic } } } "NIC" { foreach ( $nic in $nics ) { - ProcessNic $nic + ProcessNic $nic } } } } - end{} + end {} } ######### @@ -10536,21 +10544,21 @@ function Get-NsxSpoofguardPolicy { Get a specific Spoofguard policy #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$false, ParameterSetName="Name", Position=1)] - [ValidateNotNullorEmpty()] - [String]$Name, - [Parameter (Mandatory=$false, ParameterSetName="ObjectId")] - [ValidateNotNullorEmpty()] - [string]$objectId, - [Parameter (Mandatory=$false, ParameterSetName="ObjectId")] - [Parameter (Mandatory=$false, ParameterSetName="Name")] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [ValidateNotNullorEmpty()] + [String]$Name, + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + [ValidateNotNullorEmpty()] + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + [Parameter (Mandatory = $false, ParameterSetName = "Name")] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -10560,12 +10568,13 @@ function Get-NsxSpoofguardPolicy { if ( $PsCmdlet.ParameterSetName -eq 'Name' ) { #All SG Policies $URI = "/api/4.0/services/spoofguard/policies/" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::spoofguardPolicies/spoofguardPolicy')) { - if ( $Name ) { - $polcollection = $response.spoofguardPolicies.spoofguardPolicy | where-object { $_.name -eq $Name } - } else { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::spoofguardPolicies/spoofguardPolicy')) { + if ( $Name ) { + $polcollection = $response.spoofguardPolicies.spoofguardPolicy | Where-Object { $_.name -eq $Name } + } + else { $polcollection = $response.spoofguardPolicies.spoofguardPolicy } foreach ($pol in $polcollection ) { @@ -10574,7 +10583,7 @@ function Get-NsxSpoofguardPolicy { #get-nsxsgpolicy which I dont like. $URI = "/api/4.0/services/spoofguard/policies/$($pol.policyId)" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { $response.spoofguardPolicy } @@ -10590,7 +10599,7 @@ function Get-NsxSpoofguardPolicy { #Just getting a single SG Policy $URI = "/api/4.0/services/spoofguard/policies/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { $response.spoofguardPolicy } @@ -10659,27 +10668,27 @@ function New-NsxSpoofguardPolicy { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$Description, - [Parameter (Mandatory=$true)] - [ValidateSet("tofu","manual","disable")] - [string]$OperationMode, - [Parameter (Mandatory=$false)] - [switch]$AllowLocalIps, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroupOrStandardPortGroup $_ })] - [object[]]$Network, - [Parameter (Mandatory=$False)] - [switch]$Publish=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Description, + [Parameter (Mandatory = $true)] + [ValidateSet("tofu", "manual", "disable")] + [string]$OperationMode, + [Parameter (Mandatory = $false)] + [switch]$AllowLocalIps, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroupOrStandardPortGroup $_ })] + [object[]]$Network, + [Parameter (Mandatory = $False)] + [switch]$Publish = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin {} process { @@ -10687,7 +10696,7 @@ function New-NsxSpoofguardPolicy { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("spoofguardPolicy") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "operationMode" -xmlElementText $OperationMode.ToUpper() @@ -10701,11 +10710,11 @@ function New-NsxSpoofguardPolicy { foreach ( $Net in $Network) { [System.XML.XMLElement]$xmlEnforcementPoint = $XMLDoc.CreateElement("enforcementPoint") - $xmlroot.appendChild($xmlEnforcementPoint) | out-null + $xmlroot.appendChild($xmlEnforcementPoint) | Out-Null switch ( $Net ) { - { $_ -is [System.Xml.XmlElement] } { + { $_ -is [System.Xml.XmlElement] } { $id = $_.objectId } @@ -10723,7 +10732,7 @@ function New-NsxSpoofguardPolicy { #You also dont seem to be able to do a get-view on it :| #So, I have get a hasthtable of all morefs that represent VSS based PGs and search it for the name of the PG the user specified. Im fairly (not 100%) sure this is safe as networkname should be unique at least within VSS portgroups... - $StandardPgHash = Get-View -ViewType Network -Property Name | where-object { $_.Moref.Type -match 'Network' } | select-object name, moref | Sort-Object -Property Name -Unique | Group-Object -AsHashTable -Property Name + $StandardPgHash = Get-View -ViewType Network -Property Name | Where-Object { $_.Moref.Type -match 'Network' } | Select-Object name, moref | Sort-Object -Property Name -Unique | Group-Object -AsHashTable -Property Name $Item = $StandardPgHash.Item($_.name) if ( -not $item ) { throw "PortGroup $($_.name) not found." } @@ -10738,15 +10747,15 @@ function New-NsxSpoofguardPolicy { #Do the post $body = $xmlroot.OuterXml $URI = "/api/4.0/services/spoofguard/policies/" - $policyId = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $policyId = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection #Now we Publish... if ( $publish ) { $URI = "/api/4.0/services/spoofguard/$($policyId)?action=publish" - $null = invoke-nsxwebrequest -method "post" -uri $URI -connection $connection + $null = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection } - Get-NsxSpoofguardPolicy -objectId $policyId -connection $connection + Get-NsxSpoofguardPolicy -objectId $policyId -Connection $connection } end {} @@ -10789,19 +10798,19 @@ function Remove-NsxSpoofguardPolicy { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$SpoofguardPolicy, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$SpoofguardPolicy, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -10810,11 +10819,11 @@ function Remove-NsxSpoofguardPolicy { process { if ( $SpoofguardPolicy.defaultPolicy -eq 'true') { - write-warning "Cant delete the default Spoofguard policy" + Write-Warning "Cant delete the default Spoofguard policy" } else { if ( $confirm ) { - $message = "Spoofguard Policy removal is permanent." + $message = "Spoofguard Policy removal is permanent." $question = "Proceed with removal of Spoofguard Policy $($SpoofguardPolicy.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -10827,9 +10836,9 @@ function Remove-NsxSpoofguardPolicy { if ($decision -eq 0) { $URI = "/api/4.0/services/spoofguard/policies/$($SpoofguardPolicy.policyId)" - Write-Progress -activity "Remove Spoofguard Policy $($SpoofguardPolicy.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Spoofguard Policy $($SpoofguardPolicy.Name)" -completed + Write-Progress -Activity "Remove Spoofguard Policy $($SpoofguardPolicy.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Spoofguard Policy $($SpoofguardPolicy.Name)" -Completed } } } @@ -10870,20 +10879,20 @@ function Publish-NsxSpoofguardPolicy { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$SpoofguardPolicy, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$SpoofguardPolicy, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -10892,7 +10901,7 @@ function Publish-NsxSpoofguardPolicy { process { if ( $confirm ) { - $message = "Spoofguard Policy publishing will cause the current policy to be enforced." + $message = "Spoofguard Policy publishing will cause the current policy to be enforced." $question = "Proceed with publish operation on Spoofguard Policy $($SpoofguardPolicy.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -10905,11 +10914,11 @@ function Publish-NsxSpoofguardPolicy { if ($decision -eq 0) { $URI = "/api/4.0/services/spoofguard/$($SpoofguardPolicy.policyId)?action=publish" - Write-Progress -activity "Publish Spoofguard Policy $($SpoofguardPolicy.Name)" - invoke-nsxrestmethod -method "post" -uri $URI -connection $connection | out-null - write-progress -activity "Publish Spoofguard Policy $($SpoofguardPolicy.Name)" -completed + Write-Progress -Activity "Publish Spoofguard Policy $($SpoofguardPolicy.Name)" + Invoke-NsxRestMethod -method "post" -URI $URI -connection $connection | Out-Null + Write-Progress -Activity "Publish Spoofguard Policy $($SpoofguardPolicy.Name)" -Completed - Get-NsxSpoofguardPolicy -objectId $($SpoofguardPolicy.policyId) -connection $connection + Get-NsxSpoofguardPolicy -objectId $($SpoofguardPolicy.policyId) -Connection $connection } } @@ -10956,44 +10965,44 @@ function Get-NsxSpoofguardNic { Get all Inactive spoofguard Nics #> - [CmdLetBinding(DefaultParameterSetName="Default")] + [CmdLetBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "Default")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "MAC")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "VM")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "NIC")] - [ValidateScript( { ValidateSpoofguardPolicy $_ } )] - [System.xml.xmlElement]$SpoofguardPolicy, - [Parameter (Mandatory=$false, ParameterSetName = "Default")] - [Parameter (Mandatory=$false, ParameterSetName = "MAC")] - [Parameter (Mandatory=$false, ParameterSetName = "VM")] - [Parameter (Mandatory=$false, ParameterSetName = "NIC")] - [Validateset("Active", "Inactive", "Published", "Unpublished", "Review_Pending", "Duplicate")] - [string]$Filter, - [Parameter (Mandatory=$false, ParameterSetName = "MAC")] - [ValidateScript({ + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Default")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "MAC")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "VM")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "NIC")] + [ValidateScript( { ValidateSpoofguardPolicy $_ } )] + [System.xml.xmlElement]$SpoofguardPolicy, + [Parameter (Mandatory = $false, ParameterSetName = "Default")] + [Parameter (Mandatory = $false, ParameterSetName = "MAC")] + [Parameter (Mandatory = $false, ParameterSetName = "VM")] + [Parameter (Mandatory = $false, ParameterSetName = "NIC")] + [Validateset("Active", "Inactive", "Published", "Unpublished", "Review_Pending", "Duplicate")] + [string]$Filter, + [Parameter (Mandatory = $false, ParameterSetName = "MAC")] + [ValidateScript( { if ( $_ -notmatch "[a-f,A-F,0-9]{2}:[a-f,A-F,0-9]{2}:[a-f,A-F,0-9]{2}:[a-f,A-F,0-9]{2}:[a-f,A-F,0-9]{2}:[a-f,A-F,0-9]{2}" ) { throw "Specify a valid MAC address (0 must be specified as 00)" } $true - })] - [string]$MacAddress, - [Parameter (Mandatory=$false, ParameterSetName = "VM")] - #PowerCLI VirtualMachine object - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$false, ParameterSetName = "NIC")] - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop]$NetworkAdapter, - [Parameter (Mandatory=$false, ParameterSetName = "Default")] - [Parameter (Mandatory=$false, ParameterSetName = "MAC")] - [Parameter (Mandatory=$false, ParameterSetName = "VM")] - [Parameter (Mandatory=$false, ParameterSetName = "NIC")] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + })] + [string]$MacAddress, + [Parameter (Mandatory = $false, ParameterSetName = "VM")] + #PowerCLI VirtualMachine object + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, + [Parameter (Mandatory = $false, ParameterSetName = "NIC")] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop]$NetworkAdapter, + [Parameter (Mandatory = $false, ParameterSetName = "Default")] + [Parameter (Mandatory = $false, ParameterSetName = "MAC")] + [Parameter (Mandatory = $false, ParameterSetName = "VM")] + [Parameter (Mandatory = $false, ParameterSetName = "NIC")] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -11009,22 +11018,22 @@ function Get-NsxSpoofguardNic { $URI = "/api/4.0/services/spoofguard/$($SpoofguardPolicy.policyId)?list=ALL" } - [system.xml.xmldocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [system.xml.xmldocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::spoofguardList/spoofguard')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::spoofguardList/spoofguard')) { switch ( $PsCmdlet.ParameterSetName ) { - "MAC" { $outcollection = $response.spoofguardList.Spoofguard | where-object { $_.detectedMacAddress -eq $MacAddress } } + "MAC" { $outcollection = $response.spoofguardList.Spoofguard | Where-Object { $_.detectedMacAddress -eq $MacAddress } } "NIC" { $MacAddress = $NetworkAdapter.MacAddress - $outcollection = $response.spoofguardList.Spoofguard | where-object { $_.detectedMacAddress -eq $MacAddress } + $outcollection = $response.spoofguardList.Spoofguard | Where-Object { $_.detectedMacAddress -eq $MacAddress } } "VM" { foreach ( $Nic in ($virtualmachine | Get-NetworkAdapter )) { $MacAddress = $Nic.MacAddress - $outcollection = $response.spoofguardList.Spoofguard | where-object { $_.detectedMacAddress -eq $MacAddress } + $outcollection = $response.spoofguardList.Spoofguard | Where-Object { $_.detectedMacAddress -eq $MacAddress } } } default { $outcollection = $response.spoofguardList.Spoofguard } @@ -11038,7 +11047,7 @@ function Get-NsxSpoofguardNic { $outcollection } else { - write-debug "$($MyInvocation.MyCommand.Name) : No results found." + Write-Debug "$($MyInvocation.MyCommand.Name) : No results found." } } end {} @@ -11084,28 +11093,28 @@ function Grant-NsxSpoofguardNicApproval { #> - [CmdLetBinding(DefaultParameterSetName="ipAddress")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [CmdLetBinding(DefaultParameterSetName = "ipAddress")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateScript( { ValidateSpoofguardNic $_ } )] - [System.xml.xmlElement]$SpoofguardNic, - [Parameter (Mandatory=$True, ParameterSetName="ipAddress")] - [ValidateNotNullOrEmpty()] - [string[]]$IpAddress, - [Parameter (Mandatory=$True, ParameterSetName="ApproveAll")] - [ValidateNotNullOrEmpty()] - [switch]$ApproveAllDetectedIps=$False, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$Publish=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateSpoofguardNic $_ } )] + [System.xml.xmlElement]$SpoofguardNic, + [Parameter (Mandatory = $True, ParameterSetName = "ipAddress")] + [ValidateNotNullOrEmpty()] + [string[]]$IpAddress, + [Parameter (Mandatory = $True, ParameterSetName = "ApproveAll")] + [ValidateNotNullOrEmpty()] + [switch]$ApproveAllDetectedIps = $False, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$Publish = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -11116,26 +11125,26 @@ function Grant-NsxSpoofguardNicApproval { [System.XML.XMLDocument]$xmlDoc = $_SpoofguardNic.OwnerDocument [System.XML.XMLElement]$spoofguardList = $XMLDoc.CreateElement("spoofguardList") - $spoofguardList.appendChild($_SpoofguardNic) | out-null + $spoofguardList.appendChild($_SpoofguardNic) | Out-Null #Get and Remove the policyId element we put there... $policyId = $_SpoofguardNic.policyId - $_SpoofguardNic.RemoveChild((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -Query 'descendant::policyId')) | out-null + $_SpoofguardNic.RemoveChild((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -query 'descendant::policyId')) | Out-Null #if approvedIpAddress element does not exist, create it - [system.xml.xmlElement]$approvedIpAddressNode = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -Query 'descendant::approvedIpAddress') + [system.xml.xmlElement]$approvedIpAddressNode = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -query 'descendant::approvedIpAddress') if ( -not $approvedIpAddressNode ) { [System.XML.XMLElement]$approvedIpAddressNode = $XMLDoc.CreateElement("approvedIpAddress") - $_SpoofguardNic.appendChild($approvedIpAddressNode) | out-null + $_SpoofguardNic.appendChild($approvedIpAddressNode) | Out-Null } #If they are, Add the ip(s) specified if ( $PsBoundParameters.ContainsKey('ipAddress') ) { foreach ( $ip in $ipAddress ) { - if ( (Invoke-XPathQuery -QueryMethod SelectNodes -Node $approvedIpAddressNode -Query "descendant::ipAddress") | where-object { $_.'#Text' -eq $ip }) { - write-warning "Not adding duplicate IP Address $ip as it is already added." + if ( (Invoke-XpathQuery -QueryMethod SelectNodes -Node $approvedIpAddressNode -query "descendant::ipAddress") | Where-Object { $_.'#Text' -eq $ip }) { + Write-Warning "Not adding duplicate IP Address $ip as it is already added." } else { Add-XmlElement -xmlRoot $approvedIpAddressNode -xmlElementName "ipAddress" -xmlElementText $ip @@ -11144,11 +11153,11 @@ function Grant-NsxSpoofguardNicApproval { } #If there are IPs detected, and approve all is on, ensure user understands consequence. - If ( $ApproveAllDetectedIps -and ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -Query 'descendant::detectedIpAddress/ipAddress'))) { + If ( $ApproveAllDetectedIps -and ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -query 'descendant::detectedIpAddress/ipAddress'))) { If ($confirm ) { - $message = "Do you want to automatically approve all IP Addresses detected on the NIC $($_SpoofguardNic.nicName)?." + $message = "Do you want to automatically approve all IP Addresses detected on the NIC $($_SpoofguardNic.nicName)?." $question = "Validate the detected IP addresses before continuing. Proceed?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -11160,11 +11169,11 @@ function Grant-NsxSpoofguardNicApproval { else { $decision = 0 } if ($decision -eq 0) { - foreach ( $ip in $_SpoofguardNic.detectedIpAddress.ipAddress ) { + foreach ( $ip in $_SpoofguardNic.detectedIpAddress.ipAddress ) { #Have to ensure we dont add a duplicate here... - if ( (Invoke-XPathQuery -QueryMethod SelectNodes -Node $approvedIpAddressNode -Query "descendant::ipAddress") | where-object { $_.'#Text' -eq $ip }) { - write-warning "Not adding duplicate IP Address $ip as it is already added." + if ( (Invoke-XpathQuery -QueryMethod SelectNodes -Node $approvedIpAddressNode -query "descendant::ipAddress") | Where-Object { $_.'#Text' -eq $ip }) { + Write-Warning "Not adding duplicate IP Address $ip as it is already added." } else { Add-XmlElement -xmlRoot $approvedIpAddressNode -xmlElementName "ipAddress" -xmlElementText $ip @@ -11201,15 +11210,15 @@ function Grant-NsxSpoofguardNicApproval { #Do the post $body = $spoofguardList.OuterXml $URI = "/api/4.0/services/spoofguard/$($policyId)?action=approve" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection #Now we Publish... if ( $publish ) { $URI = "/api/4.0/services/spoofguard/$($policyId)?action=publish" - $response = invoke-nsxwebrequest -method "post" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection } - Get-NsxSpoofguardPolicy -objectId $policyId -connection $connection | Get-NsxSpoofguardNic -MAC $_SpoofguardNic.detectedMacAddress -connection $connection + Get-NsxSpoofguardPolicy -objectId $policyId -Connection $connection | Get-NsxSpoofguardNic -MAC $_SpoofguardNic.detectedMacAddress -Connection $connection } end {} @@ -11245,28 +11254,28 @@ function Revoke-NsxSpoofguardNicApproval { Revoke the approval for IP 1.2.3.4 from the first nic on vm evil-vm. #> - [CmdLetBinding(DefaultParameterSetName="IpList")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [CmdLetBinding(DefaultParameterSetName = "IpList")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateScript( { ValidateSpoofguardNic $_ } )] - [System.xml.xmlElement]$SpoofguardNic, - [Parameter (Mandatory=$True, ParameterSetName="IpList")] - [ValidateNotNullOrEmpty()] - [string[]]$IpAddress, - [Parameter (Mandatory=$True, ParameterSetName="RevokeAll")] - [ValidateNotNullOrEmpty()] - [switch]$RevokeAllApprovedIps, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$Publish=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateSpoofguardNic $_ } )] + [System.xml.xmlElement]$SpoofguardNic, + [Parameter (Mandatory = $True, ParameterSetName = "IpList")] + [ValidateNotNullOrEmpty()] + [string[]]$IpAddress, + [Parameter (Mandatory = $True, ParameterSetName = "RevokeAll")] + [ValidateNotNullOrEmpty()] + [switch]$RevokeAllApprovedIps, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$Publish = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -11277,30 +11286,30 @@ function Revoke-NsxSpoofguardNicApproval { [System.XML.XMLDocument]$xmlDoc = $_SpoofguardNic.OwnerDocument [System.XML.XMLElement]$spoofguardList = $XMLDoc.CreateElement("spoofguardList") - $spoofguardList.appendChild($_SpoofguardNic) | out-null + $spoofguardList.appendChild($_SpoofguardNic) | Out-Null #Get and Remove the policyId element we put there... $policyId = $_SpoofguardNic.policyId - $_SpoofguardNic.RemoveChild((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -Query 'descendant::policyId')) | out-null + $_SpoofguardNic.RemoveChild((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -query 'descendant::policyId')) | Out-Null #if approvedIpAddress element does not exist, bail - [system.xml.xmlElement]$approvedIpAddressNode = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -Query 'descendant::approvedIpAddress') - if ( -not $approvedIpAddressNode -or (-not ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $approvedIpAddressNode -Query 'descendant::ipAddress')))) { + [system.xml.xmlElement]$approvedIpAddressNode = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -query 'descendant::approvedIpAddress') + if ( -not $approvedIpAddressNode -or (-not ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $approvedIpAddressNode -query 'descendant::ipAddress')))) { Write-Warning "Nic $($_SpoofguardNic.NicName) has no approved IPs" } else { - [system.xml.xmlElement]$publishedIpAddressNode = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -Query 'descendant::publishedIpAddress') + [system.xml.xmlElement]$publishedIpAddressNode = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SpoofguardNic -query 'descendant::publishedIpAddress') - $approvedIpCollection = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $approvedIpAddressNode -Query "descendant::ipAddress") - $publishedIpCollection = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $publishedIpAddressNode -Query "descendant::ipAddress") + $approvedIpCollection = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $approvedIpAddressNode -query "descendant::ipAddress") + $publishedIpCollection = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $publishedIpAddressNode -query "descendant::ipAddress") #If there are IPs detected, and revoke all is on, kill em all... If ( $PSCmdlet.ParameterSetName -eq "RevokeAll" ) { foreach ( $node in $approvedIpCollection ) { - $approvedIpAddressNode.RemoveChild($node) | out-null + $approvedIpAddressNode.RemoveChild($node) | Out-Null } } @@ -11308,17 +11317,17 @@ function Revoke-NsxSpoofguardNicApproval { #$IPAddress is mandatory... foreach ( $ip in $ipAddress ) { - $currentApprovedIpNode = $approvedIpCollection | where-object { $_.'#Text' -eq $ip } - $currentPublishedIpNode = $publishedIpCollection | where-object { $_.'#Text' -eq $ip } + $currentApprovedIpNode = $approvedIpCollection | Where-Object { $_.'#Text' -eq $ip } + $currentPublishedIpNode = $publishedIpCollection | Where-Object { $_.'#Text' -eq $ip } if ( -not $currentApprovedIpNode ) { - write-warning "IP Address $ip is not currently approved on Nic $($_SpoofguardNic.NicName)." + Write-Warning "IP Address $ip is not currently approved on Nic $($_SpoofguardNic.NicName)." } else { - $approvedIpAddressNode.RemoveChild($currentApprovedIpNode) | out-null + $approvedIpAddressNode.RemoveChild($currentApprovedIpNode) | Out-Null if ( $currentPublishedIpNode ) { - $publishedIpAddressNode.RemoveChild($currentPublishedIpNode) | out-null + $publishedIpAddressNode.RemoveChild($currentPublishedIpNode) | Out-Null } } } @@ -11326,7 +11335,7 @@ function Revoke-NsxSpoofguardNicApproval { If ($confirm ) { - $message = "Do you want to remove the specified IP Addresses from the approved list of the NIC $($_SpoofguardNic.nicName)?." + $message = "Do you want to remove the specified IP Addresses from the approved list of the NIC $($_SpoofguardNic.nicName)?." $question = "Removal is permenant. Proceed?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -11341,15 +11350,15 @@ function Revoke-NsxSpoofguardNicApproval { #Do the post $body = $spoofguardList.OuterXml $URI = "/api/4.0/services/spoofguard/$($policyId)?action=approve" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection #Now we Publish... if ( $publish) { $URI = "/api/4.0/services/spoofguard/$($policyId)?action=publish" - $response = invoke-nsxwebrequest -method "post" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection } - Get-NsxSpoofguardPolicy -objectId $policyId -connection $connection | Get-NsxSpoofguardNic -MAC $_SpoofguardNic.detectedMacAddress -connection $connection + Get-NsxSpoofguardPolicy -objectId $policyId -Connection $connection | Get-NsxSpoofguardNic -MAC $_SpoofguardNic.detectedMacAddress -Connection $connection } } } @@ -11388,32 +11397,32 @@ function New-NsxLogicalRouterInterfaceSpec { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true)] - [ValidateSet ("internal","uplink")] - [string]$Type, - [Parameter (Mandatory=$false)] - [ValidateScript({ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$ConnectedTo, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [ValidateRange(1,9128)] - [int]$MTU=1500, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Connected=$true, - [Parameter (Mandatory=$false)] - [ValidateRange(1,1000)] - [int]$Index + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true)] + [ValidateSet ("internal", "uplink")] + [string]$Type, + [Parameter (Mandatory = $false)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$ConnectedTo, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 9128)] + [int]$MTU = 1500, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Connected = $true, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 1000)] + [int]$Index ) begin { @@ -11424,7 +11433,7 @@ function New-NsxLogicalRouterInterfaceSpec { } if (( $PsBoundParameters.ContainsKey("PrimaryAddress") -and ( -not $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) -or - (( -not $PsBoundParameters.ContainsKey("PrimaryAddress")) -and $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) { + (( -not $PsBoundParameters.ContainsKey("PrimaryAddress")) -and $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) { #Not allowed to have subnet without primary or vice versa. throw "Interfaces with a Primary address must also specify a prefix length and vice versa." @@ -11435,7 +11444,7 @@ function New-NsxLogicalRouterInterfaceSpec { [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlVnic = $XMLDoc.CreateElement("interface") - $xmlDoc.appendChild($xmlVnic) | out-null + $xmlDoc.appendChild($xmlVnic) | Out-Null if ( $PsBoundParameters.ContainsKey("Name")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "name" -xmlElementText $Name } if ( $PsBoundParameters.ContainsKey("Type")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "type" -xmlElementText $type } @@ -11443,9 +11452,9 @@ function New-NsxLogicalRouterInterfaceSpec { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "mtu" -xmlElementText $MTU Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "isConnected" -xmlElementText $Connected - switch ($ConnectedTo){ - { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } - { $_ -is [System.Xml.XmlElement]} { $PortGroupID = $_.objectId } + switch ($ConnectedTo) { + { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } + { $_ -is [System.Xml.XmlElement] } { $PortGroupID = $_.objectId } } if ( $PsBoundParameters.ContainsKey("ConnectedTo")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "connectedToId" -xmlElementText $PortGroupID } @@ -11454,13 +11463,13 @@ function New-NsxLogicalRouterInterfaceSpec { #For now, only supporting one addressgroup - will refactor later [System.XML.XMLElement]$xmlAddressGroups = $XMLDoc.CreateElement("addressGroups") - $xmlVnic.appendChild($xmlAddressGroups) | out-null + $xmlVnic.appendChild($xmlAddressGroups) | Out-Null $AddressGroupParameters = @{ xmlAddressGroups = $xmlAddressGroups } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $AddressGroupParameters.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $AddressGroupParameters.Add("SubnetPrefixLength",$SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $AddressGroupParameters.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $AddressGroupParameters.Add("SubnetPrefixLength", $SubnetPrefixLength) } AddNsxEdgeVnicAddressGroup @AddressGroupParameters @@ -11485,17 +11494,17 @@ function Get-NsxLogicalRouter { PS C:\> Get-NsxLogicalRouter LR1 #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - [string]$objectId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -11504,44 +11513,44 @@ function Get-NsxLogicalRouter { "Name" { $URI = "/api/4.0/edges?pageSize=$pagesize&startIndex=00" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection #Edge summary XML is returned as paged data, means we have to handle it. #Then we have to query for full information on a per edge basis. $edgesummaries = @() $edges = @() - $itemIndex = 0 + $itemIndex = 0 $startingIndex = 0 $pagingInfo = $response.pagedEdgeList.edgePage.pagingInfo if ( [int]$paginginfo.totalCount -ne 0 ) { - write-debug "$($MyInvocation.MyCommand.Name) : Logical Router count non zero" + Write-Debug "$($MyInvocation.MyCommand.Name) : Logical Router count non zero" do { - write-debug "$($MyInvocation.MyCommand.Name) : In paging loop. PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : In paging loop. PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" while (($itemindex -lt ([int]$paginginfo.pagesize + $startingIndex)) -and ($itemIndex -lt [int]$paginginfo.totalCount )) { - write-debug "$($MyInvocation.MyCommand.Name) : In Item Processing Loop: ItemIndex: $itemIndex" - write-debug "$($MyInvocation.MyCommand.Name) : $(@($response.pagedEdgeList.edgePage.edgeSummary)[($itemIndex - $startingIndex)].objectId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : In Item Processing Loop: ItemIndex: $itemIndex" + Write-Debug "$($MyInvocation.MyCommand.Name) : $(@($response.pagedEdgeList.edgePage.edgeSummary)[($itemIndex - $startingIndex)].objectId)" #Need to wrap the edgesummary prop of the datapage in case we get exactly 1 item - #which powershell annoyingly unwraps to a single xml element rather than an array... $edgesummaries += @($response.pagedEdgeList.edgePage.edgeSummary)[($itemIndex - $startingIndex)] $itemIndex += 1 } - write-debug "$($MyInvocation.MyCommand.Name) : Out of item processing - PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Out of item processing - PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" if ( [int]$paginginfo.totalcount -gt $itemIndex) { - write-debug "$($MyInvocation.MyCommand.Name) : PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" $startingIndex += $pagesize $URI = "/api/4.0/edges?pageSize=$pagesize&startIndex=$startingIndex" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $pagingInfo = $response.pagedEdgeList.edgePage.pagingInfo } } until ( [int]$paginginfo.totalcount -le $itemIndex ) - write-debug "$($MyInvocation.MyCommand.Name) : Completed page processing: ItemIndex: $itemIndex" + Write-Debug "$($MyInvocation.MyCommand.Name) : Completed page processing: ItemIndex: $itemIndex" } #What we got here is...failure to communicate! In order to get full detail, we have to requery for each edgeid. @@ -11551,18 +11560,19 @@ function Get-NsxLogicalRouter { foreach ($edgesummary in $edgesummaries) { $URI = "/api/4.0/edges/$($edgesummary.objectID)" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $import = $response.edge.ownerDocument.ImportNode($edgesummary, $true) - $response.edge.appendChild($import) | out-null + $response.edge.appendChild($import) | Out-Null $edges += $response.edge } if ( $name ) { - $edges | where-object { $_.Type -eq 'distributedRouter' } | where-object { $_.name -eq $name } + $edges | Where-Object { $_.Type -eq 'distributedRouter' } | Where-Object { $_.name -eq $name } - } else { - $edges | where-object { $_.Type -eq 'distributedRouter' } + } + else { + $edges | Where-Object { $_.Type -eq 'distributedRouter' } } @@ -11571,12 +11581,12 @@ function Get-NsxLogicalRouter { "objectId" { $URI = "/api/4.0/edges/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $edge = $response.edge $URI = "/api/4.0/edges/$objectId/summary" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $import = $edge.ownerDocument.ImportNode($($response.edgeSummary), $true) - $edge.AppendChild($import) | out-null + $edge.AppendChild($import) | Out-Null $edge } @@ -11631,48 +11641,48 @@ function New-NsxLogicalRouter { #> param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$ManagementPortGroup, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLogicalRouterInterfaceSpec $_ })] - [System.Xml.XmlElement[]]$Interface, - [Parameter (Mandatory=$true,ParameterSetName="ResourcePool")] - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, - [Parameter (Mandatory=$true,ParameterSetName="Cluster")] - [ValidateScript({ - if ( $_ -eq $null ) { throw "Must specify Cluster."} - if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled."} + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$ManagementPortGroup, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLogicalRouterInterfaceSpec $_ })] + [System.Xml.XmlElement[]]$Interface, + [Parameter (Mandatory = $true, ParameterSetName = "ResourcePool")] + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, + [Parameter (Mandatory = $true, ParameterSetName = "Cluster")] + [ValidateScript( { + if ( $_ -eq $null ) { throw "Must specify Cluster." } + if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled." } $true })] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$EnableHA=$false, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$HADatastore=$datastore, - [Parameter (Mandatory=$false)] - #Set to deploy as a universal distributed logical router. - [switch]$Universal=$false, - [Parameter (Mandatory=$false)] - #Create the universal logical router with Local Egress enabled. - [switch]$EnableLocalEgress=$false, - [Parameter (Mandatory=$false)] - #Optional tenant string to be configured on the DLR. - [ValidateNotNullOrEmpty()] - [String]$Tenant, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$EnableHA = $false, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$HADatastore = $datastore, + [Parameter (Mandatory = $false)] + #Set to deploy as a universal distributed logical router. + [switch]$Universal = $false, + [Parameter (Mandatory = $false)] + #Create the universal logical router with Local Egress enabled. + [switch]$EnableLocalEgress = $false, + [Parameter (Mandatory = $false)] + #Optional tenant string to be configured on the DLR. + [ValidateNotNullOrEmpty()] + [String]$Tenant, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -11681,7 +11691,7 @@ function New-NsxLogicalRouter { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("edge") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "type" -xmlElementText "distributedRouter" @@ -11690,41 +11700,41 @@ function New-NsxLogicalRouter { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "tenant" -xmlElementText $Tenant } - switch ($ManagementPortGroup){ - { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } - { $_ -is [System.Xml.XmlElement]} { $PortGroupID = $_.objectId } + switch ($ManagementPortGroup) { + { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } + { $_ -is [System.Xml.XmlElement] } { $PortGroupID = $_.objectId } } [System.XML.XMLElement]$xmlMgmtIf = $XMLDoc.CreateElement("mgmtInterface") - $xmlRoot.appendChild($xmlMgmtIf) | out-null + $xmlRoot.appendChild($xmlMgmtIf) | Out-Null Add-XmlElement -xmlRoot $xmlMgmtIf -xmlElementName "connectedToId" -xmlElementText $PortGroupID [System.XML.XMLElement]$xmlAppliances = $XMLDoc.CreateElement("appliances") - $xmlRoot.appendChild($xmlAppliances) | out-null + $xmlRoot.appendChild($xmlAppliances) | Out-Null - switch ($psCmdlet.ParameterSetName){ - "Cluster" { $ResPoolId = $($cluster | get-resourcepool | where-object { $_.parent.id -eq $cluster.id }).extensiondata.moref.value } - "ResourcePool" { $ResPoolId = $ResourcePool.extensiondata.moref.value } + switch ($psCmdlet.ParameterSetName) { + "Cluster" { $ResPoolId = $($cluster | Get-ResourcePool | Where-Object { $_.parent.id -eq $cluster.id }).extensiondata.moref.value } + "ResourcePool" { $ResPoolId = $ResourcePool.extensiondata.moref.value } } [System.XML.XMLElement]$xmlAppliance = $XMLDoc.CreateElement("appliance") - $xmlAppliances.appendChild($xmlAppliance) | out-null + $xmlAppliances.appendChild($xmlAppliance) | Out-Null Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "resourcePoolId" -xmlElementText $ResPoolId Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "datastoreId" -xmlElementText $datastore.extensiondata.moref.value if ( $EnableHA ) { [System.XML.XMLElement]$xmlAppliance = $XMLDoc.CreateElement("appliance") - $xmlAppliances.appendChild($xmlAppliance) | out-null + $xmlAppliances.appendChild($xmlAppliance) | Out-Null Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "resourcePoolId" -xmlElementText $ResPoolId Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "datastoreId" -xmlElementText $HAdatastore.extensiondata.moref.value } [System.XML.XMLElement]$xmlVnics = $XMLDoc.CreateElement("interfaces") - $xmlRoot.appendChild($xmlVnics) | out-null + $xmlRoot.appendChild($xmlVnics) | Out-Null foreach ( $VnicSpec in $Interface ) { $import = $xmlDoc.ImportNode(($VnicSpec), $true) - $xmlVnics.AppendChild($import) | out-null + $xmlVnics.AppendChild($import) | Out-Null } if ( ( $EnableLocalEgress ) -and ( $universal ) ) { @@ -11735,9 +11745,9 @@ function New-NsxLogicalRouter { $body = $xmlroot.OuterXml $URI = "/api/4.0/edges?isUniversal=$universal" - Write-Progress -activity "Creating Logical Router $Name" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - Write-Progress -activity "Creating Logical Router $Name" -completed + Write-Progress -Activity "Creating Logical Router $Name" + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating Logical Router $Name" -Completed $edgeId = $response.Headers.Location.split("/")[$response.Headers.Location.split("/").GetUpperBound(0)] if ( $EnableHA ) { @@ -11746,12 +11756,12 @@ function New-NsxLogicalRouter { Add-XmlElement -xmlRoot $xmlHA -xmlElementName "enabled" -xmlElementText "true" $body = $xmlHA.OuterXml $URI = "/api/4.0/edges/$edgeId/highavailability/config" - Write-Progress -activity "Enable HA on Logical Router $Name" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Enable HA on Logical Router $Name" -completed + Write-Progress -Activity "Enable HA on Logical Router $Name" + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Enable HA on Logical Router $Name" -Completed } - Get-NsxLogicalRouter -objectID $edgeId -connection $connection + Get-NsxLogicalRouter -objectId $edgeId -Connection $connection } end {} } @@ -11778,19 +11788,19 @@ function Remove-NsxLogicalRouter { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouter $_ })] - [System.Xml.XmlElement]$LogicalRouter, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouter $_ })] + [System.Xml.XmlElement]$LogicalRouter, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -11801,7 +11811,7 @@ function Remove-NsxLogicalRouter { process { if ( $confirm ) { - $message = "Logical Router removal is permanent." + $message = "Logical Router removal is permanent." $question = "Proceed with removal of Logical Router $($LogicalRouter.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -11813,9 +11823,9 @@ function Remove-NsxLogicalRouter { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/4.0/edges/$($LogicalRouter.Edgesummary.ObjectId)" - Write-Progress -activity "Remove Logical Router $($LogicalRouter.Name)" - invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection | out-null - write-progress -activity "Remove Logical Router $($LogicalRouter.Name)" -completed + Write-Progress -Activity "Remove Logical Router $($LogicalRouter.Name)" + Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection | Out-Null + Write-Progress -Activity "Remove Logical Router $($LogicalRouter.Name)" -Completed } } @@ -11842,39 +11852,39 @@ function Set-NsxLogicalRouterInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true)] - [ValidateSet ("internal","uplink")] - [string]$Type, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$ConnectedTo, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [ValidateRange(1,9128)] - [int]$MTU=1500, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Connected=$true, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true)] + [ValidateSet ("internal", "uplink")] + [string]$Type, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$ConnectedTo, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 9128)] + [int]$MTU = 1500, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Connected = $true, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -11883,7 +11893,7 @@ function Set-NsxLogicalRouterInterface { #Check if there is already configuration if ( $confirm ) { - $message = "Interface configuration will be overwritten." + $message = "Interface configuration will be overwritten." $question = "Proceed with reconfiguration for $($Interface.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -11898,32 +11908,32 @@ function Set-NsxLogicalRouterInterface { #generate the vnic XML $vNicSpecParams = @{ - Index = $Interface.index - Name = $name - Type = $type + Index = $Interface.index + Name = $name + Type = $type ConnectedTo = $connectedTo - MTU = $MTU - Connected = $connected + MTU = $MTU + Connected = $connected } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength",$SubnetPrefixLength) } - if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses",$SecondaryAddresses) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength", $SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses", $SecondaryAddresses) } $VnicSpec = New-NsxLogicalRouterInterfaceSpec @vNicSpecParams - write-debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | format-xml) " + Write-Debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | Format-XML) " #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlVnics = $XMLDoc.CreateElement("interfaces") $import = $xmlDoc.ImportNode(($VnicSpec), $true) - $xmlVnics.AppendChild($import) | out-null + $xmlVnics.AppendChild($import) | Out-Null # #Do the post $body = $xmlVnics.OuterXml $URI = "/api/4.0/edges/$($Interface.logicalRouterId)/interfaces/?action=patch" - Write-Progress -activity "Updating Logical Router interface configuration for interface $($Interface.Index)." - invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Updating Logical Router interface configuration for interface $($Interface.Index)." -completed + Write-Progress -Activity "Updating Logical Router interface configuration for interface $($Interface.Index)." + Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating Logical Router interface configuration for interface $($Interface.Index)." -Completed } @@ -11948,39 +11958,39 @@ function New-NsxLogicalRouterInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouter $_ })] - [System.Xml.XmlElement]$LogicalRouter, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true)] - [ValidateSet ("internal","uplink")] - [string]$Type, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$ConnectedTo, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [ValidateRange(1,9128)] - [int]$MTU=1500, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Connected=$true, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouter $_ })] + [System.Xml.XmlElement]$LogicalRouter, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true)] + [ValidateSet ("internal", "uplink")] + [string]$Type, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$ConnectedTo, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 9128)] + [int]$MTU = 1500, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Connected = $true, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -11988,31 +11998,31 @@ function New-NsxLogicalRouterInterface { #generate the vnic XML $vNicSpecParams = @{ - Name = $name - Type = $type + Name = $name + Type = $type ConnectedTo = $connectedTo - MTU = $MTU - Connected = $connected + MTU = $MTU + Connected = $connected } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength",$SubnetPrefixLength) } - if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses",$SecondaryAddresses) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength", $SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses", $SecondaryAddresses) } $VnicSpec = New-NsxLogicalRouterInterfaceSpec @vNicSpecParams - write-debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | format-xml) " + Write-Debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | Format-XML) " #Construct the XML [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlVnics = $XMLDoc.CreateElement("interfaces") $import = $xmlDoc.ImportNode(($VnicSpec), $true) - $xmlVnics.AppendChild($import) | out-null + $xmlVnics.AppendChild($import) | Out-Null # #Do the post $body = $xmlVnics.OuterXml $URI = "/api/4.0/edges/$($LogicalRouter.Id)/interfaces/?action=patch" - Write-Progress -activity "Creating Logical Router interface." - $response = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Creating Logical Router interface." -completed + Write-Progress -Activity "Creating Logical Router interface." + $response = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating Logical Router interface." -Completed $response.interfaces } @@ -12037,18 +12047,18 @@ function Remove-NsxLogicalRouterInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -12058,7 +12068,7 @@ function Remove-NsxLogicalRouterInterface { if ( $confirm ) { - $message = "Interface ($Interface.Name) will be deleted." + $message = "Interface ($Interface.Name) will be deleted." $question = "Proceed with deletion of interface $($Interface.index)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -12073,9 +12083,9 @@ function Remove-NsxLogicalRouterInterface { # #Do the delete $URI = "/api/4.0/edges/$($Interface.logicalRouterId)/interfaces/$($Interface.Index)" - Write-Progress -activity "Deleting interface $($Interface.Index) on logical router $($Interface.logicalRouterId)." - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-progress -activity "Deleting interface $($Interface.Index) on logical router $($Interface.logicalRouterId)." -completed + Write-Progress -Activity "Deleting interface $($Interface.Index) on logical router $($Interface.logicalRouterId)." + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Deleting interface $($Interface.Index) on logical router $($Interface.logicalRouterId)." -Completed } @@ -12103,22 +12113,22 @@ function Get-NsxLogicalRouterInterface { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouter $_ })] - [System.Xml.XmlElement]$LogicalRouter, - [Parameter (Mandatory=$False,ParameterSetName="Name",Position=1)] - [string]$Name, - [Parameter (Mandatory=$True,ParameterSetName="Index")] - [ValidateRange(1,1000)] - [int]$Index, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouter $_ })] + [System.Xml.XmlElement]$LogicalRouter, + [Parameter (Mandatory = $False, ParameterSetName = "Name", Position = 1)] + [string]$Name, + [Parameter (Mandatory = $True, ParameterSetName = "Index")] + [ValidateRange(1, 1000)] + [int]$Index, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -12128,10 +12138,10 @@ function Get-NsxLogicalRouterInterface { if ( -not ($PsBoundParameters.ContainsKey("Index") )) { #All Interfaces on LR $URI = "/api/4.0/edges/$($LogicalRouter.Id)/interfaces/" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'child::interfaces/interface') { + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'child::interfaces/interface') { if ( $PsBoundParameters.ContainsKey("name") ) { - $return = $response.interfaces.interface | where-object { $_.name -eq $name } + $return = $response.interfaces.interface | Where-Object { $_.name -eq $name } if ( $return ) { Add-XmlElement -xmlDoc ([system.xml.xmldocument]$return.OwnerDocument) -xmlRoot $return -xmlElementName "logicalRouterId" -xmlElementText $($LogicalRouter.Id) } @@ -12150,7 +12160,7 @@ function Get-NsxLogicalRouterInterface { #Just getting a single named Interface $URI = "/api/4.0/edges/$($LogicalRouter.Id)/interfaces/$Index" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { $return = $response.interface Add-XmlElement -xmlDoc ([system.xml.xmldocument]$return.OwnerDocument) -xmlRoot $return -xmlElementName "logicalRouterId" -xmlElementText $($LogicalRouter.Id) @@ -12184,20 +12194,20 @@ function Set-NsxLogicalRouter { #> [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - # Logical Router object as returned by Get-NsxLogicalRouter - [ValidateScript({ ValidateLogicalRouter $_ })] - [System.Xml.XmlElement]$LogicalRouter, - [Parameter (Mandatory=$False)] - # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + # Logical Router object as returned by Get-NsxLogicalRouter + [ValidateScript( { ValidateLogicalRouter $_ })] + [System.Xml.XmlElement]$LogicalRouter, + [Parameter (Mandatory = $False)] + # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -12210,16 +12220,16 @@ function Set-NsxLogicalRouter { $_LogicalRouter = $LogicalRouter.CloneNode($true) #Remove EdgeSummary... - $edgeSummary = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouter -Query 'descendant::edgeSummary') + $edgeSummary = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouter -query 'descendant::edgeSummary') if ( $edgeSummary ) { - $_LogicalRouter.RemoveChild($edgeSummary) | out-null + $_LogicalRouter.RemoveChild($edgeSummary) | Out-Null } $URI = "/api/4.0/edges/$($_LogicalRouter.Id)" $body = $_LogicalRouter.OuterXml if ( $confirm ) { - $message = "Logical Router update will modify existing Logical Router configuration." + $message = "Logical Router update will modify existing Logical Router configuration." $question = "Proceed with Update of Logical Router $($LogicalRouter.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -12229,10 +12239,10 @@ function Set-NsxLogicalRouter { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Logical Router $($LogicalRouter.Name)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Logical Router $($LogicalRouter.Name)" -completed - Get-NsxLogicalRouter -objectId $($LogicalRouter.Id) -connection $connection + Write-Progress -Activity "Update Logical Router $($LogicalRouter.Name)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Logical Router $($LogicalRouter.Name)" -Completed + Get-NsxLogicalRouter -objectId $($LogicalRouter.Id) -Connection $connection } } @@ -12254,16 +12264,16 @@ function AddNsxEdgeVnicAddressGroup { #ToDo - Implement IP address and netmask validation param ( - [Parameter (Mandatory=$true)] - [System.XML.XMLElement]$xmlAddressGroups, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [string[]]$SecondaryAddresses=@() + [Parameter (Mandatory = $true)] + [System.XML.XMLElement]$xmlAddressGroups, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [string[]]$SecondaryAddresses = @() ) @@ -12273,19 +12283,19 @@ function AddNsxEdgeVnicAddressGroup { [System.XML.XMLDocument]$xmlDoc = $xmlAddressGroups.OwnerDocument [System.XML.XMLElement]$xmlAddressGroup = $xmlDoc.CreateElement("addressGroup") - $xmlAddressGroups.appendChild($xmlAddressGroup) | out-null + $xmlAddressGroups.appendChild($xmlAddressGroup) | Out-Null Add-XmlElement -xmlRoot $xmlAddressGroup -xmlElementName "primaryAddress" -xmlElementText $PrimaryAddress Add-XmlElement -xmlRoot $xmlAddressGroup -xmlElementName "subnetPrefixLength" -xmlElementText $SubnetPrefixLength if ( $SecondaryAddresses ) { [System.XML.XMLElement]$xmlSecondaryAddresses = $XMLDoc.CreateElement("secondaryAddresses") - $xmlAddressGroup.appendChild($xmlSecondaryAddresses) | out-null + $xmlAddressGroup.appendChild($xmlSecondaryAddresses) | Out-Null foreach ($Address in $SecondaryAddresses) { Add-XmlElement -xmlRoot $xmlSecondaryAddresses -xmlElementName "ipAddress" -xmlElementText $Address } } } - end{} + end {} } ###End Private functions @@ -12310,14 +12320,14 @@ function New-NsxAddressSpec { #> param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [int]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [string[]]$SecondaryAddresses=@() + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [string[]]$SecondaryAddresses = @() ) @@ -12331,7 +12341,7 @@ function New-NsxAddressSpec { Add-XmlElement -xmlRoot $xmlAddressGroup -xmlElementName "subnetPrefixLength" -xmlElementText $SubnetPrefixLength.ToString() if ( $SecondaryAddresses ) { [System.XML.XMLElement]$xmlSecondaryAddresses = $XMLDoc.CreateElement("secondaryAddresses") - $xmlAddressGroup.appendChild($xmlSecondaryAddresses) | out-null + $xmlAddressGroup.appendChild($xmlSecondaryAddresses) | Out-Null foreach ($Address in $SecondaryAddresses) { Add-XmlElement -xmlRoot $xmlSecondaryAddresses -xmlElementName "ipAddress" -xmlElementText $Address } @@ -12340,7 +12350,7 @@ function New-NsxAddressSpec { $xmlAddressGroup } - end{} + end {} } function New-NsxEdgeInterfaceSpec { @@ -12370,34 +12380,34 @@ function New-NsxEdgeInterfaceSpec { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true)] - [ValidateRange(0,9)] - [int]$Index, - [Parameter (Mandatory=$false)] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateSet ("internal","uplink","trunk")] - [string]$Type, - [Parameter (Mandatory=$false)] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$ConnectedTo, - [Parameter (Mandatory=$false)] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false)] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [string[]]$SecondaryAddresses=@(), - [Parameter (Mandatory=$false)] - [ValidateRange(1,9128)] - [int]$MTU=1500, - [Parameter (Mandatory=$false)] - [switch]$EnableProxyArp=$false, - [Parameter (Mandatory=$false)] - [switch]$EnableSendICMPRedirects=$true, - [Parameter (Mandatory=$false)] - [switch]$Connected=$true + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true)] + [ValidateRange(0, 9)] + [int]$Index, + [Parameter (Mandatory = $false)] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateSet ("internal", "uplink", "trunk")] + [string]$Type, + [Parameter (Mandatory = $false)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$ConnectedTo, + [Parameter (Mandatory = $false)] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false)] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [string[]]$SecondaryAddresses = @(), + [Parameter (Mandatory = $false)] + [ValidateRange(1, 9128)] + [int]$MTU = 1500, + [Parameter (Mandatory = $false)] + [switch]$EnableProxyArp = $false, + [Parameter (Mandatory = $false)] + [switch]$EnableSendICMPRedirects = $true, + [Parameter (Mandatory = $false)] + [switch]$Connected = $true ) @@ -12415,7 +12425,7 @@ function New-NsxEdgeInterfaceSpec { } if (( $PsBoundParameters.ContainsKey("PrimaryAddress") -and ( -not $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) -or - (( -not $PsBoundParameters.ContainsKey("PrimaryAddress")) -and $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) { + (( -not $PsBoundParameters.ContainsKey("PrimaryAddress")) -and $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) { #Not allowed to have subnet without primary or vice versa. throw "Interfaces with a Primary address must also specify a prefix length and vice versa." @@ -12426,7 +12436,7 @@ function New-NsxEdgeInterfaceSpec { [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlVnic = $XMLDoc.CreateElement("vnic") - $xmlDoc.appendChild($xmlVnic) | out-null + $xmlDoc.appendChild($xmlVnic) | Out-Null if ( $PsBoundParameters.ContainsKey("Name")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "name" -xmlElementText $Name } if ( $PsBoundParameters.ContainsKey("Index")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "index" -xmlElementText $Index } @@ -12443,16 +12453,16 @@ function New-NsxEdgeInterfaceSpec { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "isConnected" -xmlElementText $Connected if ( $PsBoundParameters.ContainsKey("ConnectedTo")) { - switch ($ConnectedTo){ + switch ($ConnectedTo) { - { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } - { $_ -is [System.Xml.XmlElement]} { $PortGroupID = $_.objectId } + { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } + { $_ -is [System.Xml.XmlElement] } { $PortGroupID = $_.objectId } } Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "portgroupId" -xmlElementText $PortGroupID } [System.XML.XMLElement]$xmlAddressGroups = $XMLDoc.CreateElement("addressGroups") - $xmlVnic.appendChild($xmlAddressGroups) | out-null + $xmlVnic.appendChild($xmlAddressGroups) | Out-Null if ( $PsBoundParameters.ContainsKey("PrimaryAddress")) { #Only supporting one addressgroup - User must use New-NsxAddressSpec to specify multiple. @@ -12460,9 +12470,9 @@ function New-NsxEdgeInterfaceSpec { xmlAddressGroups = $xmlAddressGroups } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $AddressGroupParameters.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $AddressGroupParameters.Add("SubnetPrefixLength",$SubnetPrefixLength) } - if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $AddressGroupParameters.Add("SecondaryAddresses",$SecondaryAddresses) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $AddressGroupParameters.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $AddressGroupParameters.Add("SubnetPrefixLength", $SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $AddressGroupParameters.Add("SecondaryAddresses", $SecondaryAddresses) } AddNsxEdgeVnicAddressGroup @AddressGroupParameters } @@ -12491,40 +12501,40 @@ function New-NsxEdgeSubInterfaceSpec { #> - [CmdLetBinding(DefaultParameterSetName="None")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true)] - [string]$Name, - [Parameter (Mandatory=$true)] - [ValidateRange(1,4094)] - [int]$TunnelId, - [Parameter (Mandatory=$false,ParameterSetName="Network")] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$Network, - [Parameter (Mandatory=$false,ParameterSetName="VLAN")] - [ValidateRange(0,4094)] - [int]$VLAN, - [Parameter (Mandatory=$false)] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false)] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [string[]]$SecondaryAddresses=@(), - [Parameter (Mandatory=$false)] - [ValidateRange(1,9128)] - [int]$MTU, - [Parameter (Mandatory=$false)] - [switch]$EnableSendICMPRedirects, - [Parameter (Mandatory=$false)] - [switch]$Connected=$true + [CmdLetBinding(DefaultParameterSetName = "None")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true)] + [string]$Name, + [Parameter (Mandatory = $true)] + [ValidateRange(1, 4094)] + [int]$TunnelId, + [Parameter (Mandatory = $false, ParameterSetName = "Network")] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$Network, + [Parameter (Mandatory = $false, ParameterSetName = "VLAN")] + [ValidateRange(0, 4094)] + [int]$VLAN, + [Parameter (Mandatory = $false)] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false)] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [string[]]$SecondaryAddresses = @(), + [Parameter (Mandatory = $false)] + [ValidateRange(1, 9128)] + [int]$MTU, + [Parameter (Mandatory = $false)] + [switch]$EnableSendICMPRedirects, + [Parameter (Mandatory = $false)] + [switch]$Connected = $true ) begin { if (( $PsBoundParameters.ContainsKey("PrimaryAddress") -and ( -not $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) -or - (( -not $PsBoundParameters.ContainsKey("PrimaryAddress")) -and $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) { + (( -not $PsBoundParameters.ContainsKey("PrimaryAddress")) -and $PsBoundParameters.ContainsKey("SubnetPrefixLength"))) { #Not allowed to have subnet without primary or vice versa. throw "Interfaces with a Primary address must also specify a prefix length and vice versa." @@ -12535,7 +12545,7 @@ function New-NsxEdgeSubInterfaceSpec { [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlVnic = $XMLDoc.CreateElement("subInterface") - $xmlDoc.appendChild($xmlVnic) | out-null + $xmlDoc.appendChild($xmlVnic) | Out-Null Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "tunnelId" -xmlElementText $TunnelId @@ -12544,10 +12554,10 @@ function New-NsxEdgeSubInterfaceSpec { if ( $PsBoundParameters.ContainsKey("MTU")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "mtu" -xmlElementText $MTU } if ( $PsBoundParameters.ContainsKey("EnableSendICMPRedirects")) { Add-XmlElement -xmlRoot $xmlVnic -xmlElementName "enableSendRedirects" -xmlElementText $EnableSendICMPRedirects } if ( $PsBoundParameters.ContainsKey("Network")) { - switch ($Network){ + switch ($Network) { - { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } - { $_ -is [System.Xml.XmlElement]} { $PortGroupID = $_.objectId } + { $_ -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop] } { $PortGroupID = $_.ExtensionData.MoRef.Value } + { $_ -is [System.Xml.XmlElement] } { $PortGroupID = $_.objectId } } #Even though the element name is logicalSwitchId, subinterfaces support VDPortGroup as well as Logical Switch. @@ -12562,14 +12572,14 @@ function New-NsxEdgeSubInterfaceSpec { if ( $PsBoundParameters.ContainsKey("PrimaryAddress")) { #For now, only supporting one addressgroup - will refactor later [System.XML.XMLElement]$xmlAddressGroups = $XMLDoc.CreateElement("addressGroups") - $xmlVnic.appendChild($xmlAddressGroups) | out-null + $xmlVnic.appendChild($xmlAddressGroups) | Out-Null $AddressGroupParameters = @{ xmlAddressGroups = $xmlAddressGroups } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $AddressGroupParameters.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $AddressGroupParameters.Add("SubnetPrefixLength",$SubnetPrefixLength) } - if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $AddressGroupParameters.Add("SecondaryAddresses",$SecondaryAddresses) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $AddressGroupParameters.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $AddressGroupParameters.Add("SubnetPrefixLength", $SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $AddressGroupParameters.Add("SecondaryAddresses", $SecondaryAddresses) } AddNsxEdgeVnicAddressGroup @AddressGroupParameters } @@ -12615,61 +12625,61 @@ function Set-NsxEdgeInterface { #> - [CmdLetBinding(DefaultParameterSetName="DirectAddress")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="AddressGroupSpec")] - [ValidateScript({ ValidateEdgeInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$true, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$true, ParameterSetName="AddressGroupSpec")] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$true, ParameterSetName="AddressGroupSpec")] - [ValidateSet ("internal","uplink","trunk")] - [string]$Type, - [Parameter (Mandatory=$true, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$true, ParameterSetName="AddressGroupSpec")] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$ConnectedTo, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [string[]]$SecondaryAddresses=@(), - [Parameter (Mandatory=$true, ParameterSetName="AddressGroupSpec")] - [ValidateScript({ ValidateAddressGroupSpec $_ })] - [System.Xml.XmlElement[]]$AddressSpec, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - [ValidateRange(1,9128)] - [int]$MTU=1500, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - [ValidateNotNullOrEmpty()] - [switch]$EnableProxyArp=$false, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - [ValidateNotNullOrEmpty()] - [switch]$EnableSendICMPRedirects=$true, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - [ValidateNotNullOrEmpty()] - [switch]$Connected=$true, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - [ValidateNotNullOrEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdLetBinding(DefaultParameterSetName = "DirectAddress")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateScript( { ValidateEdgeInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $true, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateSet ("internal", "uplink", "trunk")] + [string]$Type, + [Parameter (Mandatory = $true, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$ConnectedTo, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [string[]]$SecondaryAddresses = @(), + [Parameter (Mandatory = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateScript( { ValidateAddressGroupSpec $_ })] + [System.Xml.XmlElement[]]$AddressSpec, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + [ValidateRange(1, 9128)] + [int]$MTU = 1500, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + [ValidateNotNullOrEmpty()] + [switch]$EnableProxyArp = $false, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + [ValidateNotNullOrEmpty()] + [switch]$EnableSendICMPRedirects = $true, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + [ValidateNotNullOrEmpty()] + [switch]$Connected = $true, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + [ValidateNotNullOrEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -12678,9 +12688,9 @@ function Set-NsxEdgeInterface { #Check if there is already configuration if ( $confirm ) { - If ( ($Interface | get-member -memberType properties PortGroupID ) -or ( $Interface.addressGroups ) ) { + If ( ($Interface | Get-Member -MemberType properties PortGroupID ) -or ( $Interface.addressGroups ) ) { - $message = "Interface $($Interface.Name) appears to already be configured. Config will be overwritten." + $message = "Interface $($Interface.Name) appears to already be configured. Config will be overwritten." $question = "Proceed with reconfiguration for $($Interface.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -12696,45 +12706,45 @@ function Set-NsxEdgeInterface { #generate the vnic XML $vNicSpecParams = @{ - Index = $Interface.index - Name = $name - Type = $type - ConnectedTo = $connectedTo - MTU = $MTU - EnableProxyArp = $EnableProxyArp + Index = $Interface.index + Name = $name + Type = $type + ConnectedTo = $connectedTo + MTU = $MTU + EnableProxyArp = $EnableProxyArp EnableSendICMPRedirects = $EnableSendICMPRedirects - Connected = $connected + Connected = $connected } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength",$SubnetPrefixLength) } - if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses",$SecondaryAddresses) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength", $SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses", $SecondaryAddresses) } $VnicSpec = New-NsxEdgeInterfaceSpec @vNicSpecParams - write-debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | format-xml) " + Write-Debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | Format-XML) " #Construct the vnics XML Element [System.XML.XMLElement]$xmlVnics = $VnicSpec.OwnerDocument.CreateElement("vnics") - $xmlVnics.AppendChild($VnicSpec) | out-null + $xmlVnics.AppendChild($VnicSpec) | Out-Null #Import any user specified address groups. if ( $PsBoundParameters.ContainsKey('AddressSpec')) { - [System.Xml.XmlElement]$AddressGroups = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $VnicSpec -Query 'descendant::addressGroups') + [System.Xml.XmlElement]$AddressGroups = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $VnicSpec -query 'descendant::addressGroups') foreach ( $spec in $AddressSpec ) { $import = $VnicSpec.OwnerDocument.ImportNode(($spec), $true) - $AddressGroups.AppendChild($import) | out-null + $AddressGroups.AppendChild($import) | Out-Null } } # #Do the post $body = $xmlVnics.OuterXml $URI = "/api/4.0/edges/$($Interface.edgeId)/vnics/?action=patch" - Write-Progress -activity "Updating Edge Services Gateway interface configuration for interface $($Interface.Index)." - $null = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Updating Edge Services Gateway interface configuration for interface $($Interface.Index)." -completed + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for interface $($Interface.Index)." + $null = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for interface $($Interface.Index)." -Completed - write-debug "$($MyInvocation.MyCommand.Name) : Getting updated interface" - Get-NsxEdge -objectId $($Interface.edgeId) -connection $connection | Get-NsxEdgeInterface -index "$($Interface.Index)" -connection $connection + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting updated interface" + Get-NsxEdge -objectId $($Interface.edgeId) -Connection $connection | Get-NsxEdgeInterface -index "$($Interface.Index)" -connection $connection } end {} @@ -12765,18 +12775,18 @@ function Clear-NsxEdgeInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -12787,7 +12797,7 @@ function Clear-NsxEdgeInterface { if ( $confirm ) { - $message = "Interface $($Interface.Name) config will be cleared." + $message = "Interface $($Interface.Name) config will be cleared." $question = "Proceed with interface reconfiguration for interface $($interface.index)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -12802,9 +12812,9 @@ function Clear-NsxEdgeInterface { # #Do the delete $URI = "/api/4.0/edges/$($interface.edgeId)/vnics/$($interface.Index)" - Write-Progress -activity "Clearing Edge Services Gateway interface configuration for interface $($interface.Index)." - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-progress -activity "Clearing Edge Services Gateway interface configuration for interface $($interface.Index)." -completed + Write-Progress -Activity "Clearing Edge Services Gateway interface configuration for interface $($interface.Index)." + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Clearing Edge Services Gateway interface configuration for interface $($interface.Index)." -Completed } @@ -12841,22 +12851,22 @@ function Get-NsxEdgeInterface { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False,ParameterSetName="Name",Position=1)] - [string]$Name, - [Parameter (Mandatory=$True,ParameterSetName="Index")] - [ValidateRange(0,9)] - [int]$Index, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False, ParameterSetName = "Name", Position = 1)] + [string]$Name, + [Parameter (Mandatory = $True, ParameterSetName = "Index")] + [ValidateRange(0, 9)] + [int]$Index, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -12866,19 +12876,19 @@ function Get-NsxEdgeInterface { if ( -not ($PsBoundParameters.ContainsKey("Index") )) { #All interfaces on Edge $URI = "/api/4.0/edges/$($Edge.Id)/vnics/" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $PsBoundParameters.ContainsKey("name") ) { - write-debug "$($MyInvocation.MyCommand.Name) : Getting vNic by Name" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting vNic by Name" - $return = $response.vnics.vnic | where-object { $_.name -eq $name } + $return = $response.vnics.vnic | Where-Object { $_.name -eq $name } if ( $return ) { Add-XmlElement -xmlDoc ([system.xml.xmldocument]$return.OwnerDocument) -xmlRoot $return -xmlElementName "edgeId" -xmlElementText $($Edge.Id) } } else { - write-debug "$($MyInvocation.MyCommand.Name) : Getting all vNics" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting all vNics" $return = $response.vnics.vnic foreach ( $vnic in $return ) { @@ -12888,11 +12898,11 @@ function Get-NsxEdgeInterface { } else { - write-debug "$($MyInvocation.MyCommand.Name) : Getting vNic by Index" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting vNic by Index" #Just getting a single vNic by index $URI = "/api/4.0/edges/$($Edge.Id)/vnics/$Index" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $return = $response.vnic Add-XmlElement -xmlDoc ([system.xml.xmldocument]$return.OwnerDocument) -xmlRoot $return -xmlElementName "edgeId" -xmlElementText $($Edge.Id) } @@ -12935,45 +12945,45 @@ function New-NsxEdgeSubInterface { #> - [CmdLetBinding(DefaultParameterSetName="None")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$true)] - [ValidateRange(1,4094)] - [int]$TunnelId, - [Parameter (Mandatory=$false,ParameterSetName="Network")] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ })] - [object]$Network, - [Parameter (Mandatory=$false,ParameterSetName="VLAN")] - [ValidateRange(0,4094)] - [int]$VLAN, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false)] - [string[]]$SecondaryAddresses=@(), - [Parameter (Mandatory=$false)] - [ValidateRange(1,9128)] - [int]$MTU, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$EnableSendICMPRedirects, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$Connected=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdLetBinding(DefaultParameterSetName = "None")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $true)] + [ValidateRange(1, 4094)] + [int]$TunnelId, + [Parameter (Mandatory = $false, ParameterSetName = "Network")] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ })] + [object]$Network, + [Parameter (Mandatory = $false, ParameterSetName = "VLAN")] + [ValidateRange(0, 4094)] + [int]$VLAN, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false)] + [string[]]$SecondaryAddresses = @(), + [Parameter (Mandatory = $false)] + [ValidateRange(1, 9128)] + [int]$MTU, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$EnableSendICMPRedirects, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$Connected = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) #Validate interfaceindex is trunk @@ -12986,53 +12996,53 @@ function New-NsxEdgeSubInterface { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_Interface.edgeId - $NodetoRemove = $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Interface -Query 'descendant::edgeId')) - write-debug "Node to remove parent: $($nodetoremove.ParentNode | format-xml)" + $NodetoRemove = $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Interface -query 'descendant::edgeId')) + Write-Debug "Node to remove parent: $($nodetoremove.ParentNode | Format-XML)" - $_Interface.RemoveChild( $NodeToRemove ) | out-null + $_Interface.RemoveChild( $NodeToRemove ) | Out-Null #Get or create the subinterfaces node. [System.XML.XMLDocument]$xmlDoc = $_Interface.OwnerDocument - if ( $_Interface | get-member -memberType Properties -Name subInterfaces) { + if ( $_Interface | Get-Member -MemberType Properties -Name subInterfaces) { [System.XML.XMLElement]$xmlSubInterfaces = $_Interface.subInterfaces } else { [System.XML.XMLElement]$xmlSubInterfaces = $xmlDoc.CreateElement("subInterfaces") - $_Interface.AppendChild($xmlSubInterfaces) | out-null + $_Interface.AppendChild($xmlSubInterfaces) | Out-Null } #generate the vnic XML $vNicSpecParams = @{ - TunnelId = $TunnelId + TunnelId = $TunnelId Connected = $connected - Name = $Name + Name = $Name } switch ($psCmdlet.ParameterSetName) { - "Network" { if ( $PsBoundParameters.ContainsKey("Network" )) { $vNicSpecParams.Add("Network",$Network) } } - "VLAN" { if ( $PsBoundParameters.ContainsKey("VLAN" )) { $vNicSpecParams.Add("VLAN",$VLAN) } } + "Network" { if ( $PsBoundParameters.ContainsKey("Network" )) { $vNicSpecParams.Add("Network", $Network) } } + "VLAN" { if ( $PsBoundParameters.ContainsKey("VLAN" )) { $vNicSpecParams.Add("VLAN", $VLAN) } } "None" {} Default { throw "An invalid parameterset was found. This should never happen." } } - if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress",$PrimaryAddress) } - if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength",$SubnetPrefixLength) } - if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses",$SecondaryAddresses) } - if ( $PsBoundParameters.ContainsKey("MTU" )) { $vNicSpecParams.Add("MTU",$MTU) } - if ( $PsBoundParameters.ContainsKey("EnableSendICMPRedirects" )) { $vNicSpecParams.Add("EnableSendICMPRedirects",$EnableSendICMPRedirects) } + if ( $PsBoundParameters.ContainsKey("PrimaryAddress" )) { $vNicSpecParams.Add("PrimaryAddress", $PrimaryAddress) } + if ( $PsBoundParameters.ContainsKey("SubnetPrefixLength" )) { $vNicSpecParams.Add("SubnetPrefixLength", $SubnetPrefixLength) } + if ( $PsBoundParameters.ContainsKey("SecondaryAddresses" )) { $vNicSpecParams.Add("SecondaryAddresses", $SecondaryAddresses) } + if ( $PsBoundParameters.ContainsKey("MTU" )) { $vNicSpecParams.Add("MTU", $MTU) } + if ( $PsBoundParameters.ContainsKey("EnableSendICMPRedirects" )) { $vNicSpecParams.Add("EnableSendICMPRedirects", $EnableSendICMPRedirects) } $VnicSpec = New-NsxEdgeSubInterfaceSpec @vNicSpecParams - write-debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | format-xml) " + Write-Debug "$($MyInvocation.MyCommand.Name) : vNic Spec is $($VnicSpec.outerxml | Format-XML) " $import = $xmlDoc.ImportNode(($VnicSpec), $true) - $xmlSubInterfaces.AppendChild($import) | out-null + $xmlSubInterfaces.AppendChild($import) | Out-Null # #Do the post $body = $_Interface.OuterXml $URI = "/api/4.0/edges/$($EdgeId)/vnics/$($_Interface.Index)" - Write-Progress -activity "Updating Edge Services Gateway interface configuration for $($_Interface.Name)." - invoke-nsxrestmethod -method "put" -uri $URI -body $body -connection $connection - Write-progress -activity "Updating Edge Services Gateway interface configuration for $($_Interface.Name)." -completed + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for $($_Interface.Name)." + Invoke-NsxRestMethod -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for $($_Interface.Name)." -Completed } function Remove-NsxEdgeSubInterface { @@ -13061,19 +13071,19 @@ function Remove-NsxEdgeSubInterface { #> - [CmdLetBinding(DefaultParameterSetName="None")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [CmdLetBinding(DefaultParameterSetName = "None")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSubInterface $_ })] - [System.Xml.XmlElement]$Subinterface, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSubInterface $_ })] + [System.Xml.XmlElement]$Subinterface, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -13082,7 +13092,7 @@ function Remove-NsxEdgeSubInterface { Process { if ( $confirm ) { - $message = "Interface $($Subinterface.Name) will be removed." + $message = "Interface $($Subinterface.Name) will be removed." $question = "Proceed with interface reconfiguration for interface $($Subinterface.index)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -13096,19 +13106,19 @@ function Remove-NsxEdgeSubInterface { } #Get the vnic xml - $ParentVnic = $(Get-NsxEdge -connection $connection -objectId $SubInterface.edgeId).vnics.vnic | where-object { $_.index -eq $subInterface.vnicId } + $ParentVnic = $(Get-NsxEdge -Connection $connection -objectId $SubInterface.edgeId).vnics.vnic | Where-Object { $_.index -eq $subInterface.vnicId } #Remove the node using xpath query. - $NodeToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ParentVnic.subInterfaces -Query "descendant::subInterface[index=$($subInterface.Index)]") - write-debug "$($MyInvocation.MyCommand.Name) : XPath query for node to delete returned $($NodetoRemove.OuterXml | format-xml)" - $ParentVnic.Subinterfaces.RemoveChild($NodeToRemove) | out-null + $NodeToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ParentVnic.subInterfaces -query "descendant::subInterface[index=$($subInterface.Index)]") + Write-Debug "$($MyInvocation.MyCommand.Name) : XPath query for node to delete returned $($NodetoRemove.OuterXml | Format-XML)" + $ParentVnic.Subinterfaces.RemoveChild($NodeToRemove) | Out-Null #Put the modified VNIC xml $body = $ParentVnic.OuterXml $URI = "/api/4.0/edges/$($SubInterface.edgeId)/vnics/$($ParentVnic.Index)" - Write-Progress -activity "Updating Edge Services Gateway interface configuration for interface $($ParentVnic.Name)." - invoke-nsxrestmethod -method "put" -uri $URI -body $body -connection $connection - Write-progress -activity "Updating Edge Services Gateway interface configuration for interface $($ParentVnic.Name)." -completed + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for interface $($ParentVnic.Name)." + Invoke-NsxRestMethod -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for interface $($ParentVnic.Name)." -Completed } End {} @@ -13138,18 +13148,18 @@ function Get-NsxEdgeSubInterface { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$False,ParameterSetName="Name",Position=1)] - [string]$Name, - [Parameter (Mandatory=$True,ParameterSetName="Index")] - [ValidateRange(10,200)] - [int]$Index + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $False, ParameterSetName = "Name", Position = 1)] + [string]$Name, + [Parameter (Mandatory = $True, ParameterSetName = "Index")] + [ValidateRange(10, 200)] + [int]$Index ) begin {} @@ -13157,11 +13167,11 @@ function Get-NsxEdgeSubInterface { process { #Not throwing error if no subinterfaces defined. - If ( $interface | get-member -name subInterfaces -Membertype Properties ) { + If ( $interface | Get-Member -Name subInterfaces -MemberType Properties ) { if ($PsBoundParameters.ContainsKey("Index")) { - $subint = $Interface.subInterfaces.subinterface | where-object { $_.index -eq $Index } + $subint = $Interface.subInterfaces.subinterface | Where-Object { $_.index -eq $Index } if ( $subint ) { $_subint = $subint.CloneNode($true) @@ -13172,7 +13182,7 @@ function Get-NsxEdgeSubInterface { } elseif ( $PsBoundParameters.ContainsKey("name")) { - $subint = $Interface.subInterfaces.subinterface | where-object { $_.name -eq $name } + $subint = $Interface.subInterfaces.subinterface | Where-Object { $_.name -eq $name } if ($subint) { $_subint = $subint.CloneNode($true) Add-XmlElement -xmlDoc ([system.xml.xmldocument]$Interface.OwnerDocument) -xmlRoot $_subint -xmlElementName "edgeId" -xmlElementText $($Interface.edgeId) @@ -13223,12 +13233,12 @@ function Get-NsxEdgeInterfaceAddress { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$PrimaryAddress + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$PrimaryAddress ) @@ -13238,14 +13248,14 @@ function Get-NsxEdgeInterfaceAddress { process { $_Interface = ($Interface.CloneNode($True)) - [System.Xml.XmlElement]$AddressGroups = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Interface -Query 'descendant::addressGroups') + [System.Xml.XmlElement]$AddressGroups = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Interface -query 'descendant::addressGroups') #Need to use an xpath query here, as dot notation will throw in strict mode if there is no childnode. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $AddressGroups -Query 'descendant::addressGroup')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $AddressGroups -query 'descendant::addressGroup')) { $GroupCollection = $AddressGroups.addressGroup if ( $PsBoundParameters.ContainsKey('PrimaryAddress')) { - $GroupCollection = $GroupCollection | where-object { $_.primaryAddress -eq $PrimaryAddress } + $GroupCollection = $GroupCollection | Where-Object { $_.primaryAddress -eq $PrimaryAddress } } foreach ( $AddressGroup in $GroupCollection ) { @@ -13292,26 +13302,26 @@ function Add-NsxEdgeInterfaceAddress { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="AddressGroupSpec")] - [ValidateScript({ ValidateEdgeInterface $_ })] - [System.Xml.XmlElement]$Interface, - [Parameter (Mandatory=$true, ParameterSetName="DirectAddress")] - [ValidateNotNullOrEmpty()] - [string]$PrimaryAddress, - [Parameter (Mandatory=$true, ParameterSetName="DirectAddress")] - [ValidateNotNullOrEmpty()] - [string]$SubnetPrefixLength, - [Parameter (Mandatory=$false, ParameterSetName="DirectAddress")] - [string[]]$SecondaryAddresses=@(), - [Parameter (Mandatory=$true, ParameterSetName="AddressGroupSpec")] - [ValidateScript({ ValidateAddressGroupSpec $_ })] - [System.Xml.XmlElement[]]$AddressSpec, - [Parameter (Mandatory=$False, ParameterSetName="DirectAddress")] - [Parameter (Mandatory=$false, ParameterSetName="AddressGroupSpec")] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateScript( { ValidateEdgeInterface $_ })] + [System.Xml.XmlElement]$Interface, + [Parameter (Mandatory = $true, ParameterSetName = "DirectAddress")] + [ValidateNotNullOrEmpty()] + [string]$PrimaryAddress, + [Parameter (Mandatory = $true, ParameterSetName = "DirectAddress")] + [ValidateNotNullOrEmpty()] + [string]$SubnetPrefixLength, + [Parameter (Mandatory = $false, ParameterSetName = "DirectAddress")] + [string[]]$SecondaryAddresses = @(), + [Parameter (Mandatory = $true, ParameterSetName = "AddressGroupSpec")] + [ValidateScript( { ValidateAddressGroupSpec $_ })] + [System.Xml.XmlElement[]]$AddressSpec, + [Parameter (Mandatory = $False, ParameterSetName = "DirectAddress")] + [Parameter (Mandatory = $false, ParameterSetName = "AddressGroupSpec")] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -13321,10 +13331,10 @@ function Add-NsxEdgeInterfaceAddress { #Store the edgeId and remove it from the XML as we need to put it... $edgeId = $_Interface.edgeId - $NodetoRemove = $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Interface -Query 'descendant::edgeId')) - $_Interface.RemoveChild( $NodeToRemove ) | out-null + $NodetoRemove = $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Interface -query 'descendant::edgeId')) + $_Interface.RemoveChild( $NodeToRemove ) | Out-Null - [System.Xml.XmlElement]$AddressGroups = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Interface -Query 'descendant::addressGroups') + [System.Xml.XmlElement]$AddressGroups = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Interface -query 'descendant::addressGroups') if ( $PSCmdlet.ParameterSetName -eq "DirectAddress") { if ( $PsBoundParameters.ContainsKey('SecondaryAddresses')) { @@ -13339,19 +13349,19 @@ function Add-NsxEdgeInterfaceAddress { #Import any user specified address groups. foreach ( $spec in $AddressSpec ) { $import = $_Interface.OwnerDocument.ImportNode(($spec), $true) - $AddressGroups.AppendChild($import) | out-null + $AddressGroups.AppendChild($import) | Out-Null } } #Do the post $body = $_Interface.OuterXml $URI = "/api/4.0/edges/$($edgeId)/vnics/$($_Interface.Index)" - Write-Progress -activity "Updating Edge Services Gateway interface configuration for interface $($_Interface.Index)." - $null = invoke-nsxrestmethod -method "put" -uri $URI -body $body -connection $connection - Write-progress -activity "Updating Edge Services Gateway interface configuration for interface $($_Interface.Index)." -completed + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for interface $($_Interface.Index)." + $null = Invoke-NsxRestMethod -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating Edge Services Gateway interface configuration for interface $($_Interface.Index)." -Completed - write-debug "$($MyInvocation.MyCommand.Name) : Getting updated interface" - Get-NsxEdge -objectId $($edgeId) -connection $connection | Get-NsxEdgeInterface -index "$($_Interface.Index)" -connection $connection + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting updated interface" + Get-NsxEdge -objectId $($edgeId) -Connection $connection | Get-NsxEdgeInterface -index "$($_Interface.Index)" -connection $connection } end {} @@ -13379,19 +13389,19 @@ function Remove-NsxEdgeInterfaceAddress { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeInterfaceAddress $_ })] - [System.Xml.XmlElement]$InterfaceAddress, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeInterfaceAddress $_ })] + [System.Xml.XmlElement]$InterfaceAddress, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -13402,28 +13412,28 @@ function Remove-NsxEdgeInterfaceAddress { #Get the routing config for our Edge $edgeId = $InterfaceAddress.edgeId $InterfaceIndex = $InterfaceAddress.interfaceIndex - $Edge = Get-NsxEdge -objectId $edgeId -connection $connection + $Edge = Get-NsxEdge -objectId $edgeId -Connection $connection $Interface = $Edge | Get-NsxEdgeInterface -index $InterfaceIndex -connection $connection - if ( -not $Interface ) { Throw "Interface index $InterfaceIndex was not found on edge $edgeId."} + if ( -not $Interface ) { Throw "Interface index $InterfaceIndex was not found on edge $edgeId." } #Remove the edgeId and interfaceIndex elements from the XML as we need to post it... - $Interface.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Interface -Query 'descendant::edgeId')) ) | out-null + $Interface.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Interface -query 'descendant::edgeId')) ) | Out-Null #Need to do an xpath query here to query for an address that matches the one passed in. $xpathQuery = "//addressGroups/addressGroup[primaryAddress=`"$($InterfaceAddress.primaryAddress)`"]" - write-debug "$($MyInvocation.MyCommand.Name) : XPath query for addressgroup nodes to remove is: $xpathQuery" - $addressGroupToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Interface -Query $xpathQuery) + Write-Debug "$($MyInvocation.MyCommand.Name) : XPath query for addressgroup nodes to remove is: $xpathQuery" + $addressGroupToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Interface -query $xpathQuery) if ( $addressGroupToRemove ) { - write-debug "$($MyInvocation.MyCommand.Name) : addressGroupToRemove Element is: `n $($addressGroupToRemove.OuterXml | format-xml) " + Write-Debug "$($MyInvocation.MyCommand.Name) : addressGroupToRemove Element is: `n $($addressGroupToRemove.OuterXml | Format-XML) " $Interface.AddressGroups.RemoveChild($addressGroupToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/vnics/$InterfaceIndex" $body = $Interface.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -13433,9 +13443,9 @@ function Remove-NsxEdgeInterfaceAddress { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -13467,17 +13477,17 @@ function Get-NsxEdge { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - [string]$objectId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -13486,44 +13496,44 @@ function Get-NsxEdge { "Name" { $URI = "/api/4.0/edges?pageSize=$pagesize&startIndex=00" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection #Edge summary XML is returned as paged data, means we have to handle it. #Then we have to query for full information on a per edge basis. $edgesummaries = @() $edges = @() - $itemIndex = 0 + $itemIndex = 0 $startingIndex = 0 $pagingInfo = $response.pagedEdgeList.edgePage.pagingInfo if ( [int]$paginginfo.totalCount -ne 0 ) { - write-debug "$($MyInvocation.MyCommand.Name) : ESG count non zero" + Write-Debug "$($MyInvocation.MyCommand.Name) : ESG count non zero" do { - write-debug "$($MyInvocation.MyCommand.Name) : In paging loop. PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : In paging loop. PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" while (($itemindex -lt ([int]$paginginfo.pagesize + $startingIndex)) -and ($itemIndex -lt [int]$paginginfo.totalCount )) { - write-debug "$($MyInvocation.MyCommand.Name) : In Item Processing Loop: ItemIndex: $itemIndex" - write-debug "$($MyInvocation.MyCommand.Name) : $(@($response.pagedEdgeList.edgePage.edgeSummary)[($itemIndex - $startingIndex)].objectId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : In Item Processing Loop: ItemIndex: $itemIndex" + Write-Debug "$($MyInvocation.MyCommand.Name) : $(@($response.pagedEdgeList.edgePage.edgeSummary)[($itemIndex - $startingIndex)].objectId)" #Need to wrap the edgesummary prop of the datapage in case we get exactly 1 item - #which powershell annoyingly unwraps to a single xml element rather than an array... $edgesummaries += @($response.pagedEdgeList.edgePage.edgeSummary)[($itemIndex - $startingIndex)] $itemIndex += 1 } - write-debug "$($MyInvocation.MyCommand.Name) : Out of item processing - PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Out of item processing - PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" if ( [int]$paginginfo.totalcount -gt $itemIndex) { - write-debug "$($MyInvocation.MyCommand.Name) : PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" + Write-Debug "$($MyInvocation.MyCommand.Name) : PagingInfo: PageSize: $($pagingInfo.PageSize), StartIndex: $($paginginfo.startIndex), TotalCount: $($paginginfo.totalcount)" $startingIndex += $pagesize $URI = "/api/4.0/edges?pageSize=$pagesize&startIndex=$startingIndex" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $pagingInfo = $response.pagedEdgeList.edgePage.pagingInfo } } until ( [int]$paginginfo.totalcount -le $itemIndex ) - write-debug "$($MyInvocation.MyCommand.Name) : Completed page processing: ItemIndex: $itemIndex" + Write-Debug "$($MyInvocation.MyCommand.Name) : Completed page processing: ItemIndex: $itemIndex" } #What we got here is...failure to communicate! In order to get full detail, we have to requery for each edgeid. @@ -13533,18 +13543,19 @@ function Get-NsxEdge { foreach ($edgesummary in $edgesummaries) { $URI = "/api/4.0/edges/$($edgesummary.objectID)" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $import = $response.edge.ownerDocument.ImportNode($edgesummary, $true) - $response.edge.appendChild($import) | out-null + $response.edge.appendChild($import) | Out-Null $edges += $response.edge } if ( $name ) { - $edges | where-object { $_.Type -eq 'gatewayServices' } | where-object { $_.name -eq $name } + $edges | Where-Object { $_.Type -eq 'gatewayServices' } | Where-Object { $_.name -eq $name } - } else { - $edges | where-object { $_.Type -eq 'gatewayServices' } + } + else { + $edges | Where-Object { $_.Type -eq 'gatewayServices' } } @@ -13553,12 +13564,12 @@ function Get-NsxEdge { "objectId" { $URI = "/api/4.0/edges/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $edge = $response.edge $URI = "/api/4.0/edges/$objectId/summary" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $import = $edge.ownerDocument.ImportNode($($response.edgeSummary), $true) - $edge.AppendChild($import) | out-null + $edge.AppendChild($import) | Out-Null $edge } @@ -13602,106 +13613,110 @@ function New-NsxEdge { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Unable to remove without breaking backward compatibilty. - param ( - [Parameter (Mandatory=$true)] - #Name of the edge appliance. - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true,ParameterSetName="ResourcePool")] - #Resource pool into which to deploy the Edge. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, - [Parameter (Mandatory=$true,ParameterSetName="Cluster")] - #DRS Cluster into which to deploy the Edge. - [ValidateScript({ - if ( $_ -eq $null ) { throw "Must specify Cluster."} - if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled."} + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Unable to remove without breaking backward compatibilty. + param ( + [Parameter (Mandatory = $true)] + #Name of the edge appliance. + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "ResourcePool")] + #Resource pool into which to deploy the Edge. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, + [Parameter (Mandatory = $true, ParameterSetName = "Cluster")] + #DRS Cluster into which to deploy the Edge. + [ValidateScript( { + if ( $_ -eq $null ) { throw "Must specify Cluster." } + if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled." } $true })] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$true)] - #Datastore onto which to deploy the edge appliance (If HA is enabled, use -HADatastore to specify an alternate location if desired.) - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, - [Parameter (Mandatory=$false)] - #Cli account username. - [ValidateNotNullOrEmpty()] - [String]$Username="admin", - [Parameter (Mandatory=$false)] - #CLI account password - [ValidateNotNullOrEmpty()] - [String]$Password, - [Parameter (Mandatory=$false)] - #Datastore onto which to deploy the HA edge appliance (Best practice is to use an alternative datastore/array to the first edge appliance in a HA pair. Defaults to the same datastore as the first appliance.) - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$HADatastore=$datastore, - [Parameter (Mandatory=$false)] - #Formfactor for the deploye dedge appliance. - [ValidateSet ("compact","large","xlarge","quadlarge")] - [string]$FormFactor="compact", - [Parameter (Mandatory=$false)] - #VI folder into which to place the edge in the VMs and Templates inventory. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.FolderInterop]$VMFolder, - [Parameter (Mandatory=$false)] - #Optional tenant string. - [ValidateNotNullOrEmpty()] - [String]$Tenant, - [Parameter (Mandatory=$false)] - #DNS hostname to configure on the edge appliance. Defaults to the edge name. - [ValidateNotNullOrEmpty()] - [String]$Hostname=$Name, - [Parameter (Mandatory=$false)] - #Enable SSH - [ValidateNotNullOrEmpty()] - [switch]$EnableSSH=$false, - [Parameter (Mandatory=$false)] - #Enable autogeneration of edge firewall rules for enabled services. Defaults to $true - [ValidateNotNullOrEmpty()] - [switch]$AutoGenerateRules=$true, - [Parameter (Mandatory=$false)] - #Enable edge firewall. Defaults to $true. - [switch]$FwEnabled=$true, - [Parameter (Mandatory=$false)] - #Set default firewall rule to allow. Defaults to $false. - [switch]$FwDefaultPolicyAllow=$false, - [Parameter (Mandatory=$false)] - #Enable Firewall Logging. Defaults to $true. - [switch]$FwLoggingEnabled=$true, - [Parameter (Mandatory=$false)] - #Enable HA on the deployed Edge. Defaults to $false. - [ValidateNotNullOrEmpty()] - [switch]$EnableHa=$false, - [Parameter (Mandatory=$false)] - #Configure the Edge Appliance Dead Time. - [ValidateRange(3,900)] - [int]$HaDeadTime, - [Parameter (Mandatory=$false)] - #Configure the vNIC index used to send HA heartbeats. - [ValidateRange(0,9)] - [int]$HaVnic, - [Parameter (Mandatory=$false)] - #Enable syslog. Defaults to $false. - [switch]$EnableSyslog=$false, - [Parameter (Mandatory=$false)] - #Configure the syslog server. - [ValidateNotNullOrEmpty()] - [string[]]$SyslogServer, - [Parameter (Mandatory=$false)] - #Configure the syslog protocol. - [ValidateSet("udp","tcp",IgnoreCase=$true)] - [string]$SyslogProtocol, - [Parameter (Mandatory=$true)] - #Define the Edge Interface configuration. Specify a collection of one or more interface specs as created by New-NsxEdgeInterfaceSpec. - [ValidateScript({ ValidateEdgeInterfaceSpec $_ })] - [System.Xml.XmlElement[]]$Interface, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $true)] + #Datastore onto which to deploy the edge appliance (If HA is enabled, use -HADatastore to specify an alternate location if desired.) + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, + [Parameter (Mandatory = $false)] + #Cli account username. + [ValidateNotNullOrEmpty()] + [String]$Username = "admin", + [Parameter (Mandatory = $false)] + #CLI account password + [ValidateNotNullOrEmpty()] + [String]$Password, + [Parameter (Mandatory = $false)] + #Datastore onto which to deploy the HA edge appliance (Best practice is to use an alternative datastore/array to the first edge appliance in a HA pair. Defaults to the same datastore as the first appliance.) + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$HADatastore = $datastore, + [Parameter (Mandatory = $false)] + #Formfactor for the deploye dedge appliance. + [ValidateSet ("compact", "large", "xlarge", "quadlarge")] + [string]$FormFactor = "compact", + [Parameter (Mandatory = $false)] + #VI folder into which to place the edge in the VMs and Templates inventory. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.FolderInterop]$VMFolder, + [Parameter (Mandatory = $false)] + #Optional tenant string. + [ValidateNotNullOrEmpty()] + [String]$Tenant, + [Parameter (Mandatory = $false)] + #DNS hostname to configure on the edge appliance. Defaults to the edge name. + [ValidateNotNullOrEmpty()] + [String]$Hostname = $Name, + [Parameter (Mandatory = $false)] + #Enable SSH + [ValidateNotNullOrEmpty()] + [switch]$EnableSSH = $false, + [Parameter (Mandatory = $false)] + #Enable FIPs mode + [ValidateNotNullOrEmpty()] + [switch]$EnableFIPS = $false, + [Parameter (Mandatory = $false)] + #Enable autogeneration of edge firewall rules for enabled services. Defaults to $true + [ValidateNotNullOrEmpty()] + [switch]$AutoGenerateRules = $true, + [Parameter (Mandatory = $false)] + #Enable edge firewall. Defaults to $true. + [switch]$FwEnabled = $true, + [Parameter (Mandatory = $false)] + #Set default firewall rule to allow. Defaults to $false. + [switch]$FwDefaultPolicyAllow = $false, + [Parameter (Mandatory = $false)] + #Enable Firewall Logging. Defaults to $true. + [switch]$FwLoggingEnabled = $true, + [Parameter (Mandatory = $false)] + #Enable HA on the deployed Edge. Defaults to $false. + [ValidateNotNullOrEmpty()] + [switch]$EnableHa = $false, + [Parameter (Mandatory = $false)] + #Configure the Edge Appliance Dead Time. + [ValidateRange(3, 900)] + [int]$HaDeadTime, + [Parameter (Mandatory = $false)] + #Configure the vNIC index used to send HA heartbeats. + [ValidateRange(0, 9)] + [int]$HaVnic, + [Parameter (Mandatory = $false)] + #Enable syslog. Defaults to $false. + [switch]$EnableSyslog = $false, + [Parameter (Mandatory = $false)] + #Configure the syslog server. + [ValidateNotNullOrEmpty()] + [string[]]$SyslogServer, + [Parameter (Mandatory = $false)] + #Configure the syslog protocol. + [ValidateSet("udp", "tcp", IgnoreCase = $true)] + [string]$SyslogProtocol, + [Parameter (Mandatory = $true)] + #Define the Edge Interface configuration. Specify a collection of one or more interface specs as created by New-NsxEdgeInterfaceSpec. + [ValidateScript( { ValidateEdgeInterfaceSpec $_ })] + [System.Xml.XmlElement[]]$Interface, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -13710,10 +13725,15 @@ function New-NsxEdge { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("edge") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "fqdn" -xmlElementText $Hostname + + #Enable FIPs mode + if ( $EnableFIPS ) { + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "enableFips" -xmlElementText "true" + } Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "type" -xmlElementText "gatewayServices" if ($PSBoundParameters.ContainsKey("Tenant")) { @@ -13722,37 +13742,37 @@ function New-NsxEdge { #Appliances element [System.XML.XMLElement]$xmlAppliances = $XMLDoc.CreateElement("appliances") - $xmlRoot.appendChild($xmlAppliances) | out-null + $xmlRoot.appendChild($xmlAppliances) | Out-Null - switch ($psCmdlet.ParameterSetName){ - "Cluster" { $ResPoolId = $($cluster | get-resourcepool | where-object { $_.parent.id -eq $cluster.id }).extensiondata.moref.value } - "ResourcePool" { $ResPoolId = $ResourcePool.extensiondata.moref.value } + switch ($psCmdlet.ParameterSetName) { + "Cluster" { $ResPoolId = $($cluster | Get-ResourcePool | Where-Object { $_.parent.id -eq $cluster.id }).extensiondata.moref.value } + "ResourcePool" { $ResPoolId = $ResourcePool.extensiondata.moref.value } } Add-XmlElement -xmlRoot $xmlAppliances -xmlElementName "applianceSize" -xmlElementText $FormFactor [System.XML.XMLElement]$xmlAppliance = $XMLDoc.CreateElement("appliance") - $xmlAppliances.appendChild($xmlAppliance) | out-null + $xmlAppliances.appendChild($xmlAppliance) | Out-Null Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "resourcePoolId" -xmlElementText $ResPoolId Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "datastoreId" -xmlElementText $datastore.extensiondata.moref.value - if ( $VMFolder ) { Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "vmFolderId" -xmlElementText $VMFolder.extensiondata.moref.value} + if ( $VMFolder ) { Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "vmFolderId" -xmlElementText $VMFolder.extensiondata.moref.value } #Create the features element. [System.XML.XMLElement]$xmlFeatures = $XMLDoc.CreateElement("features") - $xmlRoot.appendChild($xmlFeatures) | out-null + $xmlRoot.appendChild($xmlFeatures) | Out-Null if ( $EnableHA ) { #Define the HA appliance [System.XML.XMLElement]$xmlAppliance = $XMLDoc.CreateElement("appliance") - $xmlAppliances.appendChild($xmlAppliance) | out-null + $xmlAppliances.appendChild($xmlAppliance) | Out-Null Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "resourcePoolId" -xmlElementText $ResPoolId Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "datastoreId" -xmlElementText $HAdatastore.extensiondata.moref.value - if ( $VMFolder ) { Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "vmFolderId" -xmlElementText $VMFolder.extensiondata.moref.value} + if ( $VMFolder ) { Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "vmFolderId" -xmlElementText $VMFolder.extensiondata.moref.value } #configure HA [System.XML.XMLElement]$xmlHA = $XMLDoc.CreateElement("highAvailability") - $xmlFeatures.appendChild($xmlHA) | out-null + $xmlFeatures.appendChild($xmlHA) | Out-Null Add-XmlElement -xmlRoot $xmlHA -xmlElementName "enabled" -xmlElementText "true" if ( $PsBoundParameters.containsKey('HaDeadTime')) { @@ -13766,7 +13786,7 @@ function New-NsxEdge { #Create the syslog element [System.XML.XMLElement]$xmlSyslog = $XMLDoc.CreateElement("syslog") - $xmlFeatures.appendChild($xmlSyslog) | out-null + $xmlFeatures.appendChild($xmlSyslog) | Out-Null Add-XmlElement -xmlRoot $xmlSyslog -xmlElementName "enabled" -xmlElementText $EnableSyslog.ToString().ToLower() if ( $PsBoundParameters.containsKey('SyslogProtocol')) { @@ -13775,7 +13795,7 @@ function New-NsxEdge { if ( $PsBoundParameters.containsKey('SyslogServer')) { [System.XML.XMLElement]$xmlServerAddresses = $XMLDoc.CreateElement("serverAddresses") - $xmlSyslog.appendChild($xmlServerAddresses) | out-null + $xmlSyslog.appendChild($xmlServerAddresses) | Out-Null foreach ( $server in $SyslogServer ) { Add-XmlElement -xmlRoot $xmlServerAddresses -xmlElementName "ipAddress" -xmlElementText $server.ToString() } @@ -13783,11 +13803,11 @@ function New-NsxEdge { #Create the fw element [System.XML.XMLElement]$xmlFirewall = $XMLDoc.CreateElement("firewall") - $xmlFeatures.appendChild($xmlFirewall) | out-null + $xmlFeatures.appendChild($xmlFirewall) | Out-Null Add-XmlElement -xmlRoot $xmlFirewall -xmlElementName "enabled" -xmlElementText $FwEnabled.ToString().ToLower() [System.XML.XMLElement]$xmlDefaultPolicy = $XMLDoc.CreateElement("defaultPolicy") - $xmlFirewall.appendChild($xmlDefaultPolicy) | out-null + $xmlFirewall.appendChild($xmlDefaultPolicy) | Out-Null Add-XmlElement -xmlRoot $xmlDefaultPolicy -xmlElementName "loggingEnabled" -xmlElementText $FwLoggingEnabled.ToString().ToLower() if ( $FwDefaultPolicyAllow ) { @@ -13800,7 +13820,7 @@ function New-NsxEdge { #Rule Autoconfiguration if ( $AutoGenerateRules ) { [System.XML.XMLElement]$xmlAutoConfig = $XMLDoc.CreateElement("autoConfiguration") - $xmlRoot.appendChild($xmlAutoConfig) | out-null + $xmlRoot.appendChild($xmlAutoConfig) | Out-Null Add-XmlElement -xmlRoot $xmlAutoConfig -xmlElementName "enabled" -xmlElementText $AutoGenerateRules.ToString().ToLower() } @@ -13808,7 +13828,7 @@ function New-NsxEdge { if ( $PsBoundParameters.ContainsKey('EnableSSH') -or $PSBoundParameters.ContainsKey('Password') ) { [System.XML.XMLElement]$xmlCliSettings = $XMLDoc.CreateElement("cliSettings") - $xmlRoot.appendChild($xmlCliSettings) | out-null + $xmlRoot.appendChild($xmlCliSettings) | Out-Null if ( $PsBoundParameters.ContainsKey('Password') ) { Add-XmlElement -xmlRoot $xmlCliSettings -xmlElementName "userName" -xmlElementText $UserName @@ -13820,7 +13840,7 @@ function New-NsxEdge { #DNS Settings if ( $PsBoundParameters.ContainsKey('PrimaryDnsServer') -or $PSBoundParameters.ContainsKey('SecondaryDNSServer') -or $PSBoundParameters.ContainsKey('DNSDomainName') ) { [System.XML.XMLElement]$xmlDnsClient = $XMLDoc.CreateElement("dnsClient") - $xmlRoot.appendChild($xmlDnsClient) | out-null + $xmlRoot.appendChild($xmlDnsClient) | Out-Null if ( $PsBoundParameters.ContainsKey('PrimaryDnsServer') ) { Add-XmlElement -xmlRoot $xmlDnsClient -xmlElementName "primaryDns" -xmlElementText $PrimaryDnsServer } if ( $PsBoundParameters.ContainsKey('SecondaryDnsServer') ) { Add-XmlElement -xmlRoot $xmlDnsClient -xmlElementName "secondaryDns" -xmlElementText $SecondaryDNSServer } if ( $PsBoundParameters.ContainsKey('DNSDomainName') ) { Add-XmlElement -xmlRoot $xmlDnsClient -xmlElementName "domainName" -xmlElementText $DNSDomainName } @@ -13828,22 +13848,22 @@ function New-NsxEdge { #Nics [System.XML.XMLElement]$xmlVnics = $XMLDoc.CreateElement("vnics") - $xmlRoot.appendChild($xmlVnics) | out-null + $xmlRoot.appendChild($xmlVnics) | Out-Null foreach ( $VnicSpec in $Interface ) { $import = $xmlDoc.ImportNode(($VnicSpec), $true) - $xmlVnics.AppendChild($import) | out-null + $xmlVnics.AppendChild($import) | Out-Null } # #Do the post $body = $xmlroot.OuterXml $URI = "/api/4.0/edges" - Write-Progress -activity "Creating Edge Services Gateway $Name" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Creating Edge Services Gateway $Name" -completed + Write-Progress -Activity "Creating Edge Services Gateway $Name" + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating Edge Services Gateway $Name" -Completed $edgeId = $response.Headers.Location.split("/")[$response.Headers.Location.split("/").GetUpperBound(0)] - Get-NsxEdge -objectID $edgeId -connection $connection + Get-NsxEdge -objectId $edgeId -Connection $connection } end {} } @@ -13884,28 +13904,28 @@ function Repair-NsxEdge { #> [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - #The Edge object to be repaired. Accepted on pipline - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$True)] - #WARNING: This operation can potentially cause a datapath outage depending on the deployment architecture. - #Specify the repair operation to be performed on the Edge. - #If ForceSync - The edge appliance is rebooted - #If Redeploy - The Edge is removed and redeployed (if the edge is HA this causes failover, otherwise, an outage.) - #If Upgrade - The Edge is upgraded to latest release - [ValidateSet("ForceSync", "Redeploy","Upgrade")] - [string]$Operation, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + #The Edge object to be repaired. Accepted on pipline + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $True)] + #WARNING: This operation can potentially cause a datapath outage depending on the deployment architecture. + #Specify the repair operation to be performed on the Edge. + #If ForceSync - The edge appliance is rebooted + #If Redeploy - The Edge is removed and redeployed (if the edge is HA this causes failover, otherwise, an outage.) + #If Upgrade - The Edge is upgraded to latest release + [ValidateSet("ForceSync", "Redeploy", "Upgrade")] + [string]$Operation, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -13917,7 +13937,7 @@ function Repair-NsxEdge { $URI = "/api/4.0/edges/$($Edge.Id)?action=$($Operation.ToLower())" if ( $confirm ) { - $message = "WARNING: An Edge Services Gateway $Operation is disruptive to Edge services and may cause connectivity loss depending on the deployment architecture." + $message = "WARNING: An Edge Services Gateway $Operation is disruptive to Edge services and may cause connectivity loss depending on the deployment architecture." $question = "Proceed with Redeploy of Edge Services Gateway $($Edge.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -13927,10 +13947,10 @@ function Repair-NsxEdge { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Repairing Edge Services Gateway $($Edge.Name)" - $null = invoke-nsxwebrequest -method "post" -uri $URI -connection $connection - write-progress -activity "Reparing Edge Services Gateway $($Edge.Name)" -completed - Get-NsxEdge -objectId $($Edge.Id) -connection $connection + Write-Progress -Activity "Repairing Edge Services Gateway $($Edge.Name)" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection + Write-Progress -Activity "Reparing Edge Services Gateway $($Edge.Name)" -Completed + Get-NsxEdge -objectId $($Edge.Id) -Connection $connection } } @@ -13992,38 +14012,38 @@ function Set-NsxEdge { #> [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, #cliSettings - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$userName, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$password, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [boolean]$remoteAccess, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [ValidateRange(1,99999)] - [int]$passwordExpiry, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [string]$sshLoginBannerText, - - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$userName, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$password, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [boolean]$remoteAccess, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [ValidateRange(1, 99999)] + [int]$passwordExpiry, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [string]$sshLoginBannerText, + + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -14036,53 +14056,59 @@ function Set-NsxEdge { $_Edge = $Edge.CloneNode($true) #Remove EdgeSummary... - $edgeSummary = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query 'descendant::edgeSummary') + $edgeSummary = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query 'descendant::edgeSummary') if ( $edgeSummary ) { - $_Edge.RemoveChild($edgeSummary) | out-null + $_Edge.RemoveChild($edgeSummary) | Out-Null } #cliSettings if ( $PsBoundParameters.ContainsKey('userName') ) { if ( $PsBoundParameters.ContainsKey('password') ) { - if ( invoke-xpathquery -node $_Edge -querymethod SelectSingleNode -Query "child::cliSettings/userName" ) { + if ( Invoke-XpathQuery -Node $_Edge -QueryMethod SelectSingleNode -query "child::cliSettings/userName" ) { $_Edge.cliSettings.username = $userName - } else { - Add-XmlElement -xmlroot $_Edge.cliSettings -xmlElementName "userName" -xmlElementText $userName } - } else { + else { + Add-XmlElement -xmlRoot $_Edge.cliSettings -xmlElementName "userName" -xmlElementText $userName + } + } + else { throw "You need to specify a password for change username..." } } if ( $PsBoundParameters.ContainsKey('password') ) { - if ( invoke-xpathquery -node $_Edge -querymethod SelectSingleNode -Query "child::cliSettings/password" ) { + if ( Invoke-XpathQuery -Node $_Edge -QueryMethod SelectSingleNode -query "child::cliSettings/password" ) { $_Edge.cliSettings.password = $password - } else { + } + else { Add-XmlElement -xmlRoot $_Edge.cliSettings -xmlElementName "password" -xmlElementText $password } } if ( $PsBoundParameters.ContainsKey('remoteAccess') ) { - if ( invoke-xpathquery -node $_Edge -querymethod SelectSingleNode -Query "child::cliSettings/remoteAccess" ) { + if ( Invoke-XpathQuery -Node $_Edge -QueryMethod SelectSingleNode -query "child::cliSettings/remoteAccess" ) { $_Edge.cliSettings.remoteAccess = $remoteAccess.ToString().ToLower() - } else { - Add-XmlElement -xmlroot $_Edge.cliSettings -xmlElementName "remoteAccess" -xmlElementText $remoteAccess.ToString().ToLower() + } + else { + Add-XmlElement -xmlRoot $_Edge.cliSettings -xmlElementName "remoteAccess" -xmlElementText $remoteAccess.ToString().ToLower() } } if ( $PsBoundParameters.ContainsKey('passwordExpiry') ) { - if ( invoke-xpathquery -node $_Edge -querymethod SelectSingleNode -Query "child::cliSettings/passwordExpiry" ) { + if ( Invoke-XpathQuery -Node $_Edge -QueryMethod SelectSingleNode -query "child::cliSettings/passwordExpiry" ) { $_Edge.cliSettings.passwordExpiry = $passwordExpiry.ToString() - } else { - Add-XmlElement -xmlroot $_Edge.cliSettings -xmlElementName "passwordExpiry" -xmlElementText $passwordExpiry.ToString() + } + else { + Add-XmlElement -xmlRoot $_Edge.cliSettings -xmlElementName "passwordExpiry" -xmlElementText $passwordExpiry.ToString() } } if ( $PsBoundParameters.ContainsKey('sshLoginBannerText') ) { - if ( invoke-xpathquery -node $_Edge -querymethod SelectSingleNode -Query "child::cliSettings/sshLoginBannerText" ) { + if ( Invoke-XpathQuery -Node $_Edge -QueryMethod SelectSingleNode -query "child::cliSettings/sshLoginBannerText" ) { $_Edge.cliSettings.sshLoginBannerText = $sshLoginBannerText - } else { - Add-XmlElement -xmlroot $_Edge.cliSettings -xmlElementName "sshLoginBannerText" -xmlElementText $sshLoginBannerText + } + else { + Add-XmlElement -xmlRoot $_Edge.cliSettings -xmlElementName "sshLoginBannerText" -xmlElementText $sshLoginBannerText } } @@ -14090,7 +14116,7 @@ function Set-NsxEdge { $body = $_Edge.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway update will modify existing Edge configuration." + $message = "Edge Services Gateway update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($Edge.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -14100,10 +14126,10 @@ function Set-NsxEdge { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($Edge.Name)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($Edge.Name)" -completed - Get-NsxEdge -objectId $($Edge.Id) -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($Edge.Name)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($Edge.Name)" -Completed + Get-NsxEdge -objectId $($Edge.Id) -Connection $connection } } @@ -14130,19 +14156,19 @@ function Remove-NsxEdge { This cmdlet removes the specified ESG. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -14153,7 +14179,7 @@ function Remove-NsxEdge { process { if ( $confirm ) { - $message = "Edge Services Gateway removal is permanent." + $message = "Edge Services Gateway removal is permanent." $question = "Proceed with removal of Edge Services Gateway $($Edge.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -14165,9 +14191,9 @@ function Remove-NsxEdge { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/4.0/edges/$($Edge.Edgesummary.ObjectId)" - Write-Progress -activity "Remove Edge Services Gateway $($Edge.Name)" - invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection| out-null - write-progress -activity "Remove Edge Services Gateway $($Edge.Name)" -completed + Write-Progress -Activity "Remove Edge Services Gateway $($Edge.Name)" + Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection | Out-Null + Write-Progress -Activity "Remove Edge Services Gateway $($Edge.Name)" -Completed } } @@ -14211,21 +14237,21 @@ function Get-NsxEdgeStatus { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { $URI = "/api/4.0/edges/$($Edge.Id)/status" - [system.xml.xmldocument]$response = invoke-nsxrestmethod -method "GET" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query "child::edgeStatus")) { + [system.xml.xmldocument]$response = Invoke-NsxRestMethod -method "GET" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::edgeStatus")) { $response.edgeStatus } } @@ -14257,13 +14283,13 @@ function Enable-NsxEdgeSsh { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -14274,9 +14300,9 @@ function Enable-NsxEdgeSsh { process { $URI = "/api/4.0/edges/$($Edge.Edgesummary.ObjectId)/cliremoteaccess?enable=true" - Write-Progress -activity "Enable SSH on Edge Services Gateway $($Edge.Name)" - invoke-nsxrestmethod -method "post" -uri $URI -connection $connection| out-null - write-progress -activity "Enable SSH on Edge Services Gateway $($Edge.Name)" -completed + Write-Progress -Activity "Enable SSH on Edge Services Gateway $($Edge.Name)" + Invoke-NsxRestMethod -method "post" -URI $URI -connection $connection | Out-Null + Write-Progress -Activity "Enable SSH on Edge Services Gateway $($Edge.Name)" -Completed } @@ -14305,18 +14331,18 @@ function Disable-NsxEdgeSsh { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -14327,7 +14353,7 @@ function Disable-NsxEdgeSsh { process { if ( $confirm ) { - $message = "Disabling SSH will prevent remote SSH connections to this edge." + $message = "Disabling SSH will prevent remote SSH connections to this edge." $question = "Proceed with disabling SSH service on $($Edge.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -14339,14 +14365,136 @@ function Disable-NsxEdgeSsh { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/4.0/edges/$($Edge.Edgesummary.ObjectId)/cliremoteaccess?enable=false" - Write-Progress -activity "Disable SSH on Edge Services Gateway $($Edge.Name)" - invoke-nsxrestmethod -method "post" -uri $URI -connection $connection| out-null - write-progress -activity "Disable SSH on Edge Services Gateway $($Edge.Name)" -completed + Write-Progress -Activity "Disable SSH on Edge Services Gateway $($Edge.Name)" + Invoke-NsxRestMethod -method "post" -URI $URI -connection $connection | Out-Null + Write-Progress -Activity "Disable SSH on Edge Services Gateway $($Edge.Name)" -Completed + } + } + + end {} + +} + +function Enable-NsxEdgeFips { + + <# + .SYNOPSIS + Enables FIPS on an existing NSX Edge Services Gateway. + + .DESCRIPTION + Enables FIPS on an existing NSX Edge Services Gateway. Changing the FIPS + mode will reboot the NSX Edge appliance + + .EXAMPLE + Get-NsxEdge Edge01 | Enable-NsxEdgeFips + + Enable FIPS mode on edge Edge01 + + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + + ) + + begin { + + } + + process { + + if ($Edge.enableFips -eq "false") { + if ( $confirm ) { + $message = "Enabling FIPS mode will reboot the NSX Edge appliance." + $question = "Proceed with enabling FIPS mode on Edge Services Gateway: $($Edge.Name) ($($Edge.Edgesummary.ObjectId))?" + $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] + $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) + $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) + + $decision = $Host.UI.PromptForChoice($message, $question, $choices, 1) + } + else { $decision = 0 } + if ($decision -eq 0) { + $URI = "/api/4.0/edges/$($Edge.Edgesummary.ObjectId)/fips?enable=true" + Write-Progress -Activity "Enabling FIPS mode on Edge Services Gateway: $($Edge.Name) ($($Edge.Edgesummary.ObjectId))" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection + Write-Progress -Activity "Enabling FIPS mode on Edge Services Gateway: $($Edge.Name) ($($Edge.Edgesummary.ObjectId))" -Completed + } } } end {} +} + +function Disable-NsxEdgeFips { + + <# + .SYNOPSIS + Disables FIPS mode on an existing NSX Edge Services Gateway. + + .DESCRIPTION + Enables FIPS mode on an existing NSX Edge Services Gateway. Changing the FIPS + mode will reboot the NSX Edge appliance + + .EXAMPLE + Get-NsxEdge Edge01 | Disable-NsxEdgeFips + + Disable FIPS mode on edge Edge01 + + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + + ) + + begin { + + } + + process { + + if ($Edge.enableFips -eq "true") { + if ( $confirm ) { + $message = "Disabling FIPS mode will reboot the NSX Edge appliance." + $question = "Proceed with disabling FIPS mode on Edge Services Gateway: $($Edge.Name) ($($Edge.Edgesummary.ObjectId))?" + $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] + $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) + $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No')) + + $decision = $Host.UI.PromptForChoice($message, $question, $choices, 1) + } + else { $decision = 0 } + if ($decision -eq 0) { + $URI = "/api/4.0/edges/$($Edge.Edgesummary.ObjectId)/fips?enable=false" + Write-Progress -Activity "Disabling FIPS mode on Edge Services Gateway: $($Edge.Name) ($($Edge.Edgesummary.ObjectId))" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -connection $connection + Write-Progress -Activity "Disabling FIPS mode on Edge Services Gateway: $($Edge.Name) ($($Edge.Edgesummary.ObjectId))" -Completed + } + } + } + end {} } ######### @@ -14378,21 +14526,21 @@ function Set-NsxEdgeNat { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeNat $_ })] - [System.Xml.XmlElement]$EdgeNat, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$Enabled, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeNat $_ })] + [System.Xml.XmlElement]$EdgeNat, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$Enabled, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -14407,7 +14555,7 @@ function Set-NsxEdgeNat { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeNat.edgeId - $_EdgeNat.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeNat -Query 'descendant::edgeId')) ) | out-null + $_EdgeNat.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeNat -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -14425,7 +14573,7 @@ function Set-NsxEdgeNat { $body = $_EdgeNat.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway NAT update will modify existing Edge configuration." + $message = "Edge Services Gateway NAT update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -14435,10 +14583,10 @@ function Set-NsxEdgeNat { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeNat + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeNat } } @@ -14477,9 +14625,9 @@ function Get-NsxEdgeNat { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin { @@ -14528,14 +14676,14 @@ function Get-NsxEdgeNatRule { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeNat $_ })] - [System.Xml.XmlElement]$EdgeNat, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$RuleId, - [Parameter (Mandatory=$false)] - [switch]$ShowInternal=$false + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeNat $_ })] + [System.Xml.XmlElement]$EdgeNat, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$RuleId, + [Parameter (Mandatory = $false)] + [switch]$ShowInternal = $false ) @@ -14548,18 +14696,18 @@ function Get-NsxEdgeNatRule { #consistent readable output $_EdgeNat = ($EdgeNat.CloneNode($True)) - $_EdgeNatRules = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeNat -Query 'descendant::natRules') + $_EdgeNatRules = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeNat -query 'descendant::natRules') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called natRule. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeNatRules -Query 'descendant::natRule')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeNatRules -query 'descendant::natRule')) { $RuleCollection = $_EdgeNatRules.natRule if ( $PsBoundParameters.ContainsKey('RuleId')) { - $RuleCollection = $RuleCollection | where-object { $_.ruleId -eq $RuleId } + $RuleCollection = $RuleCollection | Where-Object { $_.ruleId -eq $RuleId } } if ( -not $ShowInternal ) { - $RuleCollection = $RuleCollection | where-object { $_.ruleType -eq 'user' } + $RuleCollection = $RuleCollection | Where-Object { $_.ruleType -eq 'user' } } foreach ( $Rule in $RuleCollection ) { @@ -14637,50 +14785,50 @@ function New-NsxEdgeNatRule { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeNat $_ })] - [System.Xml.XmlElement]$EdgeNat, - [Parameter (Mandatory=$False)] - [ValidateRange(0,200)] - [int]$Vnic, - [Parameter (Mandatory=$True)] - [string]$OriginalAddress, - [Parameter (Mandatory=$True)] - [string]$TranslatedAddress, - [Parameter (Mandatory=$True)] - [Validateset("dnat","snat",ignorecase=$false)] - [string]$action, - [Parameter (Mandatory=$false)] - [string]$Protocol, - [Parameter (Mandatory=$False)] - [string]$Description, - [Parameter (Mandatory=$False)] - [switch]$LoggingEnabled=$false, - [Parameter (Mandatory=$False)] - [switch]$Enabled=$true, - [Parameter (Mandatory=$false)] - [string]$OriginalPort, - [Parameter (Mandatory=$false)] - [string]$TranslatedPort, - [Parameter (Mandatory=$false)] - [string]$IcmpType, - [Parameter (Mandatory=$false)] - [string]$dnatMatchSourceAddress, - [Parameter (Mandatory=$false)] - [string]$snatMatchDestinationAddress, - [Parameter (Mandatory=$false)] - [string]$dnatMatchSourcePort, - [Parameter (Mandatory=$false)] - [string]$snatMatchDestinationPort, - [Parameter (Mandatory=$false)] - [int]$AboveRuleId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeNat $_ })] + [System.Xml.XmlElement]$EdgeNat, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 200)] + [int]$Vnic, + [Parameter (Mandatory = $True)] + [string]$OriginalAddress, + [Parameter (Mandatory = $True)] + [string]$TranslatedAddress, + [Parameter (Mandatory = $True)] + [Validateset("dnat", "snat", ignorecase = $false)] + [string]$action, + [Parameter (Mandatory = $false)] + [string]$Protocol, + [Parameter (Mandatory = $False)] + [string]$Description, + [Parameter (Mandatory = $False)] + [switch]$LoggingEnabled = $false, + [Parameter (Mandatory = $False)] + [switch]$Enabled = $true, + [Parameter (Mandatory = $false)] + [string]$OriginalPort, + [Parameter (Mandatory = $false)] + [string]$TranslatedPort, + [Parameter (Mandatory = $false)] + [string]$IcmpType, + [Parameter (Mandatory = $false)] + [string]$dnatMatchSourceAddress, + [Parameter (Mandatory = $false)] + [string]$snatMatchDestinationAddress, + [Parameter (Mandatory = $false)] + [string]$dnatMatchSourcePort, + [Parameter (Mandatory = $false)] + [string]$snatMatchDestinationPort, + [Parameter (Mandatory = $false)] + [int]$AboveRuleId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -14697,14 +14845,14 @@ function New-NsxEdgeNatRule { if ( -not $PsBoundParameters.ContainsKey('AboveRuleId') ) { $Rules = $xmlDoc.CreateElement('natRules') $Rule = $xmlDoc.CreateElement('natRule') - $xmlDoc.AppendChild($Rules) | out-null - $Rules.AppendChild($Rule) | out-null + $xmlDoc.AppendChild($Rules) | Out-Null + $Rules.AppendChild($Rule) | Out-Null $URI = "/api/4.0/edges/$EdgeId/nat/config/rules" } else { $Rule = $xmlDoc.CreateElement('natRule') - $xmlDoc.AppendChild($Rule) | out-null + $xmlDoc.AppendChild($Rule) | Out-Null $URI = "/api/4.0/edges/$EdgeId/nat/config/rules?aboveRuleId=$($AboveRuleId.toString())" } @@ -14739,7 +14887,7 @@ function New-NsxEdgeNatRule { if ( $PsBoundParameters.ContainsKey('dnatMatchSourceAddress') ) { if ( [version]$Connection.Version -lt [version]"6.3.0") { - write-warning "The option dnatMatchSourceAddress requires at least NSX version 6.3.0" + Write-Warning "The option dnatMatchSourceAddress requires at least NSX version 6.3.0" } else { Add-XmlElement -xmlRoot $Rule -xmlElementName "dnatMatchSourceAddress" -xmlElementText $dnatMatchSourceAddress.ToString() @@ -14748,7 +14896,7 @@ function New-NsxEdgeNatRule { if ( $PsBoundParameters.ContainsKey('snatMatchDestinationAddress') ) { if ( [version]$Connection.Version -lt [version]"6.3.0") { - write-warning "The option snatMatchDestinationAddress requires at least NSX version 6.3.0" + Write-Warning "The option snatMatchDestinationAddress requires at least NSX version 6.3.0" } else { Add-XmlElement -xmlRoot $Rule -xmlElementName "snatMatchDestinationAddress" -xmlElementText $snatMatchDestinationAddress.ToString() @@ -14757,7 +14905,7 @@ function New-NsxEdgeNatRule { if ( $PsBoundParameters.ContainsKey('dnatMatchSourcePort') ) { if ( [version]$Connection.Version -lt [version]"6.3.0") { - write-warning "The option dnatMatchSourcePort requires at least NSX version 6.3.0" + Write-Warning "The option dnatMatchSourcePort requires at least NSX version 6.3.0" } else { Add-XmlElement -xmlRoot $Rule -xmlElementName "dnatMatchSourcePort" -xmlElementText $dnatMatchSourcePort.ToString() @@ -14766,7 +14914,7 @@ function New-NsxEdgeNatRule { if ( $PsBoundParameters.ContainsKey('snatMatchDestinationPort') ) { if ( [version]$Connection.Version -lt [version]"6.3.0") { - write-warning "The option snatMatchDestinationPort requires at least NSX version 6.3.0" + Write-Warning "The option snatMatchDestinationPort requires at least NSX version 6.3.0" } else { Add-XmlElement -xmlRoot $Rule -xmlElementName "snatMatchDestinationPort" -xmlElementText $snatMatchDestinationPort.ToString() @@ -14781,11 +14929,11 @@ function New-NsxEdgeNatRule { $body = $Rule.OuterXml } - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - $ruleid = $response.Headers.Location -replace "/api/4.0/edges/$edgeid/nat/config/rules/","" - Get-NsxEdge -objectId $EdgeId -connection $connection| Get-NsxEdgeNat | Get-NsxEdgeNatRule -ruleid $ruleid + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + $ruleid = $response.Headers.Location -replace "/api/4.0/edges/$edgeid/nat/config/rules/", "" + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeNat | Get-NsxEdgeNatRule -RuleId $ruleid } end {} @@ -14832,19 +14980,19 @@ function Remove-NsxEdgeNatRule { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeNatRule $_ })] - [System.Xml.XmlElement]$NatRule, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeNatRule $_ })] + [System.Xml.XmlElement]$NatRule, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -14859,7 +15007,7 @@ function Remove-NsxEdgeNatRule { $URI = "/api/4.0/edges/$EdgeId/nat/config/rules/$ruleId" if ( $confirm ) { - $message = "Edge Services Gateway nat rule update will modify existing Edge configuration." + $message = "Edge Services Gateway nat rule update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -14869,9 +15017,9 @@ function Remove-NsxEdgeNatRule { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $EdgeId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed } } @@ -14917,83 +15065,83 @@ function Set-NsxEdgeFirewall { #> - [CmdletBinding(DefaultParameterSetName="Default")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeFw $_ })] - [System.Xml.XmlElement]$EdgeFirewall, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #Enable / Disable Edge Firewall - [switch]$Enabled, - [Parameter (Mandatory=$False)] - #Default rule action - [ValidateSet("accept","deny","reject", IgnoreCase=$False)] - [string]$DefaultRuleAction, - [Parameter (Mandatory=$False)] - #Default rule logging configuration - [switch]$DefaultRuleLoggingEnabled, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$tcpPickOngoingConnections, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$tcpAllowOutOfWindowPackets, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$tcpSendResetForClosedVsePorts, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$dropInvalidTraffic, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$logInvalidTraffic, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$tcpTimeoutOpen, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$tcpTimeoutEstablished, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$tcpTimeoutClose, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$udpTimeout, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$icmpTimeout, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$icmp6Timeout, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [int]$ipGenericTimeout, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$enableSynFloodProtection, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$logIcmpErrors, - [Parameter (Mandatory=$False)] - #Edge Firewall global config option - [switch]$dropIcmpReplays, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdletBinding(DefaultParameterSetName = "Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeFw $_ })] + [System.Xml.XmlElement]$EdgeFirewall, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #Enable / Disable Edge Firewall + [switch]$Enabled, + [Parameter (Mandatory = $False)] + #Default rule action + [ValidateSet("accept", "deny", "reject", IgnoreCase = $False)] + [string]$DefaultRuleAction, + [Parameter (Mandatory = $False)] + #Default rule logging configuration + [switch]$DefaultRuleLoggingEnabled, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$tcpPickOngoingConnections, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$tcpAllowOutOfWindowPackets, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$tcpSendResetForClosedVsePorts, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$dropInvalidTraffic, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$logInvalidTraffic, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$tcpTimeoutOpen, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$tcpTimeoutEstablished, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$tcpTimeoutClose, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$udpTimeout, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$icmpTimeout, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$icmp6Timeout, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [int]$ipGenericTimeout, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$enableSynFloodProtection, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$logIcmpErrors, + [Parameter (Mandatory = $False)] + #Edge Firewall global config option + [switch]$dropIcmpReplays, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } } @@ -15005,7 +15153,7 @@ function Set-NsxEdgeFirewall { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $EdgeFirewall.edgeId - $_EdgeFirewall.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeFirewall -Query 'descendant::edgeId')) ) | out-null + $_EdgeFirewall.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeFirewall -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -15072,7 +15220,7 @@ function Set-NsxEdgeFirewall { if ( $PsBoundParameters.ContainsKey('enableSynFloodProtection') ) { if ( [version]$Connection.Version -lt [version]"6.2.3") { - write-warning "The option enableSynFloodProtection requires at least NSX version 6.2.3" + Write-Warning "The option enableSynFloodProtection requires at least NSX version 6.2.3" } else { $_EdgeFirewall.globalConfig.enableSynFloodProtection = $enableSynFloodProtection.ToString().ToLower() @@ -15081,7 +15229,7 @@ function Set-NsxEdgeFirewall { if ( $PsBoundParameters.ContainsKey('logIcmpErrors') ) { if ( [version]$Connection.Version -lt [version]"6.3.0") { - write-warning "The option logIcmpErrors requires at least NSX version 6.3.0" + Write-Warning "The option logIcmpErrors requires at least NSX version 6.3.0" } else { $_EdgeFirewall.globalConfig.logIcmpErrors = $logIcmpErrors.ToString().ToLower() @@ -15090,7 +15238,7 @@ function Set-NsxEdgeFirewall { if ( $PsBoundParameters.ContainsKey('dropIcmpReplays') ) { if ( [version]$Connection.Version -lt [version]"6.3.0") { - write-warning "The option dropIcmpReplays requires at least NSX version 6.3.0" + Write-Warning "The option dropIcmpReplays requires at least NSX version 6.3.0" } else { $_EdgeFirewall.globalConfig.dropIcmpReplays = $dropIcmpReplays.ToString().ToLower() @@ -15101,7 +15249,7 @@ function Set-NsxEdgeFirewall { $body = $_EdgeFirewall.OuterXml if ( -not ( $Noconfirm )) { - $message = "Edge Services Gateway firewall configuration update will modify and existing Edge configuration." + $message = "Edge Services Gateway firewall configuration update will modify and existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -15111,10 +15259,10 @@ function Set-NsxEdgeFirewall { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeFirewall + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeFirewall } } @@ -15147,9 +15295,9 @@ function Get-NsxEdgeFirewall { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin { @@ -15190,18 +15338,18 @@ function Get-NsxEdgeFirewallRule { the specified Edge Services Gateway. #> - [CmdLetBinding (DefaultParameterSetName="Name")] + [CmdLetBinding (DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeFw $_ })] - [System.Xml.XmlElement]$EdgeFirewall, - [Parameter (Mandatory=$false, ParameterSetName="RuleId")] - [ValidateNotNullorEmpty()] - [String]$RuleId, - [Parameter (Mandatory=$false, ParameterSetName="Name", Position=1)] - [ValidateNotNullorEmpty()] - [String]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeFw $_ })] + [System.Xml.XmlElement]$EdgeFirewall, + [Parameter (Mandatory = $false, ParameterSetName = "RuleId")] + [ValidateNotNullorEmpty()] + [String]$RuleId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [ValidateNotNullorEmpty()] + [String]$Name ) begin { @@ -15213,17 +15361,17 @@ function Get-NsxEdgeFirewallRule { #consistent readable output $_EdgeFirewall = ($EdgeFirewall.CloneNode($True)) - $_EdgeFirewallRules = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeFirewall -Query 'descendant::firewallRules') + $_EdgeFirewallRules = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeFirewall -query 'descendant::firewallRules') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called natRule. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeFirewallRules -Query 'descendant::firewallRule')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeFirewallRules -query 'descendant::firewallRule')) { $RuleCollection = $_EdgeFirewallRules.FirewallRule if ( $PsBoundParameters.ContainsKey('RuleId')) { - $RuleCollection = $RuleCollection | where-object { $_.id -eq $RuleId } + $RuleCollection = $RuleCollection | Where-Object { $_.id -eq $RuleId } } elseif ($PsBoundParameters.ContainsKey("Name")) { - $RuleCollection = $RuleCollection | where-object { $_.Name -eq $Name } + $RuleCollection = $RuleCollection | Where-Object { $_.Name -eq $Name } } foreach ( $Rule in $RuleCollection ) { @@ -15259,64 +15407,64 @@ function New-NsxEdgeFirewallRule { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeFw $_ })] - [System.Xml.XmlElement]$EdgeFireWall, - [Parameter (Mandatory=$true)] - # Name of the new rule - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - # Comment string for the new rule - [string]$Comment="", - [Parameter (Mandatory=$true)] - # Action of the rule - allow, deny or reject. - [ValidateSet("accept","deny","reject")] - [string]$Action, - [Parameter (Mandatory=$false)] - # Source(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. - [ValidateScript({ ValidateFirewallRuleSourceDest $_ })] - [object[]]$Source, - [Parameter (Mandatory=$false)] - # Source(s) vNics of traffic to hit the rule. Valid options are 0 - 9, internal, external, vse - [ValidateSet("0","1","2","3","4","5","6","7","8","9", "internal", "external", "vse")] - [string[]]$SourceVnic, - [Parameter (Mandatory=$false)] - # Destination(s) vNics of traffic to hit the rule. Valid options are 0 - 9, internal, external, vse - [ValidateSet("0","1","2","3","4","5","6","7","8","9", "internal", "external", "vse")] - [string[]]$DestinationVnic, - [Parameter (Mandatory=$false)] - # Negate the list of sources hit by the rule - [ValidateNotNullOrEmpty()] - [switch]$NegateSource, - [Parameter (Mandatory=$false)] - # Destination(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. - [ValidateScript({ ValidateFirewallRuleSourceDest $_ })] - [object[]]$Destination, - [Parameter (Mandatory=$false)] - # Negate the list of destinations hit by the rule - [ValidateNotNullOrEmpty()] - [switch]$NegateDestination, - [Parameter (Mandatory=$false)] - # Services to hit the rule. Services must be marked for inheritance in global scope, or defined directly within edge scope. - [ValidateScript ({ ValidateEdgeFirewallRuleService $_ })] - [object[]]$Service, - [Parameter (Mandatory=$false)] - # Rule is created as disabled - [switch]$Disabled, - [Parameter (Mandatory=$false)] - # Rule logging is enabled - [switch]$EnableLogging, - [Parameter (Mandatory=$false)] - # Existing RuleId above which to create new rule - [int]$AboveRuleId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeFw $_ })] + [System.Xml.XmlElement]$EdgeFireWall, + [Parameter (Mandatory = $true)] + # Name of the new rule + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + # Comment string for the new rule + [string]$Comment = "", + [Parameter (Mandatory = $true)] + # Action of the rule - allow, deny or reject. + [ValidateSet("accept", "deny", "reject")] + [string]$Action, + [Parameter (Mandatory = $false)] + # Source(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. + [ValidateScript( { ValidateFirewallRuleSourceDest $_ })] + [object[]]$Source, + [Parameter (Mandatory = $false)] + # Source(s) vNics of traffic to hit the rule. Valid options are 0 - 9, internal, external, vse + [ValidateSet("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "internal", "external", "vse")] + [string[]]$SourceVnic, + [Parameter (Mandatory = $false)] + # Destination(s) vNics of traffic to hit the rule. Valid options are 0 - 9, internal, external, vse + [ValidateSet("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "internal", "external", "vse")] + [string[]]$DestinationVnic, + [Parameter (Mandatory = $false)] + # Negate the list of sources hit by the rule + [ValidateNotNullOrEmpty()] + [switch]$NegateSource, + [Parameter (Mandatory = $false)] + # Destination(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. + [ValidateScript( { ValidateFirewallRuleSourceDest $_ })] + [object[]]$Destination, + [Parameter (Mandatory = $false)] + # Negate the list of destinations hit by the rule + [ValidateNotNullOrEmpty()] + [switch]$NegateDestination, + [Parameter (Mandatory = $false)] + # Services to hit the rule. Services must be marked for inheritance in global scope, or defined directly within edge scope. + [ValidateScript ( { ValidateEdgeFirewallRuleService $_ })] + [object[]]$Service, + [Parameter (Mandatory = $false)] + # Rule is created as disabled + [switch]$Disabled, + [Parameter (Mandatory = $false)] + # Rule logging is enabled + [switch]$EnableLogging, + [Parameter (Mandatory = $false)] + # Existing RuleId above which to create new rule + [int]$AboveRuleId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -15330,19 +15478,20 @@ function New-NsxEdgeFirewallRule { if ( ( $member -as [ipaddress]) -or ( ValidateIPRange -argument $member ) -or ( ValidateIPPrefix -argument $member ) ) { #Item is v4 or 6 address - write-debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $member" - write-debug "$($MyInvocation.MyCommand.Name) : Object $member is an ipaddress" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $member" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $member is an ipaddress" Add-XmlElement -xmlRoot $SourceDestNode -xmlElementName "ipAddress" -xmlElementText $member } elseif ( $member -is [system.xml.xmlelement] ) { - write-debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $($member.name)" - write-debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as xml element" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $($member.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as xml element" #XML representation of NSX object passed - ipset, sec group or logical switch #get appropritate name, value. Add-XmlElement -xmlRoot $SourceDestNode -xmlElementName "groupingObjectId" -xmlElementText $member.objectId - } else { - write-debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $($member.name)" - write-debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as supported powercli object" + } + else { + Write-Debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $($member.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as supported powercli object" #Proper PowerCLI Object passed. We just need to grab details from the moref. Add-XmlElement -xmlRoot $SourceDestNode -xmlElementName "groupingObjectId" -xmlElementText $member.extensiondata.moref.value } @@ -15435,12 +15584,12 @@ function New-NsxEdgeFirewallRule { } - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - $ruleid = $response.Headers.Location -replace "/api/4.0/edges/$edgeid/firewall/config/rules/","" - write-debug "$($MyInvocation.MyCommand.Name) : Retrieving ruleid $ruleid from API for $edgeid" - $response = invoke-nsxwebrequest -method "get" -uri "/api/4.0/edges/$EdgeId/firewall/config/rules/$ruleid" -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + $ruleid = $response.Headers.Location -replace "/api/4.0/edges/$edgeid/firewall/config/rules/", "" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieving ruleid $ruleid from API for $edgeid" + $response = Invoke-NsxWebRequest -method "get" -URI "/api/4.0/edges/$EdgeId/firewall/config/rules/$ruleid" -connection $connection [system.xml.xmlDocument]$responserule = $response.content Add-XmlElement -xmlRoot $responserule.firewallRule -xmlElementName "edgeId" -xmlElementText $EdgeId $responserule.firewallRule @@ -15497,27 +15646,27 @@ function Set-NsxEdgeFirewallRule { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - # Edge FW rule as returned by Get-NsxEdgeFirewallRule / New-NsxEdgeFirewallRule - [ValidateScript({ ValidateEdgeFwRule $_ })] - [System.Xml.XmlElement]$FirewallRule, - [Parameter (Mandatory=$false)] - [boolean]$enabled, - [Parameter (Mandatory=$false)] - [boolean]$loggingEnabled, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$comment, - [Parameter (Mandatory=$false)] - [ValidateSet("Accept", "Deny", "Reject")] - [string]$action, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + # Edge FW rule as returned by Get-NsxEdgeFirewallRule / New-NsxEdgeFirewallRule + [ValidateScript( { ValidateEdgeFwRule $_ })] + [System.Xml.XmlElement]$FirewallRule, + [Parameter (Mandatory = $false)] + [boolean]$enabled, + [Parameter (Mandatory = $false)] + [boolean]$loggingEnabled, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$comment, + [Parameter (Mandatory = $false)] + [ValidateSet("Accept", "Deny", "Reject")] + [string]$action, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -15530,7 +15679,7 @@ function Set-NsxEdgeFirewallRule { $_FirewallRule = $FirewallRule.CloneNode($true) $edgeId = $FirewallRule.edgeId - $_FirewallRule.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_FirewallRule -Query 'descendant::edgeId')) ) | out-null + $_FirewallRule.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_FirewallRule -query 'descendant::edgeId')) ) | Out-Null if ( $PsBoundParameters.ContainsKey('enabled') ) { $_FirewallRule.enabled = $enabled.ToString().ToLower() @@ -15555,7 +15704,7 @@ function Set-NsxEdgeFirewallRule { $URI = "/api/4.0/edges/$EdgeId/firewall/config/rules/$ruleId" try { - $response = Invoke-NsxWebRequest -method put -Uri $uri -body $_FirewallRule.OuterXml -connection $connection + $response = Invoke-NsxWebRequest -method put -URI $uri -body $_FirewallRule.OuterXml -connection $connection [xml]$ruleElem = $response.Content Get-NsxEdge -Object $EdgeId | Get-NsxEdgeFirewall | Get-NsxEdgeFirewallRule -RuleId $ruleId } @@ -15587,28 +15736,28 @@ function Remove-NsxEdgeFirewallRule { from the specified Edge Services Gateway. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - [CmdletBinding (DefaultParameterSetName="Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + [CmdletBinding (DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeFwRule $_ })] - [System.Xml.XmlElement]$FirewallRule, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeFwRule $_ })] + [System.Xml.XmlElement]$FirewallRule, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } } @@ -15622,7 +15771,7 @@ function Remove-NsxEdgeFirewallRule { $URI = "/api/4.0/edges/$EdgeId/firewall/config/rules/$ruleId" if ( -not $noConfirm ) { - $message = "Edge Services Gateway firewall rule update will modify existing Edge configuration." + $message = "Edge Services Gateway firewall rule update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -15632,9 +15781,9 @@ function Remove-NsxEdgeFirewallRule { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $EdgeId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed } } @@ -15673,15 +15822,15 @@ function Get-NsxEdgeCsr { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Edge")] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - [string]$objectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Edge")] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + [string]$objectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -15692,9 +15841,9 @@ function Get-NsxEdgeCsr { #Just getting a single named csr by id group $URI = "/api/2.0/services/truststore/csr/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::csr')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::csr')) { $response.csr } } @@ -15703,10 +15852,10 @@ function Get-NsxEdgeCsr { else { $URI = "/api/2.0/services/truststore/csr/scope/$($Edge.Id)" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::csrs/csr')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::csrs/csr')) { $response.csrs.csr } } @@ -15716,7 +15865,7 @@ function Get-NsxEdgeCsr { end {} } -function New-NsxEdgeCsr{ +function New-NsxEdgeCsr { <# .SYNOPSIS @@ -15743,31 +15892,31 @@ function New-NsxEdgeCsr{ #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$True)] - [string]$CommonName, - [Parameter (Mandatory=$True)] - [string]$Organisation, - [Parameter (Mandatory=$True)] - [string]$Country, - [Parameter (Mandatory=$True)] - [string]$OrganisationalUnit, - [Parameter (Mandatory=$False)] - [ValidateSet(2048,3072)] - [int]$Keysize=2048, - [Parameter (Mandatory=$False)] - [ValidateSet("RSA", "DSA", IgnoreCase=$false )] - [string]$Algorithm="RSA", - [Parameter (Mandatory=$False)] - [string]$Description, - [Parameter (Mandatory=$False)] - [string]$Name, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $True)] + [string]$CommonName, + [Parameter (Mandatory = $True)] + [string]$Organisation, + [Parameter (Mandatory = $True)] + [string]$Country, + [Parameter (Mandatory = $True)] + [string]$OrganisationalUnit, + [Parameter (Mandatory = $False)] + [ValidateSet(2048, 3072)] + [int]$Keysize = 2048, + [Parameter (Mandatory = $False)] + [ValidateSet("RSA", "DSA", IgnoreCase = $false )] + [string]$Algorithm = "RSA", + [Parameter (Mandatory = $False)] + [string]$Description, + [Parameter (Mandatory = $False)] + [string]$Name, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -15781,29 +15930,29 @@ function New-NsxEdgeCsr{ [System.Xml.XmlDocument] $xmlDoc = New-Object System.Xml.XmlDocument $csr = $xmlDoc.CreateElement('csr') $subject = $xmlDoc.CreateElement('subject') - $csr.AppendChild($subject) | out-null + $csr.AppendChild($subject) | Out-Null #Common Name $CnAttribute = $xmlDoc.CreateElement('attribute') - $subject.AppendChild($CnAttribute) | out-null + $subject.AppendChild($CnAttribute) | Out-Null Add-XmlElement -xmlRoot $CnAttribute -xmlElementName "key" -xmlElementText "CN" Add-XmlElement -xmlRoot $CnAttribute -xmlElementName "value" -xmlElementText $CommonName.ToString() #Organisation $OAttribute = $xmlDoc.CreateElement('attribute') - $subject.AppendChild($OAttribute) | out-null + $subject.AppendChild($OAttribute) | Out-Null Add-XmlElement -xmlRoot $OAttribute -xmlElementName "key" -xmlElementText "O" Add-XmlElement -xmlRoot $OAttribute -xmlElementName "value" -xmlElementText $Organisation.ToString() #OU $OuAttribute = $xmlDoc.CreateElement('attribute') - $subject.AppendChild($OuAttribute) | out-null + $subject.AppendChild($OuAttribute) | Out-Null Add-XmlElement -xmlRoot $OuAttribute -xmlElementName "key" -xmlElementText "OU" Add-XmlElement -xmlRoot $OuAttribute -xmlElementName "value" -xmlElementText $OrganisationalUnit.ToString() #Country $CAttribute = $xmlDoc.CreateElement('attribute') - $subject.AppendChild($CAttribute) | out-null + $subject.AppendChild($CAttribute) | Out-Null Add-XmlElement -xmlRoot $CAttribute -xmlElementName "key" -xmlElementText "C" Add-XmlElement -xmlRoot $CAttribute -xmlElementName "value" -xmlElementText $Country.ToString() @@ -15826,9 +15975,9 @@ function New-NsxEdgeCsr{ $URI = "/api/2.0/services/truststore/csr/$edgeId" $body = $csr.OuterXml - Write-Progress -activity "Update Edge Services Gateway $EdgeId" - $response = Invoke-NsxRestMethod -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" + $response = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed $response.csr } @@ -15836,7 +15985,7 @@ function New-NsxEdgeCsr{ end {} } -function Remove-NsxEdgeCsr{ +function Remove-NsxEdgeCsr { <# .SYNOPSIS @@ -15865,19 +16014,19 @@ function Remove-NsxEdgeCsr{ pipeline to Remove-NsxEdgeCsr. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeCsr $_ })] - [System.Xml.XmlElement]$Csr, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeCsr $_ })] + [System.Xml.XmlElement]$Csr, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -15887,7 +16036,7 @@ function Remove-NsxEdgeCsr{ process { if ( $confirm ) { - $message = "CSR removal is permanent." + $message = "CSR removal is permanent." $question = "Proceed with removal of CSR $($Csr.objectId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -15900,9 +16049,9 @@ function Remove-NsxEdgeCsr{ if ($decision -eq 0) { $URI = "/api/2.0/services/truststore/csr/$($csr.objectId)" - Write-Progress -activity "Remove CSR $($Csr.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove CSR $($Csr.Name)" -completed + Write-Progress -Activity "Remove CSR $($Csr.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove CSR $($Csr.Name)" -Completed } } @@ -15910,7 +16059,7 @@ function Remove-NsxEdgeCsr{ end {} } -function Get-NsxEdgeCertificate{ +function Get-NsxEdgeCertificate { <# .SYNOPSIS @@ -15937,15 +16086,15 @@ function Get-NsxEdgeCertificate{ param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Edge")] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - [string]$objectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Edge")] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + [string]$objectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -15956,9 +16105,9 @@ function Get-NsxEdgeCertificate{ #Just getting a single named csr by id group $URI = "/api/2.0/services/truststore/certificate/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::certificate')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::certificate')) { $response.certificate } } @@ -15967,10 +16116,10 @@ function Get-NsxEdgeCertificate{ else { $URI = "/api/2.0/services/truststore/certificate/scope/$($Edge.Id)" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( $response ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::certificates/certificate')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::certificates/certificate')) { $response.certificates.certificate } } @@ -15980,7 +16129,7 @@ function Get-NsxEdgeCertificate{ end {} } -function New-NsxEdgeSelfSignedCertificate{ +function New-NsxEdgeSelfSignedCertificate { <# .SYNOPSIS @@ -16007,15 +16156,15 @@ function New-NsxEdgeSelfSignedCertificate{ #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeCSR $_ })] - [System.Xml.XmlElement]$CSR, - [Parameter (Mandatory=$False)] - [int]$NumberOfDays=365, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeCSR $_ })] + [System.Xml.XmlElement]$CSR, + [Parameter (Mandatory = $False)] + [int]$NumberOfDays = 365, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -16027,9 +16176,9 @@ function New-NsxEdgeSelfSignedCertificate{ $URI = "/api/2.0/services/truststore/csr/$($csr.objectId)?noOfDays=$NumberOfDays" - Write-Progress -activity "Update Edge Services Gateway $EdgeId" - $response = Invoke-NsxRestMethod -method "Put" -uri $URI -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" + $response = Invoke-NsxRestMethod -method "Put" -URI $URI -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed $response.Certificate } @@ -16037,7 +16186,7 @@ function New-NsxEdgeSelfSignedCertificate{ end {} } -function Remove-NsxEdgeCertificate{ +function Remove-NsxEdgeCertificate { <# .SYNOPSIS @@ -16065,19 +16214,19 @@ function Remove-NsxEdgeCertificate{ passing them on the pipeline to Remove-NsxEdgeCertificate. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeCertificate $_ })] - [System.Xml.XmlElement]$Certificate, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeCertificate $_ })] + [System.Xml.XmlElement]$Certificate, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -16087,7 +16236,7 @@ function Remove-NsxEdgeCertificate{ process { if ( $confirm ) { - $message = "Certificate removal is permanent." + $message = "Certificate removal is permanent." $question = "Proceed with removal of Certificate $($Certificate.objectId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -16100,9 +16249,9 @@ function Remove-NsxEdgeCertificate{ if ($decision -eq 0) { $URI = "/api/2.0/services/truststore/certificate/$($certificate.objectId)" - Write-Progress -activity "Remove Certificate $($Csr.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Certificate $($Csr.Name)" -completed + Write-Progress -Activity "Remove Certificate $($Csr.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Certificate $($Csr.Name)" -Completed } } @@ -16139,9 +16288,9 @@ function Get-NsxSslVpn { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin { @@ -16165,63 +16314,63 @@ function Set-NsxSslVpn { #To do, portal customisation, server ip config... - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$Enabled, - [Parameter (Mandatory=$False)] - [switch]$EnableCompression, - [Parameter (Mandatory=$False)] - [switch]$ForceVirtualKeyboard, - [Parameter (Mandatory=$False)] - [switch]$RandomizeVirtualkeys, - [Parameter (Mandatory=$False)] - [switch]$PreventMultipleLogon, - [Parameter (Mandatory=$False)] - [string]$ClientNotification, - [Parameter (Mandatory=$False)] - [switch]$EnablePublicUrlAccess=$False, - [Parameter (Mandatory=$False)] - [int]$ForcedTimeout, - [Parameter (Mandatory=$False)] - [int]$SessionIdleTimeout, - [Parameter (Mandatory=$False)] - [switch]$ClientAutoReconnect, - [Parameter (Mandatory=$False)] - [switch]$ClientUpgradeNotification, - [Parameter (Mandatory=$False)] - [switch]$EnableLogging, - [Parameter (Mandatory=$False)] - [ValidateSet("emergency","alert","critical","error","warning","notice","info","debug")] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - [ipaddress]$ServerAddress, - [Parameter (Mandatory=$False)] - [int]$ServerPort, - [Parameter (Mandatory=$False)] - [string]$CertificateID, - [Parameter (Mandatory=$False)] - [switch]$Enable_AES128_SHA, - [Parameter (Mandatory=$False)] - [switch]$Enable_AES256_SHA, - [Parameter (Mandatory=$False)] - [switch]$Enable_DES_CBC3_SHA, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$Enabled, + [Parameter (Mandatory = $False)] + [switch]$EnableCompression, + [Parameter (Mandatory = $False)] + [switch]$ForceVirtualKeyboard, + [Parameter (Mandatory = $False)] + [switch]$RandomizeVirtualkeys, + [Parameter (Mandatory = $False)] + [switch]$PreventMultipleLogon, + [Parameter (Mandatory = $False)] + [string]$ClientNotification, + [Parameter (Mandatory = $False)] + [switch]$EnablePublicUrlAccess = $False, + [Parameter (Mandatory = $False)] + [int]$ForcedTimeout, + [Parameter (Mandatory = $False)] + [int]$SessionIdleTimeout, + [Parameter (Mandatory = $False)] + [switch]$ClientAutoReconnect, + [Parameter (Mandatory = $False)] + [switch]$ClientUpgradeNotification, + [Parameter (Mandatory = $False)] + [switch]$EnableLogging, + [Parameter (Mandatory = $False)] + [ValidateSet("emergency", "alert", "critical", "error", "warning", "notice", "info", "debug")] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + [ipaddress]$ServerAddress, + [Parameter (Mandatory = $False)] + [int]$ServerPort, + [Parameter (Mandatory = $False)] + [string]$CertificateID, + [Parameter (Mandatory = $False)] + [switch]$Enable_AES128_SHA, + [Parameter (Mandatory = $False)] + [switch]$Enable_AES256_SHA, + [Parameter (Mandatory = $False)] + [switch]$Enable_DES_CBC3_SHA, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - if (($EnablePublicUrlAccess -eq $True) -and ([version]$Connection.version -ge [version]"6.3.0")){ + if (($EnablePublicUrlAccess -eq $True) -and ([version]$Connection.version -ge [version]"6.3.0")) { Write-Warning "PublicURL feature has been deprecated in the 6.3.X release. It has not been enabled." $EnablePublicUrlAccess = $False } @@ -16229,13 +16378,13 @@ function Set-NsxSslVpn { process { - #Create private xml element + #Create private xml element $_EdgeSslVpn = $SslVpn.CloneNode($true) #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeSslVpn.edgeId - $_EdgeSslVpn.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -Query 'descendant::edgeId')) ) | out-null + $_EdgeSslVpn.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -16284,12 +16433,11 @@ function Set-NsxSslVpn { $PsBoundParameters.ContainsKey("ServerPort") -or $PsBoundParameters.ContainsKey("Enable_DES_CBC3_SHA") -or $PsBoundParameters.ContainsKey("Enable_AES128_SHA") -or - $PsBoundParameters.ContainsKey("Enable_AES256_SHA")) - { + $PsBoundParameters.ContainsKey("Enable_AES256_SHA")) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -Query 'descendant::serverSettings') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -query 'descendant::serverSettings') ) { [System.Xml.XmlElement]$serverSettings = $_EdgeSslVpn.ownerDocument.CreateElement('serverSettings') - $_EdgeSslVpn.AppendChild($serverSettings) | out-null + $_EdgeSslVpn.AppendChild($serverSettings) | Out-Null } else { [System.Xml.XmlElement]$ServerSettings = $_EdgeSslVpn.serverSettings @@ -16297,15 +16445,15 @@ function Set-NsxSslVpn { if ( $PsBoundParameters.ContainsKey("ServerAddress")) { #Set ServerAddress - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $serverSettings -Query 'descendant::serverAddresses') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $serverSettings -query 'descendant::serverAddresses') ) { [System.Xml.XmlElement]$serverAddresses = $_EdgeSslVpn.ownerDocument.CreateElement('serverAddresses') - $serverSettings.AppendChild($serverAddresses) | out-null + $serverSettings.AppendChild($serverAddresses) | Out-Null } else { [System.Xml.XmlElement]$serverAddresses = $serverSettings.serverAddresses } - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $serverAddresses -Query 'descendant::ipAddress') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $serverAddresses -query 'descendant::ipAddress') ) { Add-XmlElement -xmlRoot $serverAddresses -xmlElementName "ipAddress" -xmlElementText $($ServerAddress.IPAddresstoString) } else { @@ -16315,7 +16463,7 @@ function Set-NsxSslVpn { if ( $PsBoundParameters.ContainsKey("ServerPort")) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $serverSettings -Query 'descendant::port') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $serverSettings -query 'descendant::port') ) { Add-XmlElement -xmlRoot $serverSettings -xmlElementName "port" -xmlElementText $ServerPort.ToString() } else { @@ -16325,7 +16473,7 @@ function Set-NsxSslVpn { if ( $PsBoundParameters.ContainsKey("CertificateID")) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $serverSettings -Query 'descendant::certificateId') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $serverSettings -query 'descendant::certificateId') ) { Add-XmlElement -xmlRoot $serverSettings -xmlElementName "certificateId" -xmlElementText $CertificateID } else { @@ -16337,41 +16485,41 @@ function Set-NsxSslVpn { $PsBoundParameters.ContainsKey("Enable_AES128_SHA") -or $PsBoundParameters.ContainsKey("Enable_AES256_SHA")) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ServerSettings -Query 'descendant::cipherList') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ServerSettings -query 'descendant::cipherList') ) { [System.Xml.XmlElement]$cipherList = $serverSettings.ownerDocument.CreateElement('cipherList') - $serverSettings.AppendChild($cipherList) | out-null + $serverSettings.AppendChild($cipherList) | Out-Null } else { [System.Xml.XmlElement]$cipherList = $serverSettings.cipherList } if ( $PsBoundParameters.ContainsKey("Enable_DES_CBC3_SHA") ) { - $cipher = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $cipherList -Query "descendant::cipher") | where-object { $_.'#Text' -eq 'DES-CBC3-SHA'} + $cipher = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $cipherList -query "descendant::cipher") | Where-Object { $_.'#Text' -eq 'DES-CBC3-SHA' } if ( ( -not $cipher ) -and $Enable_DES_CBC3_SHA ) { Add-XmlElement -xmlRoot $cipherList -xmlElementName "cipher" -xmlElementText "DES-CBC3-SHA" } elseif ( $cipher -and ( -not $Enable_DES_CBC3_SHA )) { - $cipherList.RemoveChild( $cipher )| out-null + $cipherList.RemoveChild( $cipher ) | Out-Null } } if ( $PsBoundParameters.ContainsKey("Enable_AES128_SHA") ) { - $cipher = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $cipherList -Query "descendant::cipher") | where-object { $_.'#Text' -eq 'AES128-SHA'} + $cipher = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $cipherList -query "descendant::cipher") | Where-Object { $_.'#Text' -eq 'AES128-SHA' } if ( ( -not $cipher ) -and $Enable_AES128_SHA ) { Add-XmlElement -xmlRoot $cipherList -xmlElementName "cipher" -xmlElementText "AES128-SHA" } elseif ( $cipher -and ( -not $Enable_AES128_SHA )) { - $CipherList.RemoveChild( $cipher )| out-null + $CipherList.RemoveChild( $cipher ) | Out-Null } } if ( $PsBoundParameters.ContainsKey("Enable_AES256_SHA") ) { - $cipher = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $cipherList -Query "descendant::cipher") | where-object { $_.'#Text' -eq 'AES256-SHA'} + $cipher = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $cipherList -query "descendant::cipher") | Where-Object { $_.'#Text' -eq 'AES256-SHA' } if ( ( -not $cipher ) -and $Enable_AES256_SHA ) { Add-XmlElement -xmlRoot $cipherList -xmlElementName "cipher" -xmlElementText "AES256-SHA" } elseif ( $cipher -and ( -not $Enable_AES256_SHA )) { - $CipherList.RemoveChild( $cipher ) | out-null + $CipherList.RemoveChild( $cipher ) | Out-Null } } } @@ -16381,7 +16529,7 @@ function Set-NsxSslVpn { $body = $_EdgeSslVpn.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway SSL VPN update will modify existing Edge configuration." + $message = "Edge Services Gateway SSL VPN update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -16391,10 +16539,10 @@ function Set-NsxSslVpn { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxSslVpn + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxSslVpn } } @@ -16402,51 +16550,51 @@ function Set-NsxSslVpn { } function New-NsxSslVpnAuthServer { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Incorrect assertion by ScriptAnalyser. - - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$False)] - [ValidateRange(1,63)] - [int]$PasswordMinLength=1, - [Parameter (Mandatory=$False)] - [ValidateRange(1,63)] - [int]$PasswordMaxLength=63, - [Parameter (Mandatory=$False)] - [ValidateRange(1,63)] - [int]$PasswordMinAlphabet=0, - [Parameter (Mandatory=$False)] - [ValidateRange(1,63)] - [int]$PasswordMinDigit=0, - [Parameter (Mandatory=$False)] - [ValidateRange(1,63)] - [int]$PasswordMinSpecialChar=0, - [Parameter (Mandatory=$False)] - [switch]$PasswordAllowUsernameInPassword=$false, - [Parameter (Mandatory=$False)] - [int]$PasswordLifetime=30, - [Parameter (Mandatory=$False)] - [int]$PasswordExpiryNotificationTime=25, - [Parameter (Mandatory=$False)] - [int]$PasswordLockoutRetryCount=3, - [Parameter (Mandatory=$False)] - [int]$PasswordLockoutRetryDuration=2, - [Parameter (Mandatory=$False)] - [int]$PasswordLockoutDuration=2, - [Parameter (Mandatory=$False)] - [ValidateSet("Local")] - [string]$ServerType="Local", - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - - ) - - Begin{} + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Incorrect assertion by ScriptAnalyser. + + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 63)] + [int]$PasswordMinLength = 1, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 63)] + [int]$PasswordMaxLength = 63, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 63)] + [int]$PasswordMinAlphabet = 0, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 63)] + [int]$PasswordMinDigit = 0, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 63)] + [int]$PasswordMinSpecialChar = 0, + [Parameter (Mandatory = $False)] + [switch]$PasswordAllowUsernameInPassword = $false, + [Parameter (Mandatory = $False)] + [int]$PasswordLifetime = 30, + [Parameter (Mandatory = $False)] + [int]$PasswordExpiryNotificationTime = 25, + [Parameter (Mandatory = $False)] + [int]$PasswordLockoutRetryCount = 3, + [Parameter (Mandatory = $False)] + [int]$PasswordLockoutRetryDuration = 2, + [Parameter (Mandatory = $False)] + [int]$PasswordLockoutDuration = 2, + [Parameter (Mandatory = $False)] + [ValidateSet("Local")] + [string]$ServerType = "Local", + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + + ) + + Begin {} Process { @@ -16456,10 +16604,10 @@ function New-NsxSslVpnAuthServer { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeSslVpn.edgeId - $_EdgeSslVpn.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -Query 'descendant::edgeId')) ) | out-null + $_EdgeSslVpn.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -query 'descendant::edgeId')) ) | Out-Null #Get the AuthServers node, and create a new PrimaryAuthServer in it. - $PrimaryAuthServers = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -Query 'descendant::authenticationConfiguration/passwordAuthentication/primaryAuthServers') + $PrimaryAuthServers = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeSslVpn -query 'descendant::authenticationConfiguration/passwordAuthentication/primaryAuthServers') Switch ( $ServerType ) { @@ -16467,7 +16615,7 @@ function New-NsxSslVpnAuthServer { #Like highlander, there can be only one! :) - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $PrimaryAuthServers -Query 'descendant::localAuthServer') ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PrimaryAuthServers -query 'descendant::localAuthServer') ) { throw "Local Authentication source already exists. Use Set-NsxEdgeSslVpnAuthServer to modify an existing server." } @@ -16475,12 +16623,12 @@ function New-NsxSslVpnAuthServer { #Construct the Local Server XML Element. $AuthServer = $PrimaryAuthServers.ownerDocument.CreateElement('com.vmware.vshield.edge.sslvpn.dto.LocalAuthServerDto') - $PrimaryAuthServers.AppendChild($AuthServer) | out-null + $PrimaryAuthServers.AppendChild($AuthServer) | Out-Null $PasswordPolicy = $AuthServer.ownerDocument.CreateElement('passwordPolicy') $AccountLockoutPolicy = $AuthServer.ownerDocument.CreateElement('accountLockoutPolicy') - $AuthServer.AppendChild($PasswordPolicy) | out-null - $AuthServer.AppendChild($AccountLockoutPolicy) | out-null + $AuthServer.AppendChild($PasswordPolicy) | Out-Null + $AuthServer.AppendChild($AccountLockoutPolicy) | Out-Null #No need to check if user specified as we are defaulting to the documented defaults for all props as per API guide. @@ -16503,15 +16651,15 @@ function New-NsxSslVpnAuthServer { $URI = "/api/4.0/edges/$EdgeId/sslvpn/config" $body = $_EdgeSslVpn.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed #Totally cheating here while we only support local auth server. Will have to augment this later... - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxSslVpn | Get-NsxSslVpnAuthServer -Servertype local + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxSslVpn | Get-NsxSslVpnAuthServer -ServerType local } - end{} + end {} } function Get-NsxSslVpnAuthServer { @@ -16542,12 +16690,12 @@ function Get-NsxSslVpnAuthServer { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$false,Position=1)] - [ValidateSet("local",IgnoreCase=$false)] - [string]$ServerType + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $false, Position = 1)] + [ValidateSet("local", IgnoreCase = $false)] + [string]$ServerType ) begin { @@ -16560,19 +16708,20 @@ function Get-NsxSslVpnAuthServer { #consistent readable output $_EdgeSslVpn = $SslVpn.CloneNode($True) - $PrimaryAuthenticationServers = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -Query 'descendant::authenticationConfiguration/passwordAuthentication/primaryAuthServers/*') + $PrimaryAuthenticationServers = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -query 'descendant::authenticationConfiguration/passwordAuthentication/primaryAuthServers/*') if ( $PrimaryAuthenticationServers ) { foreach ( $Server in $PrimaryAuthenticationServers ) { Add-XmlElement -xmlRoot $Server -xmlElementName "edgeId" -xmlElementText $SslVpn.EdgeId if ( $PsBoundParameters.ContainsKey('ServerType')) { - $Server | where-object { $_.authServerType -eq $ServerType } - } else { + $Server | Where-Object { $_.authServerType -eq $ServerType } + } + else { $Server } } } - $SecondaryAuthenticationServers = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -Query 'descendant::authenticationConfiguration/passwordAuthentication/secondaryAuthServers/*') + $SecondaryAuthenticationServers = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -query 'descendant::authenticationConfiguration/passwordAuthentication/secondaryAuthServers/*') if ( $SecondaryAuthenticationServers ) { foreach ( $Server in $SecondaryAuthenticationServers ) { @@ -16585,47 +16734,47 @@ function Get-NsxSslVpnAuthServer { end {} } -function New-NsxSslVpnUser{ - - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Unable to remove without breaking backward compatibilty. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$UserName, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$Password, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$FirstName, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$LastName, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$Description, - [Parameter (Mandatory=$False)] - [switch]$DisableUser=$False, - [Parameter (Mandatory=$False)] - [switch]$PasswordNeverExpires=$False, - [Parameter (Mandatory=$False)] - [switch]$AllowPasswordChange=$True, - [Parameter (Mandatory=$False)] - [switch]$ForcePasswordChangeOnNextLogin, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - - ) - - Begin{} +function New-NsxSslVpnUser { + + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Unable to remove without breaking backward compatibilty. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$UserName, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Password, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$FirstName, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$LastName, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$Description, + [Parameter (Mandatory = $False)] + [switch]$DisableUser = $False, + [Parameter (Mandatory = $False)] + [switch]$PasswordNeverExpires = $False, + [Parameter (Mandatory = $False)] + [switch]$AllowPasswordChange = $True, + [Parameter (Mandatory = $False)] + [switch]$ForcePasswordChangeOnNextLogin, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + + ) + + Begin {} Process { @@ -16642,7 +16791,7 @@ function New-NsxSslVpnUser{ Add-XmlElement -xmlRoot $User -xmlElementName "passwordNeverExpires" -xmlElementText $PasswordNeverExpires.ToString().ToLower() if ( $AllowPasswordChange ) { $xmlAllowChangePassword = $User.OwnerDocument.CreateElement('allowChangePassword') - $User.AppendChild($xmlAllowChangePassword) | out-null + $User.AppendChild($xmlAllowChangePassword) | Out-Null Add-XmlElement -xmlRoot $xmlAllowChangePassword -xmlElementName "changePasswordOnNextLogin" -xmlElementText $AllowPasswordChange.ToString().ToLower() } elseif ( $ForcePasswordChangeOnNextLogin ) { @@ -16663,11 +16812,11 @@ function New-NsxSslVpnUser{ $URI = "/api/4.0/edges/$edgeId/sslvpn/config/auth/localserver/users/" $body = $User.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed - Get-NsxEdge -objectId $EdgeId -connection $connection| Get-NsxSslVpn | Get-NsxSslVpnUser -UserName $UserName + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxSslVpn | Get-NsxSslVpnUser -UserName $UserName } } @@ -16675,11 +16824,11 @@ function Get-NsxSslVpnUser { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$false,Position=1)] - [string]$UserName + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $false, Position = 1)] + [string]$UserName ) begin { @@ -16693,12 +16842,12 @@ function Get-NsxSslVpnUser { $_EdgeSslVpn = $SslVpn.CloneNode($True) - $Users = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -Query 'descendant::users/*') + $Users = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -query 'descendant::users/*') if ( $Users ) { foreach ( $User in $Users ) { Add-XmlElement -xmlRoot $User -xmlElementName "edgeId" -xmlElementText $SslVpn.EdgeId if ( $PsBoundParameters.ContainsKey('UserName')) { - $User | where-object { $_.UserId -eq $UserName } + $User | Where-Object { $_.UserId -eq $UserName } } else { $User @@ -16711,18 +16860,18 @@ function Get-NsxSslVpnUser { } function Remove-NsxSslVpnUser { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpnUser $_ })] - [System.Xml.XmlElement]$SslVpnUser, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpnUser $_ })] + [System.Xml.XmlElement]$SslVpnUser, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -16737,7 +16886,7 @@ function Remove-NsxSslVpnUser { $URI = "/api/4.0/edges/$edgeId/sslvpn/config/auth/localserver/users/$userId" if ( $confirm ) { - $message = "User deletion is permanent." + $message = "User deletion is permanent." $question = "Proceed with deletion of user $($SslVpnUser.UserId) ($($userId)) from edge $($edgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -16747,9 +16896,9 @@ function Remove-NsxSslVpnUser { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Deleting user $($SslVpnUser.UserId) ($($userId)) from edge $edgeId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Deleting user $($SslVpnUser.UserId) ($($userId)) from edge $edgeId" -completed + Write-Progress -Activity "Deleting user $($SslVpnUser.UserId) ($($userId)) from edge $edgeId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Deleting user $($SslVpnUser.UserId) ($($userId)) from edge $edgeId" -Completed } } @@ -16758,42 +16907,42 @@ function Remove-NsxSslVpnUser { function New-NsxSslVpnIpPool { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$IpRange, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [ipaddress]$Netmask, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [ipaddress]$Gateway, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [ipAddress]$PrimaryDnsServer, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [ipAddress]$SecondaryDnsServer, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$DnsSuffix, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [ipAddress]$WinsServer, - [Parameter (Mandatory=$False)] - [switch]$Enabled=$True, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) - - Begin{} + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$IpRange, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [ipaddress]$Netmask, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [ipaddress]$Gateway, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [ipAddress]$PrimaryDnsServer, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [ipAddress]$SecondaryDnsServer, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$DnsSuffix, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [ipAddress]$WinsServer, + [Parameter (Mandatory = $False)] + [switch]$Enabled = $True, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) + + Begin {} Process { @@ -16810,7 +16959,7 @@ function New-NsxSslVpnIpPool { # Optionals... if ( $PsBoundParameters.ContainsKey('Description')) { - Add-XmlElement -xmlRoot $IpAddressPool -xmlElementName "description" -xmlElementText $Description.ToString() + Add-XmlElement -xmlRoot $IpAddressPool -xmlElementName "description" -xmlElementText $Description.ToString() } if ( $PsBoundParameters.ContainsKey('PrimaryDNSServer')) { Add-XmlElement -xmlRoot $IpAddressPool -xmlElementName "primaryDns" -xmlElementText $($PrimaryDnsServer.IpAddressToString) @@ -16832,11 +16981,11 @@ function New-NsxSslVpnIpPool { $URI = "/api/4.0/edges/$edgeId/sslvpn/config/client/networkextension/ippools/" $body = $IpAddressPool.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed - Get-NsxEdge -objectId $EdgeId -connection $connection| Get-NsxSslVpn | Get-NsxSslVpnIpPool -IpRange $IpRange + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxSslVpn | Get-NsxSslVpnIpPool -IpRange $IpRange } } @@ -16844,11 +16993,11 @@ function Get-NsxSslVpnIpPool { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$false,Position=1)] - [string]$IpRange + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $false, Position = 1)] + [string]$IpRange ) begin { @@ -16862,12 +17011,12 @@ function Get-NsxSslVpnIpPool { $_EdgeSslVpn = $SslVpn.CloneNode($True) - $IpPools = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -Query 'descendant::ipAddressPools/*') + $IpPools = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -query 'descendant::ipAddressPools/*') if ( $IpPools ) { foreach ( $IpPool in $IpPools ) { Add-XmlElement -xmlRoot $IpPool -xmlElementName "edgeId" -xmlElementText $SslVpn.EdgeId if ( $PsBoundParameters.ContainsKey('IpRange')) { - $IpPool | where-object { $_.ipRange -eq $IpRange } + $IpPool | Where-Object { $_.ipRange -eq $IpRange } } else { $IpPool @@ -16881,18 +17030,18 @@ function Get-NsxSslVpnIpPool { function Remove-NsxSslVpnIpPool { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpnIpPool $_ })] - [System.Xml.XmlElement]$SslVpnIpPool, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpnIpPool $_ })] + [System.Xml.XmlElement]$SslVpnIpPool, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -16906,7 +17055,7 @@ function Remove-NsxSslVpnIpPool { $URI = "/api/4.0/edges/$edgeId/sslvpn/config/client/networkextension/ippools/$poolId" if ( $confirm ) { - $message = "Ip Pool deletion is permanent." + $message = "Ip Pool deletion is permanent." $question = "Proceed with deletion of pool $($SslVpnIpPool.IpRange) ($($poolId)) from edge $($edgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -16916,9 +17065,9 @@ function Remove-NsxSslVpnIpPool { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Deleting pool $($SslVpnIpPool.IpRange) ($($poolId)) from edge $edgeId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Deleting pool $($SslVpnIpPool.IpRange) ($($poolId)) from edge $edgeId" -completed + Write-Progress -Activity "Deleting pool $($SslVpnIpPool.IpRange) ($($poolId)) from edge $edgeId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Deleting pool $($SslVpnIpPool.IpRange) ($($poolId)) from edge $edgeId" -Completed } } @@ -16927,34 +17076,34 @@ function Remove-NsxSslVpnIpPool { function New-NsxSslVpnPrivateNetwork { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$Network, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$Ports, - [Parameter (Mandatory=$False)] - [switch]$BypassTunnel=$False, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$Description, - [Parameter (Mandatory=$False)] - [switch]$OptimiseTcp=$True, - [Parameter (Mandatory=$False)] - [switch]$Enabled=$True, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) - - Begin{} + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Network, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$Ports, + [Parameter (Mandatory = $False)] + [switch]$BypassTunnel = $False, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$Description, + [Parameter (Mandatory = $False)] + [switch]$OptimiseTcp = $True, + [Parameter (Mandatory = $False)] + [switch]$Enabled = $True, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) + + Begin {} Process { @@ -16969,18 +17118,18 @@ function New-NsxSslVpnPrivateNetwork { # Optionals... if ( $PsBoundParameters.ContainsKey('Description')) { - Add-XmlElement -xmlRoot $PrivateNetwork -xmlElementName "description" -xmlElementText $Description.ToString() + Add-XmlElement -xmlRoot $PrivateNetwork -xmlElementName "description" -xmlElementText $Description.ToString() } if ( -not $BypassTunnel ) { [system.Xml.XmlElement]$sendOverTunnel = $PrivateNetwork.ownerDocument.CreateElement('sendOverTunnel') - $PrivateNetwork.AppendChild($SendOverTunnel) | out-null + $PrivateNetwork.AppendChild($SendOverTunnel) | Out-Null Add-XmlElement -xmlRoot $SendOverTunnel -xmlElementName "optimize" -xmlElementText $OptimiseTcp.ToString().ToLower() if ( $PsBoundParameters.ContainsKey('Ports')) { Add-XmlElement -xmlRoot $SendOverTunnel -xmlElementName "ports" -xmlElementText $Ports.ToString() } } elseif ( $OptimiseTcp ) { - write-warning "TCP Optimisation is not applicable when tunnel bypass is enabled." + Write-Warning "TCP Optimisation is not applicable when tunnel bypass is enabled." } elseif ( $PsBoundParameters.ContainsKey('Ports') ) { throw "Unable to specify ports when tunnel bypass is enabled." @@ -16993,11 +17142,11 @@ function New-NsxSslVpnPrivateNetwork { $URI = "/api/4.0/edges/$edgeId/sslvpn/config/client/networkextension/privatenetworks" $body = $PrivateNetwork.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed - Get-NsxEdge -objectId $EdgeId -connection $connection| Get-NsxSslVpn | Get-NsxSslVpnPrivateNetwork -Network $Network + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxSslVpn | Get-NsxSslVpnPrivateNetwork -Network $Network } } @@ -17005,11 +17154,11 @@ function Get-NsxSslVpnPrivateNetwork { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$false,Position=1)] - [string]$Network + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $false, Position = 1)] + [string]$Network ) begin { @@ -17023,12 +17172,12 @@ function Get-NsxSslVpnPrivateNetwork { $_EdgeSslVpn = $SslVpn.CloneNode($True) - $Networks = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -Query 'descendant::privateNetworks/*') + $Networks = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -query 'descendant::privateNetworks/*') if ( $Networks ) { foreach ( $Net in $Networks ) { Add-XmlElement -xmlRoot $Net -xmlElementName "edgeId" -xmlElementText $SslVpn.EdgeId if ( $PsBoundParameters.ContainsKey('Network')) { - $Net | where-object { $_.Network -eq $Network } + $Net | Where-Object { $_.Network -eq $Network } } else { $Net @@ -17042,18 +17191,18 @@ function Get-NsxSslVpnPrivateNetwork { function Remove-NsxSslVpnPrivateNetwork { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpnPrivateNetwork $_ })] - [System.Xml.XmlElement]$SslVpnPrivateNetwork, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpnPrivateNetwork $_ })] + [System.Xml.XmlElement]$SslVpnPrivateNetwork, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -17067,7 +17216,7 @@ function Remove-NsxSslVpnPrivateNetwork { $URI = "/api/4.0/edges/$edgeId/sslvpn/config/client/networkextension/privatenetworks/$networkId" if ( $confirm ) { - $message = "Private network deletion is permanent." + $message = "Private network deletion is permanent." $question = "Proceed with deletion of network $($SslVpnPrivateNetwork.Network) ($($networkId)) from edge $($edgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -17077,9 +17226,9 @@ function Remove-NsxSslVpnPrivateNetwork { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Deleting network $($SslVpnPrivateNetwork.Network) ($($networkId)) from edge $edgeId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Deleting network $($SslVpnPrivateNetwork.Network) ($($networkId)) from edge $edgeId" -completed + Write-Progress -Activity "Deleting network $($SslVpnPrivateNetwork.Network) ($($networkId)) from edge $edgeId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Deleting network $($SslVpnPrivateNetwork.Network) ($($networkId)) from edge $edgeId" -Completed } } @@ -17088,50 +17237,50 @@ function Remove-NsxSslVpnPrivateNetwork { function New-NsxSslVpnClientInstallationPackage { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$True)] - [string]$Name, - [Parameter (Mandatory=$True)] - [ipAddress[]]$Gateway, - [Parameter (Mandatory=$False)] - [ValidateRange(1,65535)] - [Int]$Port, - [Parameter (Mandatory=$False)] - [switch]$CreateLinuxClient, - [Parameter (Mandatory=$False)] - [switch]$CreateMacClient, - [Parameter (Mandatory=$False)] - [string]$Description, - [Parameter (Mandatory=$False)] - [switch]$StartClientOnLogon, - [Parameter (Mandatory=$False)] - [switch]$HideSystrayIcon, - [Parameter (Mandatory=$False)] - [switch]$RememberPassword, - [Parameter (Mandatory=$False)] - [switch]$SilentModeOperation, - [Parameter (Mandatory=$False)] - [switch]$SilentModeInstallation, - [Parameter (Mandatory=$False)] - [switch]$HideNetworkAdaptor, - [Parameter (Mandatory=$False)] - [switch]$CreateDesktopIcon, - [Parameter (Mandatory=$False)] - [switch]$EnforceServerSecurityCertValidation, - [Parameter (Mandatory=$False)] - [switch]$Enabled=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) - - Begin{} + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $True)] + [string]$Name, + [Parameter (Mandatory = $True)] + [ipAddress[]]$Gateway, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 65535)] + [Int]$Port, + [Parameter (Mandatory = $False)] + [switch]$CreateLinuxClient, + [Parameter (Mandatory = $False)] + [switch]$CreateMacClient, + [Parameter (Mandatory = $False)] + [string]$Description, + [Parameter (Mandatory = $False)] + [switch]$StartClientOnLogon, + [Parameter (Mandatory = $False)] + [switch]$HideSystrayIcon, + [Parameter (Mandatory = $False)] + [switch]$RememberPassword, + [Parameter (Mandatory = $False)] + [switch]$SilentModeOperation, + [Parameter (Mandatory = $False)] + [switch]$SilentModeInstallation, + [Parameter (Mandatory = $False)] + [switch]$HideNetworkAdaptor, + [Parameter (Mandatory = $False)] + [switch]$CreateDesktopIcon, + [Parameter (Mandatory = $False)] + [switch]$EnforceServerSecurityCertValidation, + [Parameter (Mandatory = $False)] + [switch]$Enabled = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) + + Begin {} Process { @@ -17143,10 +17292,10 @@ function New-NsxSslVpnClientInstallationPackage { #gatewayList element [system.Xml.XmlElement]$gatewayList = $clientInstallPackage.ownerDocument.CreateElement('gatewayList') - $clientInstallPackage.AppendChild($gatewayList) | out-null + $clientInstallPackage.AppendChild($gatewayList) | Out-Null foreach ($gatewayitem in $gateway) { [system.Xml.XmlElement]$gatewayNode = $gatewayList.ownerDocument.CreateElement('gateway') - $gatewayList.AppendChild($gatewayNode) | out-null + $gatewayList.AppendChild($gatewayNode) | Out-Null Add-XmlElement -xmlRoot $gatewayNode -xmlElementName "hostName" -xmlElementText $gatewayitem if ( $PSBoundParameters.ContainsKey('port')) { Add-XmlElement -xmlRoot $gatewayNode -xmlElementName "port" -xmlElementText $Port @@ -17159,47 +17308,47 @@ function New-NsxSslVpnClientInstallationPackage { # Optionals... if ( $PsBoundParameters.ContainsKey('StartClientOnLogon')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "startClientOnLogon" -xmlElementText $StartClientOnLogon.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "startClientOnLogon" -xmlElementText $StartClientOnLogon.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('hideSystrayIcon')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "hideSystrayIcon" -xmlElementText $hideSystrayIcon.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "hideSystrayIcon" -xmlElementText $hideSystrayIcon.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('rememberPassword')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "rememberPassword" -xmlElementText $rememberPassword.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "rememberPassword" -xmlElementText $rememberPassword.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('silentModeOperation')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "silentModeOperation" -xmlElementText $silentModeOperation.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "silentModeOperation" -xmlElementText $silentModeOperation.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('silentModeInstallation')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "silentModeInstallation" -xmlElementText $silentModeInstallation.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "silentModeInstallation" -xmlElementText $silentModeInstallation.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('hideNetworkAdaptor')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "hideNetworkAdaptor" -xmlElementText $hideNetworkAdaptor.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "hideNetworkAdaptor" -xmlElementText $hideNetworkAdaptor.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('createDesktopIcon')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "createDesktopIcon" -xmlElementText $createDesktopIcon.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "createDesktopIcon" -xmlElementText $createDesktopIcon.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('enforceServerSecurityCertValidation')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "enforceServerSecurityCertValidation" -xmlElementText $enforceServerSecurityCertValidation.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "enforceServerSecurityCertValidation" -xmlElementText $enforceServerSecurityCertValidation.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('createLinuxClient')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "createLinuxClient" -xmlElementText $createLinuxClient.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "createLinuxClient" -xmlElementText $createLinuxClient.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('createMacClient')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "createMacClient" -xmlElementText $createMacClient.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "createMacClient" -xmlElementText $createMacClient.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey('description')) { - Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "description" -xmlElementText $description.ToString().ToLower() + Add-XmlElement -xmlRoot $clientInstallPackage -xmlElementName "description" -xmlElementText $description.ToString().ToLower() } $URI = "/api/4.0/edges/$edgeId/sslvpn/config/client/networkextension/installpackages/" $body = $clientInstallPackage.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed - Get-NsxEdge -objectId $EdgeId -connection $connection| Get-NsxSslVpn | Get-NsxSslVpnClientInstallationPackage -Name $Name + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxSslVpn | Get-NsxSslVpnClientInstallationPackage -Name $Name } } @@ -17207,11 +17356,11 @@ function Get-NsxSslVpnClientInstallationPackage { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$false,Position=1)] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $false, Position = 1)] + [string]$Name ) begin { @@ -17225,12 +17374,12 @@ function Get-NsxSslVpnClientInstallationPackage { $_EdgeSslVpn = $SslVpn.CloneNode($True) - $Packages = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -Query 'descendant::clientInstallPackages/*') + $Packages = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_EdgeSslVpn -query 'descendant::clientInstallPackages/*') if ( $Packages ) { foreach ( $Package in $Packages ) { Add-XmlElement -xmlRoot $Package -xmlElementName "edgeId" -xmlElementText $SslVpn.EdgeId if ( $PsBoundParameters.ContainsKey('Name')) { - $Package | where-object { $_.ProfileName -eq $Name } + $Package | Where-Object { $_.ProfileName -eq $Name } } else { $Package @@ -17244,19 +17393,19 @@ function Get-NsxSslVpnClientInstallationPackage { function Remove-NsxSslVpnClientInstallationPackage { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeSslVpnClientPackage $_ })] - [System.Xml.XmlElement]$EdgeSslVpnClientPackage, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeSslVpnClientPackage $_ })] + [System.Xml.XmlElement]$EdgeSslVpnClientPackage, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -17270,7 +17419,7 @@ function Remove-NsxSslVpnClientInstallationPackage { $URI = "/api/4.0/edges/$edgeId/sslvpn/config/client/networkextension/installpackages/$packageId" if ( $confirm ) { - $message = "Installation Package deletion is permanent." + $message = "Installation Package deletion is permanent." $question = "Proceed with deletion of installation package $($EdgeSslVpnClientPackage.profileName) ($($packageId)) from edge $($edgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -17280,9 +17429,9 @@ function Remove-NsxSslVpnClientInstallationPackage { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Deleting install package $($EdgeSslVpnClientPackage.profileName) ($($packageId)) from edge $edgeId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Deleting install package $($EdgeSslVpnClientPackage.profileName) ($($packageId)) from edge $edgeId" -completed + Write-Progress -Activity "Deleting install package $($EdgeSslVpnClientPackage.profileName) ($($packageId)) from edge $edgeId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Deleting install package $($EdgeSslVpnClientPackage.profileName) ($($packageId)) from edge $edgeId" -Completed } } @@ -17323,28 +17472,28 @@ function Remove-NsxSslVpn { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #NSX Edge SslVpn to remove - [ValidateScript({ ValidateEdgeSslVpn $_ })] - [System.Xml.XmlElement]$SslVpn, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #NSX Edge SslVpn to remove + [ValidateScript( { ValidateEdgeSslVpn $_ })] + [System.Xml.XmlElement]$SslVpn, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } } @@ -17352,7 +17501,7 @@ function Remove-NsxSslVpn { process { $edgeId = $SslVpn.edgeId if ( -not ( $Noconfirm )) { - $message = "Edge SslVpn removal is permanent." + $message = "Edge SslVpn removal is permanent." $question = "Proceed with removal of Edge SslVpn $($EdgeId) ?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -17362,9 +17511,9 @@ function Remove-NsxSslVpn { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/4.0/edges/$($EdgeId)/sslvpn/config" - Write-Progress -activity "Remove SSL VPN for Edge $($EdgeId)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Remove SSL VPN for Edge $($EdgeId)" -completed + Write-Progress -Activity "Remove SSL VPN for Edge $($EdgeId)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove SSL VPN for Edge $($EdgeId)" -Completed } } @@ -17421,52 +17570,52 @@ function Set-NsxEdgeRouting { Disable OSPF Route Redistribution without confirmation. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$EnableOspf, - [Parameter (Mandatory=$False)] - [switch]$EnableBgp, - [Parameter (Mandatory=$False)] - [IpAddress]$RouterId, - [Parameter (Mandatory=$False)] - [ValidateRange(0,65535)] - [int]$LocalAS, - [Parameter (Mandatory=$False)] - [switch]$EnableEcmp, - [Parameter (Mandatory=$False)] - [switch]$EnableOspfRouteRedistribution, - [Parameter (Mandatory=$False)] - [switch]$EnableBgpRouteRedistribution, - [Parameter (Mandatory=$False)] - [switch]$EnableLogging, - [Parameter (Mandatory=$False)] - [ValidateSet("emergency","alert","critical","error","warning","notice","info","debug")] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - [ValidateRange(0,200)] - [int]$DefaultGatewayVnic, - [Parameter (Mandatory=$False)] - [ValidateRange(0,9128)] - [int]$DefaultGatewayMTU, - [Parameter (Mandatory=$False)] - [string]$DefaultGatewayDescription, - [Parameter (Mandatory=$False)] - [ipAddress]$DefaultGatewayAddress, - [Parameter (Mandatory=$False)] - [ValidateRange(0,255)] - [int]$DefaultGatewayAdminDistance, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$EnableOspf, + [Parameter (Mandatory = $False)] + [switch]$EnableBgp, + [Parameter (Mandatory = $False)] + [IpAddress]$RouterId, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 65535)] + [int]$LocalAS, + [Parameter (Mandatory = $False)] + [switch]$EnableEcmp, + [Parameter (Mandatory = $False)] + [switch]$EnableOspfRouteRedistribution, + [Parameter (Mandatory = $False)] + [switch]$EnableBgpRouteRedistribution, + [Parameter (Mandatory = $False)] + [switch]$EnableLogging, + [Parameter (Mandatory = $False)] + [ValidateSet("emergency", "alert", "critical", "error", "warning", "notice", "info", "debug")] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 200)] + [int]$DefaultGatewayVnic, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 9128)] + [int]$DefaultGatewayMTU, + [Parameter (Mandatory = $False)] + [string]$DefaultGatewayDescription, + [Parameter (Mandatory = $False)] + [ipAddress]$DefaultGatewayAddress, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 255)] + [int]$DefaultGatewayAdminDistance, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -17481,14 +17630,14 @@ function Set-NsxEdgeRouting { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. if ( $PsBoundParameters.ContainsKey('EnableOSPF') -or $PsBoundParameters.ContainsKey('EnableBGP') ) { $xmlGlobalConfig = $_EdgeRouting.routingGlobalConfig - $xmlRouterId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -Query 'descendant::routerId') + $xmlRouterId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -query 'descendant::routerId') if ( $EnableOSPF -or $EnableBGP ) { if ( -not ($xmlRouterId -or $PsBoundParameters.ContainsKey("RouterId"))) { #Existing config missing and no new value set... @@ -17500,7 +17649,7 @@ function Set-NsxEdgeRouting { if ($xmlRouterId) { $xmlRouterId = $RouterId.IPAddresstoString } - else{ + else { Add-XmlElement -xmlRoot $xmlGlobalConfig -xmlElementName "routerId" -xmlElementText $RouterId.IPAddresstoString } } @@ -17508,14 +17657,14 @@ function Set-NsxEdgeRouting { } if ( $PsBoundParameters.ContainsKey('EnableOSPF')) { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::ospf') if ( -not $ospf ) { #ospf node does not exist. [System.XML.XMLElement]$ospf = $_EdgeRouting.ownerDocument.CreateElement("ospf") - $_EdgeRouting.appendChild($ospf) | out-null + $_EdgeRouting.appendChild($ospf) | Out-Null } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::enabled')) { #Enabled element exists. Update it. $ospf.enabled = $EnableOSPF.ToString().ToLower() } @@ -17528,15 +17677,15 @@ function Set-NsxEdgeRouting { if ( $PsBoundParameters.ContainsKey('EnableBGP')) { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::bgp') if ( -not $bgp ) { #bgp node does not exist. [System.XML.XMLElement]$bgp = $_EdgeRouting.ownerDocument.CreateElement("bgp") - $_EdgeRouting.appendChild($bgp) | out-null + $_EdgeRouting.appendChild($bgp) | Out-Null } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::enabled')) { #Enabled element exists. Update it. $bgp.enabled = $EnableBGP.ToString().ToLower() } @@ -17546,8 +17695,8 @@ function Set-NsxEdgeRouting { } if ( $PsBoundParameters.ContainsKey("LocalAS")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::localAS')) { - #LocalAS element exists, update it. + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::localAS')) { + #LocalAS element exists, update it. $bgp.localAS = $LocalAS.ToString() } else { @@ -17555,7 +17704,7 @@ function Set-NsxEdgeRouting { Add-XmlElement -xmlRoot $bgp -xmlElementName "localAS" -xmlElementText $LocalAS.ToString() } } - elseif ( (-not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::localAS')) -and $EnableBGP )) { + elseif ( (-not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::localAS')) -and $EnableBGP )) { throw "Existing configuration has no Local AS number specified. Local AS must be set to enable BGP." } @@ -17571,7 +17720,7 @@ function Set-NsxEdgeRouting { } if ( $PsBoundParameters.ContainsKey("EnableBgpRouteRedistribution")) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'child::bgp/redistribution/enabled') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'child::bgp/redistribution/enabled') ) { throw "BGP must have been configured at least once to enable or disable BGP route redistribution. Enable BGP and try again." } @@ -17591,10 +17740,10 @@ function Set-NsxEdgeRouting { $PsBoundParameters.ContainsKey("DefaultGatewayAdminDistance") ) { #Check for and create if required the defaultRoute element. first. - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting.staticRouting -Query 'descendant::defaultRoute')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting.staticRouting -query 'descendant::defaultRoute')) { #defaultRoute element does not exist $defaultRoute = $_EdgeRouting.ownerDocument.CreateElement('defaultRoute') - $_EdgeRouting.staticRouting.AppendChild($defaultRoute) | out-null + $_EdgeRouting.staticRouting.AppendChild($defaultRoute) | Out-Null } else { #defaultRoute element exists @@ -17602,7 +17751,7 @@ function Set-NsxEdgeRouting { } if ( $PsBoundParameters.ContainsKey("DefaultGatewayVnic") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'descendant::vnic')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'descendant::vnic')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "vnic" -xmlElementText $DefaultGatewayVnic.ToString() } @@ -17613,7 +17762,7 @@ function Set-NsxEdgeRouting { } if ( $PsBoundParameters.ContainsKey("DefaultGatewayAddress") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'descendant::gatewayAddress')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'descendant::gatewayAddress')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "gatewayAddress" -xmlElementText $DefaultGatewayAddress.ToString() } @@ -17624,7 +17773,7 @@ function Set-NsxEdgeRouting { } if ( $PsBoundParameters.ContainsKey("DefaultGatewayDescription") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'descendant::description')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'descendant::description')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "description" -xmlElementText $DefaultGatewayDescription } @@ -17634,7 +17783,7 @@ function Set-NsxEdgeRouting { } } if ( $PsBoundParameters.ContainsKey("DefaultGatewayMTU") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'descendant::mtu')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'descendant::mtu')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "mtu" -xmlElementText $DefaultGatewayMTU.ToString() } @@ -17644,7 +17793,7 @@ function Set-NsxEdgeRouting { } } if ( $PsBoundParameters.ContainsKey("DefaultGatewayAdminDistance") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'descendant::adminDistance')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'descendant::adminDistance')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "adminDistance" -xmlElementText $DefaultGatewayAdminDistance.ToString() } @@ -17659,7 +17808,7 @@ function Set-NsxEdgeRouting { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -17669,10 +17818,10 @@ function Set-NsxEdgeRouting { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting } } @@ -17707,9 +17856,9 @@ function Get-NsxEdgeRouting { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin { @@ -17760,15 +17909,15 @@ function Get-NsxEdgeStaticRoute { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Network, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [ipAddress]$NextHop + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Network, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [ipAddress]$NextHop ) @@ -17781,10 +17930,10 @@ function Get-NsxEdgeStaticRoute { #consistent readable output $_EdgeStaticRouting = ($EdgeRouting.staticRouting.CloneNode($True)) - $EdgeStaticRoutes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeStaticRouting -Query 'descendant::staticRoutes') + $EdgeStaticRoutes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeStaticRouting -query 'descendant::staticRoutes') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called route. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeStaticRoutes -Query 'descendant::route')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeStaticRoutes -query 'descendant::route')) { $RouteCollection = $EdgeStaticRoutes.route if ( $PsBoundParameters.ContainsKey('Network')) { @@ -17833,33 +17982,33 @@ function New-NsxEdgeStaticRoute { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [ValidateRange(0,200)] - [int]$Vnic, - [Parameter (Mandatory=$False)] - [ValidateRange(0,9128)] - [int]$MTU, - [Parameter (Mandatory=$False)] - [string]$Description, - [Parameter (Mandatory=$True)] - [ipAddress]$NextHop, - [Parameter (Mandatory=$True)] - [string]$Network, - [Parameter (Mandatory=$False)] - [ValidateRange(0,255)] - [int]$AdminDistance, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 200)] + [int]$Vnic, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 9128)] + [int]$MTU, + [Parameter (Mandatory = $False)] + [string]$Description, + [Parameter (Mandatory = $True)] + [ipAddress]$NextHop, + [Parameter (Mandatory = $True)] + [string]$Network, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 255)] + [int]$AdminDistance, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -17872,7 +18021,7 @@ function New-NsxEdgeStaticRoute { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -17882,7 +18031,7 @@ function New-NsxEdgeStaticRoute { #Need to do an xpath query here rather than use PoSH dot notation to get the static route element, #as it might be empty, and PoSH silently turns an empty element into a string object, which is rather not what we want... :| - $StaticRoutes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting.staticRouting -Query 'descendant::staticRoutes') + $StaticRoutes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting.staticRouting -query 'descendant::staticRoutes') $StaticRoutes.AppendChild($Route) | Out-Null Add-XmlElement -xmlRoot $Route -xmlElementName "network" -xmlElementText $Network.ToString() @@ -17908,7 +18057,7 @@ function New-NsxEdgeStaticRoute { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -17918,10 +18067,10 @@ function New-NsxEdgeStaticRoute { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeStaticRoute -Network $Network -NextHop $NextHop + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeStaticRoute -Network $Network -NextHop $NextHop } } @@ -17962,19 +18111,19 @@ function Remove-NsxEdgeStaticRoute { Remove all routes to 1.1.1.0/24 from ESG Edge01 #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeStaticRoute $_ })] - [System.Xml.XmlElement]$StaticRoute, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeStaticRoute $_ })] + [System.Xml.XmlElement]$StaticRoute, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -17984,27 +18133,27 @@ function Remove-NsxEdgeStaticRoute { #Get the routing config for our Edge $edgeId = $StaticRoute.edgeId - $routing = Get-NsxEdge -objectId $edgeId -connection $connection | Get-NsxEdgeRouting + $routing = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxEdgeRouting #Remove the edgeId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::edgeId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::edgeId')) ) | Out-Null #Need to do an xpath query here to query for a route that matches the one passed in. #Union of nextHop and network should be unique $xpathQuery = "//staticRoutes/route[nextHop=`"$($StaticRoute.nextHop)`" and network=`"$($StaticRoute.network)`"]" - write-debug "XPath query for route nodes to remove is: $xpathQuery" - $RouteToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.staticRouting -Query $xpathQuery) + Write-Debug "XPath query for route nodes to remove is: $xpathQuery" + $RouteToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.staticRouting -query $xpathQuery) if ( $RouteToRemove ) { - write-debug "RouteToRemove Element is: `n $($RouteToRemove.OuterXml | format-xml) " + Write-Debug "RouteToRemove Element is: `n $($RouteToRemove.OuterXml | Format-XML) " $routing.staticRouting.staticRoutes.RemoveChild($RouteToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -18014,9 +18163,9 @@ function Remove-NsxEdgeStaticRoute { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -18068,15 +18217,15 @@ function Get-NsxEdgePrefix { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Network + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Network ) @@ -18089,20 +18238,20 @@ function Get-NsxEdgePrefix { #consistent readable output $_GlobalRoutingConfig = ($EdgeRouting.routingGlobalConfig.CloneNode($True)) - $IpPrefixes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_GlobalRoutingConfig -Query 'child::ipPrefixes') + $IpPrefixes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_GlobalRoutingConfig -query 'child::ipPrefixes') #IPPrefixes may not exist... if ( $IPPrefixes ) { #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called ipPrefix. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $IpPrefixes -Query 'child::ipPrefix')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $IpPrefixes -query 'child::ipPrefix')) { $PrefixCollection = $IPPrefixes.ipPrefix if ( $PsBoundParameters.ContainsKey('Network')) { - $PrefixCollection = $PrefixCollection | where-object { $_.ipAddress -eq $Network } + $PrefixCollection = $PrefixCollection | Where-Object { $_.ipAddress -eq $Network } } if ( $PsBoundParameters.ContainsKey('Name')) { - $PrefixCollection = $PrefixCollection | where-object { $_.name -eq $Name } + $PrefixCollection = $PrefixCollection | Where-Object { $_.name -eq $Name } } foreach ( $Prefix in $PrefixCollection ) { @@ -18143,25 +18292,25 @@ function New-NsxEdgePrefix { Create a new prefix called test for network 1.1.1.0/24 on ESG Edge01 #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$True)] - [ValidateNotNullorEmpty()] - [string]$Name, - [Parameter (Mandatory=$True)] - [ValidateNotNullorEmpty()] - [string]$Network, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $True)] + [ValidateNotNullorEmpty()] + [string]$Name, + [Parameter (Mandatory = $True)] + [ValidateNotNullorEmpty()] + [string]$Network, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -18174,11 +18323,11 @@ function New-NsxEdgePrefix { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'child::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'child::edgeId')) ) | Out-Null #Need to do an xpath query here rather than use PoSH dot notation to get the IP prefix element, #as it might be empty or not exist, and PoSH silently turns an empty element into a string object, which is rather not what we want... :| - $ipPrefixes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting.routingGlobalConfig -Query 'child::ipPrefixes') + $ipPrefixes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting.routingGlobalConfig -query 'child::ipPrefixes') if ( -not $ipPrefixes ) { #Create the ipPrefixes element $ipPrefixes = $_EdgeRouting.ownerDocument.CreateElement('ipPrefixes') @@ -18196,7 +18345,7 @@ function New-NsxEdgePrefix { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -18206,10 +18355,10 @@ function New-NsxEdgePrefix { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgePrefix -Network $Network -Name $Name + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgePrefix -Network $Network -Name $Name } } @@ -18246,19 +18395,19 @@ function Remove-NsxEdgePrefix { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgePrefix $_ })] - [System.Xml.XmlElement]$Prefix, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgePrefix $_ })] + [System.Xml.XmlElement]$Prefix, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -18268,27 +18417,27 @@ function Remove-NsxEdgePrefix { #Get the routing config for our Edge $edgeId = $Prefix.edgeId - $routing = Get-NsxEdge -objectId $edgeId -connection $connection | Get-NsxEdgeRouting + $routing = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxEdgeRouting #Remove the edgeId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::edgeId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::edgeId')) ) | Out-Null #Need to do an xpath query here to query for a prefix that matches the one passed in. #Union of nextHop and network should be unique $xpathQuery = "/routingGlobalConfig/ipPrefixes/ipPrefix[name=`"$($Prefix.name)`" and ipAddress=`"$($Prefix.ipAddress)`"]" - write-debug "XPath query for prefix nodes to remove is: $xpathQuery" - $PrefixToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query $xpathQuery) + Write-Debug "XPath query for prefix nodes to remove is: $xpathQuery" + $PrefixToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query $xpathQuery) if ( $PrefixToRemove ) { - write-debug "PrefixToRemove Element is: `n $($PrefixToRemove.OuterXml | format-xml) " + Write-Debug "PrefixToRemove Element is: `n $($PrefixToRemove.OuterXml | Format-XML) " $routing.routingGlobalConfig.ipPrefixes.RemoveChild($PrefixToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -18298,9 +18447,9 @@ function Remove-NsxEdgePrefix { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -18341,9 +18490,9 @@ function Get-NsxEdgeBgp { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting ) begin { @@ -18355,8 +18504,8 @@ function Get-NsxEdgeBgp { #We append the Edge-id to the associated Routing config XML to enable pipeline workflows and #consistent readable output - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'descendant::bgp')) { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'child::bgp').CloneNode($True) + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'descendant::bgp')) { + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'child::bgp').CloneNode($True) Add-XmlElement -xmlRoot $bgp -xmlElementName "edgeId" -xmlElementText $EdgeRouting.EdgeId $bgp } @@ -18387,30 +18536,30 @@ function Set-NsxEdgeBgp { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$EnableBGP, - [Parameter (Mandatory=$False)] - [IpAddress]$RouterId, - [Parameter (Mandatory=$False)] - [ValidateRange(0,65535)] - [int]$LocalAS, - [Parameter (Mandatory=$False)] - [switch]$GracefulRestart, - [Parameter (Mandatory=$False)] - [switch]$DefaultOriginate, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$EnableBGP, + [Parameter (Mandatory = $False)] + [IpAddress]$RouterId, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 65535)] + [int]$LocalAS, + [Parameter (Mandatory = $False)] + [switch]$GracefulRestart, + [Parameter (Mandatory = $False)] + [switch]$DefaultOriginate, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -18425,22 +18574,22 @@ function Set-NsxEdgeBgp { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::bgp') if ( -not $bgp ) { #bgp node does not exist. [System.XML.XMLElement]$bgp = $_EdgeRouting.ownerDocument.CreateElement("bgp") - $_EdgeRouting.appendChild($bgp) | out-null + $_EdgeRouting.appendChild($bgp) | Out-Null } # Check bgp enablement if ($PsBoundParameters.ContainsKey('EnableBGP')) { # BGP option is specified - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::enabled')) { #Enabled element exists. Update it. $bgp.enabled = $EnableBGP.ToString().ToLower() } @@ -18449,7 +18598,7 @@ function Set-NsxEdgeBgp { Add-XmlElement -xmlRoot $bgp -xmlElementName "enabled" -xmlElementText $EnableBGP.ToString().ToLower() } } - elseif (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::enabled') { + elseif (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::enabled') { # BGP option is not specified but enabled if ( $bgp.enabled -eq 'true' ) { # Assume bgp is already enabled. @@ -18463,7 +18612,7 @@ function Set-NsxEdgeBgp { } $xmlGlobalConfig = $_EdgeRouting.routingGlobalConfig - $xmlRouterId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -Query 'descendant::routerId') + $xmlRouterId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -query 'descendant::routerId') if ( $EnableBGP ) { if ( -not ($xmlRouterId -or $PsBoundParameters.ContainsKey("RouterId"))) { @@ -18472,18 +18621,18 @@ function Set-NsxEdgeBgp { } if ($PsBoundParameters.ContainsKey("RouterId")) { - #Set Routerid... + #Set Routerid... if ($xmlRouterId) { $xmlRouterId = $RouterId.IPAddresstoString } - else{ + else { Add-XmlElement -xmlRoot $xmlGlobalConfig -xmlElementName "routerId" -xmlElementText $RouterId.IPAddresstoString } } } if ( $PsBoundParameters.ContainsKey("LocalAS")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::localAS')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::localAS')) { #LocalAS element exists, update it. $bgp.localAS = $LocalAS.ToString() } @@ -18492,12 +18641,12 @@ function Set-NsxEdgeBgp { Add-XmlElement -xmlRoot $bgp -xmlElementName "localAS" -xmlElementText $LocalAS.ToString() } } - elseif ( (-not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::localAS')) -and $EnableBGP )) { + elseif ( (-not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::localAS')) -and $EnableBGP )) { throw "Existing configuration has no Local AS number specified. Local AS must be set to enable BGP." } if ( $PsBoundParameters.ContainsKey("GracefulRestart")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::gracefulRestart')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::gracefulRestart')) { #element exists, update it. $bgp.gracefulRestart = $GracefulRestart.ToString().ToLower() } @@ -18508,7 +18657,7 @@ function Set-NsxEdgeBgp { } if ( $PsBoundParameters.ContainsKey("DefaultOriginate")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::defaultOriginate')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::defaultOriginate')) { #element exists, update it. $bgp.defaultOriginate = $DefaultOriginate.ToString().ToLower() } @@ -18522,7 +18671,7 @@ function Set-NsxEdgeBgp { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -18532,10 +18681,10 @@ function Set-NsxEdgeBgp { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeBgp + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeBgp } } @@ -18581,18 +18730,18 @@ function Get-NsxEdgeBgpNeighbour { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Network, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [ipAddress]$IpAddress, - [Parameter (Mandatory=$false)] - [ValidateRange(0,65535)] - [int]$RemoteAS + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Network, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [ipAddress]$IpAddress, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 65535)] + [int]$RemoteAS ) begin { @@ -18600,23 +18749,23 @@ function Get-NsxEdgeBgpNeighbour { process { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'descendant::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'descendant::bgp') if ( $bgp ) { $_bgp = $bgp.CloneNode($True) - $BgpNeighbours = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_bgp -Query 'descendant::bgpNeighbours') + $BgpNeighbours = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_bgp -query 'descendant::bgpNeighbours') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called bgpNeighbour. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $BgpNeighbours -Query 'descendant::bgpNeighbour')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $BgpNeighbours -query 'descendant::bgpNeighbour')) { $NeighbourCollection = $BgpNeighbours.bgpNeighbour if ( $PsBoundParameters.ContainsKey('IpAddress')) { - $NeighbourCollection = $NeighbourCollection | where-object { $_.ipAddress -eq $IpAddress } + $NeighbourCollection = $NeighbourCollection | Where-Object { $_.ipAddress -eq $IpAddress } } if ( $PsBoundParameters.ContainsKey('RemoteAS')) { - $NeighbourCollection = $NeighbourCollection | where-object { $_.remoteAS -eq $RemoteAS } + $NeighbourCollection = $NeighbourCollection | Where-Object { $_.remoteAS -eq $RemoteAS } } foreach ( $Neighbour in $NeighbourCollection ) { @@ -18665,38 +18814,38 @@ function New-NsxEdgeBgpNeighbour { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$true)] - [ValidateNotNullorEmpty()] - [ipAddress]$IpAddress, - [Parameter (Mandatory=$true)] - [ValidateRange(0,65535)] - [int]$RemoteAS, - [Parameter (Mandatory=$false)] - [ValidateRange(0,65535)] - [int]$Weight, - [Parameter (Mandatory=$false)] - [ValidateRange(2,65535)] - [int]$HoldDownTimer, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65534)] - [int]$KeepAliveTimer, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [string]$Password, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $true)] + [ValidateNotNullorEmpty()] + [ipAddress]$IpAddress, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 65535)] + [int]$RemoteAS, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 65535)] + [int]$Weight, + [Parameter (Mandatory = $false)] + [ValidateRange(2, 65535)] + [int]$HoldDownTimer, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65534)] + [int]$KeepAliveTimer, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [string]$Password, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -18709,16 +18858,16 @@ function New-NsxEdgeBgpNeighbour { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Create the new bgpNeighbour element. $Neighbour = $_EdgeRouting.ownerDocument.CreateElement('bgpNeighbour') #Need to do an xpath query here rather than use PoSH dot notation to get the bgp element, #as it might not exist which wil cause PoSH to throw in stric mode. - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::bgp') if ( $bgp ) { - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::bgpNeighbours').AppendChild($Neighbour) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::bgpNeighbours').AppendChild($Neighbour) | Out-Null Add-XmlElement -xmlRoot $Neighbour -xmlElementName "ipAddress" -xmlElementText $IpAddress.ToString() Add-XmlElement -xmlRoot $Neighbour -xmlElementName "remoteAS" -xmlElementText $RemoteAS.ToString() @@ -18745,7 +18894,7 @@ function New-NsxEdgeBgpNeighbour { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -18755,10 +18904,10 @@ function New-NsxEdgeBgpNeighbour { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeBgpNeighbour -IpAddress $IpAddress -RemoteAS $RemoteAS + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeBgpNeighbour -IpAddress $IpAddress -RemoteAS $RemoteAS } } else { @@ -18798,19 +18947,19 @@ function Remove-NsxEdgeBgpNeighbour { PS C:\> Get-NsxEdge Edge01 | Get-NsxEdgeRouting | Get-NsxEdgeBgpNeighbour | where-object { $_.ipaddress -eq '1.1.1.2' } | Remove-NsxEdgeBgpNeighbour #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeBgpNeighbour $_ })] - [System.Xml.XmlElement]$BgpNeighbour, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeBgpNeighbour $_ })] + [System.Xml.XmlElement]$BgpNeighbour, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -18823,10 +18972,10 @@ function Remove-NsxEdgeBgpNeighbour { $routing = Get-NsxEdge -objectId $edgeId | Get-NsxEdgeRouting #Remove the edgeId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::edgeId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::edgeId')) ) | Out-Null #Validate the BGP node exists on the edge - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::bgp')) { throw "BGP is not enabled on ESG $edgeId. Enable BGP and try again." } + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::bgp')) { throw "BGP is not enabled on ESG $edgeId. Enable BGP and try again." } #Need to do an xpath query here to query for a bgp neighbour that matches the one passed in. #Union of ipaddress and remote AS should be unique (though this is not enforced by the API, @@ -18836,19 +18985,19 @@ function Remove-NsxEdgeBgpNeighbour { #matching on filters to better handle uniquness amongst bgp neighbours with same ip and remoteAS $xpathQuery = "//bgpNeighbours/bgpNeighbour[ipAddress=`"$($BgpNeighbour.ipAddress)`" and remoteAS=`"$($BgpNeighbour.remoteAS)`"]" - write-debug "XPath query for neighbour nodes to remove is: $xpathQuery" - $NeighbourToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.bgp -Query $xpathQuery) + Write-Debug "XPath query for neighbour nodes to remove is: $xpathQuery" + $NeighbourToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.bgp -query $xpathQuery) if ( $NeighbourToRemove ) { - write-debug "NeighbourToRemove Element is: `n $($NeighbourToRemove.OuterXml | format-xml) " + Write-Debug "NeighbourToRemove Element is: `n $($NeighbourToRemove.OuterXml | Format-XML) " $routing.bgp.bgpNeighbours.RemoveChild($NeighbourToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -18858,9 +19007,9 @@ function Remove-NsxEdgeBgpNeighbour { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -18901,9 +19050,9 @@ function Get-NsxEdgeOspf { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting ) begin { @@ -18915,7 +19064,7 @@ function Get-NsxEdgeOspf { #We append the Edge-id to the associated Routing config XML to enable pipeline workflows and #consistent readable output - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'descendant::ospf')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'descendant::ospf')) { $ospf = $EdgeRouting.ospf.CloneNode($True) Add-XmlElement -xmlRoot $ospf -xmlElementName "edgeId" -xmlElementText $EdgeRouting.EdgeId $ospf @@ -18947,27 +19096,27 @@ function Set-NsxEdgeOspf { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$EnableOSPF, - [Parameter (Mandatory=$False)] - [IpAddress]$RouterId, - [Parameter (Mandatory=$False)] - [switch]$GracefulRestart, - [Parameter (Mandatory=$False)] - [switch]$DefaultOriginate, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$EnableOSPF, + [Parameter (Mandatory = $False)] + [IpAddress]$RouterId, + [Parameter (Mandatory = $False)] + [switch]$GracefulRestart, + [Parameter (Mandatory = $False)] + [switch]$DefaultOriginate, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -18982,21 +19131,21 @@ function Set-NsxEdgeOspf { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::ospf') if ( -not $ospf ) { #ospf node does not exist. [System.XML.XMLElement]$ospf = $_EdgeRouting.ownerDocument.CreateElement("ospf") - $_EdgeRouting.appendChild($ospf) | out-null + $_EdgeRouting.appendChild($ospf) | Out-Null } # Check ospf enablemant if ($PsBoundParameters.ContainsKey('EnableOSPF')) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::enabled')) { #Enabled element exists. Update it. $ospf.enabled = $EnableOSPF.ToString().ToLower() } @@ -19005,11 +19154,12 @@ function Set-NsxEdgeOspf { Add-XmlElement -xmlRoot $ospf -xmlElementName "enabled" -xmlElementText $EnableOSPF.ToString().ToLower() } } - elseif (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::enabled') { + elseif (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::enabled') { # OSPF option is not specified but enabled if ( $ospf.enabled -eq 'true' ) { # Assume ospf is already enabled. - } else { + } + else { throw "EnableOSPF is not specified or BGP is not enabled on edge $edgeID. Please specify option EnableOSPF" } } @@ -19018,7 +19168,7 @@ function Set-NsxEdgeOspf { } $xmlGlobalConfig = $_EdgeRouting.routingGlobalConfig - $xmlRouterId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -Query 'descendant::routerId') + $xmlRouterId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -query 'descendant::routerId') if ( $EnableOSPF ) { if ( -not ($xmlRouterId -or $PsBoundParameters.ContainsKey("RouterId"))) { #Existing config missing and no new value set... @@ -19030,14 +19180,14 @@ function Set-NsxEdgeOspf { if ($xmlRouterId) { $xmlRouterId = $RouterId.IPAddresstoString } - else{ + else { Add-XmlElement -xmlRoot $xmlGlobalConfig -xmlElementName "routerId" -xmlElementText $RouterId.IPAddresstoString } } } if ( $PsBoundParameters.ContainsKey("GracefulRestart")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::gracefulRestart')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::gracefulRestart')) { #element exists, update it. $ospf.gracefulRestart = $GracefulRestart.ToString().ToLower() } @@ -19048,7 +19198,7 @@ function Set-NsxEdgeOspf { } if ( $PsBoundParameters.ContainsKey("DefaultOriginate")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::defaultOriginate')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::defaultOriginate')) { #element exists, update it. $ospf.defaultOriginate = $DefaultOriginate.ToString().ToLower() } @@ -19062,7 +19212,7 @@ function Set-NsxEdgeOspf { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -19072,10 +19222,10 @@ function Set-NsxEdgeOspf { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeOspf + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeOspf } } @@ -19111,12 +19261,12 @@ function Get-NsxEdgeOspfArea { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$false)] - [ValidateRange(0,4294967295)] - [int]$AreaId + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 4294967295)] + [int]$AreaId ) begin { @@ -19124,19 +19274,19 @@ function Get-NsxEdgeOspfArea { process { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'descendant::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'descendant::ospf') if ( $ospf ) { $_ospf = $ospf.CloneNode($True) - $OspfAreas = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ospf -Query 'descendant::ospfAreas') + $OspfAreas = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ospf -query 'descendant::ospfAreas') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called ospfArea. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $OspfAreas -Query 'descendant::ospfArea')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $OspfAreas -query 'descendant::ospfArea')) { $AreaCollection = $OspfAreas.ospfArea if ( $PsBoundParameters.ContainsKey('AreaId')) { - $AreaCollection = $AreaCollection | where-object { $_.areaId -eq $AreaId } + $AreaCollection = $AreaCollection | Where-Object { $_.areaId -eq $AreaId } } foreach ( $Area in $AreaCollection ) { @@ -19183,19 +19333,19 @@ function Remove-NsxEdgeOspfArea { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeOspfArea $_ })] - [System.Xml.XmlElement]$OspfArea, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeOspfArea $_ })] + [System.Xml.XmlElement]$OspfArea, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -19205,29 +19355,29 @@ function Remove-NsxEdgeOspfArea { #Get the routing config for our Edge $edgeId = $OspfArea.edgeId - $routing = Get-NsxEdge -objectId $edgeId -connection $connection | Get-NsxEdgeRouting + $routing = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxEdgeRouting #Remove the edgeId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::edgeId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::edgeId')) ) | Out-Null #Validate the OSPF node exists on the edge - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::ospf')) { throw "OSPF is not enabled on ESG $edgeId. Enable OSPF and try again." } + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::ospf')) { throw "OSPF is not enabled on ESG $edgeId. Enable OSPF and try again." } if ( -not ($routing.ospf.enabled -eq 'true') ) { throw "OSPF is not enabled on ESG $edgeId. Enable OSPF and try again." } $xpathQuery = "//ospfAreas/ospfArea[areaId=`"$($OspfArea.areaId)`"]" - write-debug "XPath query for area nodes to remove is: $xpathQuery" - $AreaToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -Query $xpathQuery) + Write-Debug "XPath query for area nodes to remove is: $xpathQuery" + $AreaToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -query $xpathQuery) if ( $AreaToRemove ) { - write-debug "AreaToRemove Element is: `n $($AreaToRemove.OuterXml | format-xml) " + Write-Debug "AreaToRemove Element is: `n $($AreaToRemove.OuterXml | Format-XML) " $routing.ospf.ospfAreas.RemoveChild($AreaToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -19237,9 +19387,9 @@ function Remove-NsxEdgeOspfArea { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -19282,32 +19432,32 @@ function New-NsxEdgeOspfArea { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$true)] - [ValidateRange(0,4294967295)] - [uint32]$AreaId, - [Parameter (Mandatory=$false)] - [ValidateSet("normal","nssa",IgnoreCase = $false)] - [string]$Type, - [Parameter (Mandatory=$false)] - [ValidateSet("none","password","md5",IgnoreCase = $false)] - [string]$AuthenticationType="none", - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [string]$Password, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 4294967295)] + [uint32]$AreaId, + [Parameter (Mandatory = $false)] + [ValidateSet("normal", "nssa", IgnoreCase = $false)] + [string]$Type, + [Parameter (Mandatory = $false)] + [ValidateSet("none", "password", "md5", IgnoreCase = $false)] + [string]$AuthenticationType = "none", + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [string]$Password, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -19320,16 +19470,16 @@ function New-NsxEdgeOspfArea { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Create the new ospfArea element. $Area = $_EdgeRouting.ownerDocument.CreateElement('ospfArea') #Need to do an xpath query here rather than use PoSH dot notation to get the ospf element, #as it might not exist which wil cause PoSH to throw in stric mode. - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::ospf') if ( $ospf ) { - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::ospfAreas').AppendChild($Area) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::ospfAreas').AppendChild($Area) | Out-Null Add-XmlElement -xmlRoot $Area -xmlElementName "areaId" -xmlElementText $AreaId.ToString() @@ -19354,7 +19504,7 @@ function New-NsxEdgeOspfArea { throw "Must specify a password if Authentication type is not none." } $Authentication = $Area.ownerDocument.CreateElement("authentication") - $Area.AppendChild( $Authentication ) | out-null + $Area.AppendChild( $Authentication ) | Out-Null Add-XmlElement -xmlRoot $Authentication -xmlElementName "type" -xmlElementText $AuthenticationType Add-XmlElement -xmlRoot $Authentication -xmlElementName "value" -xmlElementText $Password @@ -19366,7 +19516,7 @@ function New-NsxEdgeOspfArea { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -19376,10 +19526,10 @@ function New-NsxEdgeOspfArea { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeOspfArea -AreaId $AreaId + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeOspfArea -AreaId $AreaId } } else { @@ -19424,15 +19574,15 @@ function Get-NsxEdgeOspfInterface { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$false)] - [ValidateRange(0,4294967295)] - [int]$AreaId, - [Parameter (Mandatory=$false)] - [ValidateRange(0,200)] - [int]$vNicId + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 4294967295)] + [int]$AreaId, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 200)] + [int]$vNicId ) begin { @@ -19440,23 +19590,23 @@ function Get-NsxEdgeOspfInterface { process { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'descendant::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'descendant::ospf') if ( $ospf ) { $_ospf = $ospf.CloneNode($True) - $OspfInterfaces = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ospf -Query 'descendant::ospfInterfaces') + $OspfInterfaces = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ospf -query 'descendant::ospfInterfaces') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called ospfArea. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $OspfInterfaces -Query 'descendant::ospfInterface')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $OspfInterfaces -query 'descendant::ospfInterface')) { $InterfaceCollection = $OspfInterfaces.ospfInterface if ( $PsBoundParameters.ContainsKey('AreaId')) { - $InterfaceCollection = $InterfaceCollection | where-object { $_.areaId -eq $AreaId } + $InterfaceCollection = $InterfaceCollection | Where-Object { $_.areaId -eq $AreaId } } if ( $PsBoundParameters.ContainsKey('vNicId')) { - $InterfaceCollection = $InterfaceCollection | where-object { $_.vnic -eq $vNicId } + $InterfaceCollection = $InterfaceCollection | Where-Object { $_.vnic -eq $vNicId } } foreach ( $Interface in $InterfaceCollection ) { @@ -19508,19 +19658,19 @@ function Remove-NsxEdgeOspfInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeOspfInterface $_ })] - [System.Xml.XmlElement]$OspfInterface, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeOspfInterface $_ })] + [System.Xml.XmlElement]$OspfInterface, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -19530,29 +19680,29 @@ function Remove-NsxEdgeOspfInterface { #Get the routing config for our Edge $edgeId = $OspfInterface.edgeId - $routing = Get-NsxEdge -objectId $edgeId -connection $connection | Get-NsxEdgeRouting + $routing = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxEdgeRouting #Remove the edgeId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::edgeId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::edgeId')) ) | Out-Null #Validate the OSPF node exists on the edge - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'descendant::ospf')) { throw "OSPF is not enabled on ESG $edgeId. Enable OSPF and try again." } + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'descendant::ospf')) { throw "OSPF is not enabled on ESG $edgeId. Enable OSPF and try again." } if ( -not ($routing.ospf.enabled -eq 'true') ) { throw "OSPF is not enabled on ESG $edgeId. Enable OSPF and try again." } $xpathQuery = "//ospfInterfaces/ospfInterface[areaId=`"$($OspfInterface.areaId)`"]" - write-debug "XPath query for interface nodes to remove is: $xpathQuery" - $InterfaceToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -Query $xpathQuery) + Write-Debug "XPath query for interface nodes to remove is: $xpathQuery" + $InterfaceToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -query $xpathQuery) if ( $InterfaceToRemove ) { - write-debug "InterfaceToRemove Element is: `n $($InterfaceToRemove.OuterXml | format-xml) " + Write-Debug "InterfaceToRemove Element is: `n $($InterfaceToRemove.OuterXml | Format-XML) " $routing.ospf.ospfInterfaces.RemoveChild($InterfaceToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -19562,9 +19712,9 @@ function Remove-NsxEdgeOspfInterface { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -19602,39 +19752,39 @@ function New-NsxEdgeOspfInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$true)] - [ValidateRange(0,4294967295)] - [uint32]$AreaId, - [Parameter (Mandatory=$true)] - [ValidateRange(0,200)] - [int]$Vnic, - [Parameter (Mandatory=$false)] - [ValidateRange(1,255)] - [int]$HelloInterval, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$DeadInterval, - [Parameter (Mandatory=$false)] - [ValidateRange(0,255)] - [int]$Priority, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$Cost, - [Parameter (Mandatory=$false)] - [switch]$IgnoreMTU, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 4294967295)] + [uint32]$AreaId, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 200)] + [int]$Vnic, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 255)] + [int]$HelloInterval, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$DeadInterval, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 255)] + [int]$Priority, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$Cost, + [Parameter (Mandatory = $false)] + [switch]$IgnoreMTU, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -19648,16 +19798,16 @@ function New-NsxEdgeOspfInterface { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::edgeId')) ) | Out-Null #Create the new ospfInterface element. $Interface = $_EdgeRouting.ownerDocument.CreateElement('ospfInterface') #Need to do an xpath query here rather than use PoSH dot notation to get the ospf element, #as it might not exist which wil cause PoSH to throw in stric mode. - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'descendant::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'descendant::ospf') if ( $ospf ) { - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'descendant::ospfInterfaces').AppendChild($Interface) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'descendant::ospfInterfaces').AppendChild($Interface) | Out-Null Add-XmlElement -xmlRoot $Interface -xmlElementName "areaId" -xmlElementText $AreaId.ToString() Add-XmlElement -xmlRoot $Interface -xmlElementName "vnic" -xmlElementText $Vnic.ToString() @@ -19688,7 +19838,7 @@ function New-NsxEdgeOspfInterface { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -19698,10 +19848,10 @@ function New-NsxEdgeOspfInterface { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeOspfInterface -AreaId $AreaId + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeOspfInterface -AreaId $AreaId } } else { @@ -19742,14 +19892,14 @@ function Get-NsxEdgeRedistributionRule { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$false)] - [ValidateSet("ospf","bgp")] - [string]$Learner, - [Parameter (Mandatory=$false)] - [int]$Id + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $false)] + [ValidateSet("ospf", "bgp")] + [string]$Learner, + [Parameter (Mandatory = $false)] + [int]$Id ) begin { @@ -19760,12 +19910,12 @@ function Get-NsxEdgeRedistributionRule { #Rules can be defined in either ospf or bgp (isis as well, but who cares huh? :) ) if ( ( -not $PsBoundParameters.ContainsKey('Learner')) -or ($PsBoundParameters.ContainsKey('Learner') -and $Learner -eq 'ospf')) { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'child::ospf') if ( $ospf ) { $_ospf = $ospf.CloneNode($True) - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ospf -Query 'child::redistribution/rules/rule') ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ospf -query 'child::redistribution/rules/rule') ) { $OspfRuleCollection = $_ospf.redistribution.rules.rule @@ -19780,7 +19930,7 @@ function Get-NsxEdgeRedistributionRule { } if ( $PsBoundParameters.ContainsKey('Id')) { - $OspfRuleCollection = $OspfRuleCollection | where-object { $_.id -eq $Id } + $OspfRuleCollection = $OspfRuleCollection | Where-Object { $_.id -eq $Id } } $OspfRuleCollection @@ -19790,11 +19940,11 @@ function Get-NsxEdgeRedistributionRule { if ( ( -not $PsBoundParameters.ContainsKey('Learner')) -or ($PsBoundParameters.ContainsKey('Learner') -and $Learner -eq 'bgp')) { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -Query 'child::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $EdgeRouting -query 'child::bgp') if ( $bgp ) { $_bgp = $bgp.CloneNode($True) - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_bgp -Query 'child::redistribution/rules/rule') ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_bgp -query 'child::redistribution/rules/rule') ) { $BgpRuleCollection = $_bgp.redistribution.rules.rule @@ -19808,7 +19958,7 @@ function Get-NsxEdgeRedistributionRule { } if ( $PsBoundParameters.ContainsKey('Id')) { - $BgpRuleCollection = $BgpRuleCollection | where-object { $_.id -eq $Id } + $BgpRuleCollection = $BgpRuleCollection | Where-Object { $_.id -eq $Id } } $BgpRuleCollection } @@ -19848,19 +19998,19 @@ function Remove-NsxEdgeRedistributionRule { Remove all ospf redistribution rules from Edge01 #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRedistributionRule $_ })] - [System.Xml.XmlElement]$RedistributionRule, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRedistributionRule $_ })] + [System.Xml.XmlElement]$RedistributionRule, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -19870,13 +20020,13 @@ function Remove-NsxEdgeRedistributionRule { #Get the routing config for our Edge $edgeId = $RedistributionRule.edgeId - $routing = Get-NsxEdge -objectId $edgeId -connection $connection | Get-NsxEdgeRouting + $routing = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxEdgeRouting #Remove the edgeId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::edgeId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::edgeId')) ) | Out-Null #Validate the learner protocol node exists on the edge - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query "child::$($RedistributionRule.learner)")) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query "child::$($RedistributionRule.learner)")) { throw "Rule learner protocol $($RedistributionRule.learner) is not enabled on ESG $edgeId. Use Get-NsxEdge | Get-NsxEdgerouting | Get-NsxEdgeRedistributionRule to get the rule you want to remove." } @@ -19885,30 +20035,30 @@ function Remove-NsxEdgeRedistributionRule { $xPathQuery += " and from/connected=`"$($RedistributionRule.from.connected)`" and from/static=`"$($RedistributionRule.from.static)`"" $xPathQuery += " and from/ospf=`"$($RedistributionRule.from.ospf)`" and from/bgp=`"$($RedistributionRule.from.bgp)`"" - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -Query 'child::from/isis')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -query 'child::from/isis')) { $xPathQuery += " and from/isis=`"$($RedistributionRule.from.isis)`"" } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -Query 'child::prefixName')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -query 'child::prefixName')) { $xPathQuery += " and prefixName=`"$($RedistributionRule.prefixName)`"" } $xPathQuery += "]" - write-debug "XPath query for rule node to remove is: $xpathQuery" + Write-Debug "XPath query for rule node to remove is: $xpathQuery" - $RuleToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query $xpathQuery) + $RuleToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query $xpathQuery) if ( $RuleToRemove ) { - write-debug "RuleToRemove Element is: `n $($RuleToRemove | format-xml) " + Write-Debug "RuleToRemove Element is: `n $($RuleToRemove | Format-XML) " $routing.$($RedistributionRule.Learner).redistribution.rules.RemoveChild($RuleToRemove) | Out-Null $URI = "/api/4.0/edges/$($EdgeId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -19918,9 +20068,9 @@ function Remove-NsxEdgeRedistributionRule { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } else { @@ -19957,35 +20107,35 @@ function New-NsxEdgeRedistributionRule { Create a new permit Redistribution Rule for prefix test (note, prefix must already exist, and is case sensistive) for ospf. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdgeRouting $_ })] - [System.Xml.XmlElement]$EdgeRouting, - [Parameter (Mandatory=$True)] - [ValidateSet("ospf","bgp",IgnoreCase=$false)] - [String]$Learner, - [Parameter (Mandatory=$false)] - [String]$PrefixName, - [Parameter (Mandatory=$false)] - [switch]$FromConnected, - [Parameter (Mandatory=$false)] - [switch]$FromStatic, - [Parameter (Mandatory=$false)] - [switch]$FromOspf, - [Parameter (Mandatory=$false)] - [switch]$FromBgp, - [Parameter (Mandatory=$False)] - [ValidateSet("permit","deny",IgnoreCase=$false)] - [String]$Action="permit", - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdgeRouting $_ })] + [System.Xml.XmlElement]$EdgeRouting, + [Parameter (Mandatory = $True)] + [ValidateSet("ospf", "bgp", IgnoreCase = $false)] + [String]$Learner, + [Parameter (Mandatory = $false)] + [String]$PrefixName, + [Parameter (Mandatory = $false)] + [switch]$FromConnected, + [Parameter (Mandatory = $false)] + [switch]$FromStatic, + [Parameter (Mandatory = $false)] + [switch]$FromOspf, + [Parameter (Mandatory = $false)] + [switch]$FromBgp, + [Parameter (Mandatory = $False)] + [ValidateSet("permit", "deny", IgnoreCase = $false)] + [String]$Action = "permit", + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -19999,11 +20149,11 @@ function New-NsxEdgeRedistributionRule { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_EdgeRouting.edgeId - $_EdgeRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query 'child::edgeId')) ) | out-null + $_EdgeRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query 'child::edgeId')) ) | Out-Null #Need to do an xpath query here rather than use PoSH dot notation to get the protocol element, #as it might not exist which wil cause PoSH to throw in stric mode. - $ProtocolElement = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -Query "child::$Learner") + $ProtocolElement = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_EdgeRouting -query "child::$Learner") if ( (-not $ProtocolElement) -or ($ProtocolElement.Enabled -ne 'true')) { @@ -20013,7 +20163,7 @@ function New-NsxEdgeRedistributionRule { #Create the new rule element. $Rule = $_EdgeRouting.ownerDocument.CreateElement('rule') - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ProtocolElement -Query 'child::redistribution/rules').AppendChild($Rule) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ProtocolElement -query 'child::redistribution/rules').AppendChild($Rule) | Out-Null Add-XmlElement -xmlRoot $Rule -xmlElementName "action" -xmlElementText $Action if ( $PsBoundParameters.ContainsKey("PrefixName") ) { @@ -20023,7 +20173,7 @@ function New-NsxEdgeRedistributionRule { #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. if ( $PsBoundParameters.ContainsKey('FromConnected') -or $PsBoundParameters.ContainsKey('FromStatic') -or - $PsBoundParameters.ContainsKey('FromOspf') -or $PsBoundParameters.ContainsKey('FromBgp') ) { + $PsBoundParameters.ContainsKey('FromOspf') -or $PsBoundParameters.ContainsKey('FromBgp') ) { $FromElement = $Rule.ownerDocument.CreateElement('from') $Rule.AppendChild($FromElement) | Out-Null @@ -20049,7 +20199,7 @@ function New-NsxEdgeRedistributionRule { $body = $_EdgeRouting.OuterXml if ( $confirm ) { - $message = "Edge Services Gateway routing update will modify existing Edge configuration." + $message = "Edge Services Gateway routing update will modify existing Edge configuration." $question = "Proceed with Update of Edge Services Gateway $($EdgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -20059,10 +20209,10 @@ function New-NsxEdgeRedistributionRule { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed - (Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -Learner $Learner)[-1] + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed + (Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -Learner $Learner)[-1] } } @@ -20117,58 +20267,58 @@ function Set-NsxLogicalRouterRouting { Disable OSPF Route Redistribution without confirmation. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$EnableOspf, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [ipAddress]$ProtocolAddress, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [ipAddress]$ForwardingAddress, - [Parameter (Mandatory=$False)] - [switch]$EnableBgp, - [Parameter (Mandatory=$False)] - [IpAddress]$RouterId, - [Parameter (MAndatory=$False)] - [ValidateRange(0,65535)] - [int]$LocalAS, - [Parameter (Mandatory=$False)] - [switch]$EnableEcmp, - [Parameter (Mandatory=$False)] - [switch]$EnableOspfRouteRedistribution, - [Parameter (Mandatory=$False)] - [switch]$EnableBgpRouteRedistribution, - [Parameter (Mandatory=$False)] - [switch]$EnableLogging, - [Parameter (Mandatory=$False)] - [ValidateSet("emergency","alert","critical","error","warning","notice","info","debug")] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - [ValidateRange(0,200)] - [int]$DefaultGatewayVnic, - [Parameter (Mandatory=$False)] - [ValidateRange(0,9128)] - [int]$DefaultGatewayMTU, - [Parameter (Mandatory=$False)] - [string]$DefaultGatewayDescription, - [Parameter (Mandatory=$False)] - [ipAddress]$DefaultGatewayAddress, - [Parameter (Mandatory=$False)] - [ValidateRange(0,255)] - [int]$DefaultGatewayAdminDistance, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$EnableOspf, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [ipAddress]$ProtocolAddress, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [ipAddress]$ForwardingAddress, + [Parameter (Mandatory = $False)] + [switch]$EnableBgp, + [Parameter (Mandatory = $False)] + [IpAddress]$RouterId, + [Parameter (MAndatory = $False)] + [ValidateRange(0, 65535)] + [int]$LocalAS, + [Parameter (Mandatory = $False)] + [switch]$EnableEcmp, + [Parameter (Mandatory = $False)] + [switch]$EnableOspfRouteRedistribution, + [Parameter (Mandatory = $False)] + [switch]$EnableBgpRouteRedistribution, + [Parameter (Mandatory = $False)] + [switch]$EnableLogging, + [Parameter (Mandatory = $False)] + [ValidateSet("emergency", "alert", "critical", "error", "warning", "notice", "info", "debug")] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 200)] + [int]$DefaultGatewayVnic, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 9128)] + [int]$DefaultGatewayMTU, + [Parameter (Mandatory = $False)] + [string]$DefaultGatewayDescription, + [Parameter (Mandatory = $False)] + [ipAddress]$DefaultGatewayAddress, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 255)] + [int]$DefaultGatewayAdminDistance, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -20183,14 +20333,14 @@ function Set-NsxLogicalRouterRouting { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. if ( $PsBoundParameters.ContainsKey('EnableOSPF') -or $PsBoundParameters.ContainsKey('EnableBGP') ) { $xmlGlobalConfig = $_LogicalRouterRouting.routingGlobalConfig - $xmlRouterId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -Query 'child::routerId') + $xmlRouterId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -query 'child::routerId') if ( $EnableOSPF -or $EnableBGP ) { if ( -not ($xmlRouterId -or $PsBoundParameters.ContainsKey("RouterId"))) { #Existing config missing and no new value set... @@ -20202,7 +20352,7 @@ function Set-NsxLogicalRouterRouting { if ($xmlRouterId) { $xmlRouterId = $RouterId.IPAddresstoString } - else{ + else { Add-XmlElement -xmlRoot $xmlGlobalConfig -xmlElementName "routerId" -xmlElementText $RouterId.IPAddresstoString } } @@ -20210,14 +20360,14 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey('EnableOSPF')) { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::ospf') if ( -not $ospf ) { #ospf node does not exist. [System.XML.XMLElement]$ospf = $_LogicalRouterRouting.ownerDocument.CreateElement("ospf") - $_LogicalRouterRouting.appendChild($ospf) | out-null + $_LogicalRouterRouting.appendChild($ospf) | Out-Null } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::enabled')) { #Enabled element exists. Update it. $ospf.enabled = $EnableOSPF.ToString().ToLower() } @@ -20226,16 +20376,16 @@ function Set-NsxLogicalRouterRouting { Add-XmlElement -xmlRoot $ospf -xmlElementName "enabled" -xmlElementText $EnableOSPF.ToString().ToLower() } - if ( $EnableOSPF -and (-not ($ProtocolAddress -or ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::protocolAddress'))))) { + if ( $EnableOSPF -and (-not ($ProtocolAddress -or ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::protocolAddress'))))) { throw "ProtocolAddress and ForwardingAddress are required to enable OSPF" } - if ( $EnableOSPF -and (-not ($ForwardingAddress -or ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::forwardingAddress'))))) { + if ( $EnableOSPF -and (-not ($ForwardingAddress -or ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::forwardingAddress'))))) { throw "ProtocolAddress and ForwardingAddress are required to enable OSPF" } if ( $PsBoundParameters.ContainsKey('ProtocolAddress') ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::protocolAddress')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::protocolAddress')) { # element exists. Update it. $ospf.protocolAddress = $ProtocolAddress.ToString().ToLower() } @@ -20246,7 +20396,7 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey('ForwardingAddress') ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::forwardingAddress')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::forwardingAddress')) { # element exists. Update it. $ospf.forwardingAddress = $ForwardingAddress.ToString().ToLower() } @@ -20260,16 +20410,16 @@ function Set-NsxLogicalRouterRouting { if ( $PsBoundParameters.ContainsKey('EnableBGP')) { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::bgp') if ( -not $bgp ) { #bgp node does not exist. [System.XML.XMLElement]$bgp = $_LogicalRouterRouting.ownerDocument.CreateElement("bgp") - $_LogicalRouterRouting.appendChild($bgp) | out-null + $_LogicalRouterRouting.appendChild($bgp) | Out-Null } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::enabled')) { #Enabled element exists. Update it. $bgp.enabled = $EnableBGP.ToString().ToLower() } @@ -20279,8 +20429,8 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey("LocalAS")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::localAS')) { - #LocalAS element exists, update it. + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::localAS')) { + #LocalAS element exists, update it. $bgp.localAS = $LocalAS.ToString() } else { @@ -20288,7 +20438,7 @@ function Set-NsxLogicalRouterRouting { Add-XmlElement -xmlRoot $bgp -xmlElementName "localAS" -xmlElementText $LocalAS.ToString() } } - elseif ( (-not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::localAS')) -and $EnableBGP )) { + elseif ( (-not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::localAS')) -and $EnableBGP )) { throw "Existing configuration has no Local AS number specified. Local AS must be set to enable BGP." } @@ -20304,7 +20454,7 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey("EnableBgpRouteRedistribution")) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::bgp/redistribution/enabled') ) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::bgp/redistribution/enabled') ) { throw "BGP must have been configured at least once to enable/disable BGP route redistribution. Enable BGP and try again." } @@ -20324,10 +20474,10 @@ function Set-NsxLogicalRouterRouting { $PsBoundParameters.ContainsKey("DefaultGatewayAdminDistance") ) { #Check for and create if required the defaultRoute element. first. - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting.staticRouting -Query 'child::defaultRoute')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting.staticRouting -query 'child::defaultRoute')) { #defaultRoute element does not exist $defaultRoute = $_LogicalRouterRouting.ownerDocument.CreateElement('defaultRoute') - $_LogicalRouterRouting.staticRouting.AppendChild($defaultRoute) | out-null + $_LogicalRouterRouting.staticRouting.AppendChild($defaultRoute) | Out-Null } else { #defaultRoute element exists @@ -20335,7 +20485,7 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey("DefaultGatewayVnic") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'child::vnic')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'child::vnic')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "vnic" -xmlElementText $DefaultGatewayVnic.ToString() } @@ -20346,7 +20496,7 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey("DefaultGatewayAddress") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'child::gatewayAddress')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'child::gatewayAddress')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "gatewayAddress" -xmlElementText $DefaultGatewayAddress.ToString() } @@ -20357,7 +20507,7 @@ function Set-NsxLogicalRouterRouting { } if ( $PsBoundParameters.ContainsKey("DefaultGatewayDescription") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'child::description')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'child::description')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "description" -xmlElementText $DefaultGatewayDescription } @@ -20367,7 +20517,7 @@ function Set-NsxLogicalRouterRouting { } } if ( $PsBoundParameters.ContainsKey("DefaultGatewayMTU") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'child::mtu')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'child::mtu')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "mtu" -xmlElementText $DefaultGatewayMTU.ToString() } @@ -20377,7 +20527,7 @@ function Set-NsxLogicalRouterRouting { } } if ( $PsBoundParameters.ContainsKey("DefaultGatewayAdminDistance") ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -Query 'child::adminDistance')) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $defaultRoute -query 'child::adminDistance')) { #element does not exist Add-XmlElement -xmlRoot $defaultRoute -xmlElementName "adminDistance" -xmlElementText $DefaultGatewayAdminDistance.ToString() } @@ -20392,7 +20542,7 @@ function Set-NsxLogicalRouterRouting { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -20402,10 +20552,10 @@ function Set-NsxLogicalRouterRouting { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting } } @@ -20437,9 +20587,9 @@ function Get-NsxLogicalRouterRouting { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouter $_ })] - [System.Xml.XmlElement]$LogicalRouter + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouter $_ })] + [System.Xml.XmlElement]$LogicalRouter ) begin { @@ -20487,15 +20637,15 @@ function Get-NsxLogicalRouterStaticRoute { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Network, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [ipAddress]$NextHop + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Network, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [ipAddress]$NextHop ) @@ -20508,18 +20658,18 @@ function Get-NsxLogicalRouterStaticRoute { #consistent readable output $_LogicalRouterStaticRouting = ($LogicalRouterRouting.staticRouting.CloneNode($True)) - $LogicalRouterStaticRoutes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterStaticRouting -Query 'child::staticRoutes') + $LogicalRouterStaticRoutes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterStaticRouting -query 'child::staticRoutes') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called route. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterStaticRoutes -Query 'child::route')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterStaticRoutes -query 'child::route')) { $RouteCollection = $LogicalRouterStaticRoutes.route if ( $PsBoundParameters.ContainsKey('Network')) { - $RouteCollection = $RouteCollection | where-object { $_.network -eq $Network } + $RouteCollection = $RouteCollection | Where-Object { $_.network -eq $Network } } if ( $PsBoundParameters.ContainsKey('NextHop')) { - $RouteCollection = $RouteCollection | where-object { $_.nextHop -eq $NextHop } + $RouteCollection = $RouteCollection | Where-Object { $_.nextHop -eq $NextHop } } foreach ( $StaticRoute in $RouteCollection ) { @@ -20556,34 +20706,34 @@ function New-NsxLogicalRouterStaticRoute { Add a new static route to LogicalRouter LogicalRouter01 for 1.1.1.0/24 via 10.0.0.200 #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [ValidateRange(0,200)] - [int]$Vnic, - [Parameter (Mandatory=$False)] - [ValidateRange(0,9128)] - [int]$MTU, - [Parameter (Mandatory=$False)] - [string]$Description, - [Parameter (Mandatory=$True)] - [ipAddress]$NextHop, - [Parameter (Mandatory=$True)] - [string]$Network, - [Parameter (Mandatory=$False)] - [ValidateRange(0,255)] - [int]$AdminDistance, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 200)] + [int]$Vnic, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 9128)] + [int]$MTU, + [Parameter (Mandatory = $False)] + [string]$Description, + [Parameter (Mandatory = $True)] + [ipAddress]$NextHop, + [Parameter (Mandatory = $True)] + [string]$Network, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 255)] + [int]$AdminDistance, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -20596,7 +20746,7 @@ function New-NsxLogicalRouterStaticRoute { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -20606,7 +20756,7 @@ function New-NsxLogicalRouterStaticRoute { #Need to do an xpath query here rather than use PoSH dot notation to get the static route element, #as it might be empty, and PoSH silently turns an empty element into a string object, which is rather not what we want... :| - $StaticRoutes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting.staticRouting -Query 'child::staticRoutes') + $StaticRoutes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting.staticRouting -query 'child::staticRoutes') $StaticRoutes.AppendChild($Route) | Out-Null Add-XmlElement -xmlRoot $Route -xmlElementName "network" -xmlElementText $Network.ToString() @@ -20632,7 +20782,7 @@ function New-NsxLogicalRouterStaticRoute { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -20642,10 +20792,10 @@ function New-NsxLogicalRouterStaticRoute { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterStaticRoute -Network $Network -NextHop $NextHop + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterStaticRoute -Network $Network -NextHop $NextHop } } @@ -20682,19 +20832,19 @@ function Remove-NsxLogicalRouterStaticRoute { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterStaticRoute $_ })] - [System.Xml.XmlElement]$StaticRoute, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterStaticRoute $_ })] + [System.Xml.XmlElement]$StaticRoute, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -20704,27 +20854,27 @@ function Remove-NsxLogicalRouterStaticRoute { #Get the routing config for our LogicalRouter $logicalrouterId = $StaticRoute.logicalrouterId - $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterRouting + $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterRouting #Remove the logicalrouterId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::logicalrouterId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::logicalrouterId')) ) | Out-Null #Need to do an xpath query here to query for a route that matches the one passed in. #Union of nextHop and network should be unique $xpathQuery = "//staticRoutes/route[nextHop=`"$($StaticRoute.nextHop)`" and network=`"$($StaticRoute.network)`"]" - write-debug "XPath query for route nodes to remove is: $xpathQuery" - $RouteToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.staticRouting -Query $xpathQuery) + Write-Debug "XPath query for route nodes to remove is: $xpathQuery" + $RouteToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.staticRouting -query $xpathQuery) if ( $RouteToRemove ) { - write-debug "RouteToRemove Element is: `n $($RouteToRemove.OuterXml | format-xml) " + Write-Debug "RouteToRemove Element is: `n $($RouteToRemove.OuterXml | Format-XML) " $routing.staticRouting.staticRoutes.RemoveChild($RouteToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -20734,9 +20884,9 @@ function Remove-NsxLogicalRouterStaticRoute { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -20785,15 +20935,15 @@ function Get-NsxLogicalRouterPrefix { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Network + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Network ) @@ -20806,20 +20956,20 @@ function Get-NsxLogicalRouterPrefix { #consistent readable output $_GlobalRoutingConfig = ($LogicalRouterRouting.routingGlobalConfig.CloneNode($True)) - $IpPrefixes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_GlobalRoutingConfig -Query 'child::ipPrefixes') + $IpPrefixes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_GlobalRoutingConfig -query 'child::ipPrefixes') #IPPrefixes may not exist... if ( $IPPrefixes ) { #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called ipPrefix. - If ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $IpPrefixes -Query 'child::ipPrefix')) { + If ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $IpPrefixes -query 'child::ipPrefix')) { $PrefixCollection = $IPPrefixes.ipPrefix if ( $PsBoundParameters.ContainsKey('Network')) { - $PrefixCollection = $PrefixCollection | where-object { $_.ipAddress -eq $Network } + $PrefixCollection = $PrefixCollection | Where-Object { $_.ipAddress -eq $Network } } if ( $PsBoundParameters.ContainsKey('Name')) { - $PrefixCollection = $PrefixCollection | where-object { $_.name -eq $Name } + $PrefixCollection = $PrefixCollection | Where-Object { $_.name -eq $Name } } foreach ( $Prefix in $PrefixCollection ) { @@ -20853,25 +21003,25 @@ function New-NsxLogicalRouterPrefix { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [switch]$Confirm=$true, - [Parameter (Mandatory=$True)] - [ValidateNotNullorEmpty()] - [string]$Name, - [Parameter (Mandatory=$True)] - [ValidateNotNullorEmpty()] - [string]$Network, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [switch]$Confirm = $true, + [Parameter (Mandatory = $True)] + [ValidateNotNullorEmpty()] + [string]$Name, + [Parameter (Mandatory = $True)] + [ValidateNotNullorEmpty()] + [string]$Network, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -20884,11 +21034,11 @@ function New-NsxLogicalRouterPrefix { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Need to do an xpath query here rather than use PoSH dot notation to get the IP prefix element, #as it might be empty or not exist, and PoSH silently turns an empty element into a string object, which is rather not what we want... :| - $ipPrefixes = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting.routingGlobalConfig -Query 'child::ipPrefixes') + $ipPrefixes = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting.routingGlobalConfig -query 'child::ipPrefixes') if ( -not $ipPrefixes ) { #Create the ipPrefixes element $ipPrefixes = $_LogicalRouterRouting.ownerDocument.CreateElement('ipPrefixes') @@ -20906,7 +21056,7 @@ function New-NsxLogicalRouterPrefix { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -20916,10 +21066,10 @@ function New-NsxLogicalRouterPrefix { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterPrefix -Network $Network -Name $Name + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterPrefix -Network $Network -Name $Name } } @@ -20948,19 +21098,19 @@ function Remove-NsxLogicalRouterPrefix { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterPrefix $_ })] - [System.Xml.XmlElement]$Prefix, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterPrefix $_ })] + [System.Xml.XmlElement]$Prefix, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -20970,27 +21120,27 @@ function Remove-NsxLogicalRouterPrefix { #Get the routing config for our LogicalRouter $logicalrouterId = $Prefix.logicalrouterId - $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterRouting + $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterRouting #Remove the logicalrouterId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::logicalrouterId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::logicalrouterId')) ) | Out-Null #Need to do an xpath query here to query for a prefix that matches the one passed in. #Union of nextHop and network should be unique $xpathQuery = "/routingGlobalConfig/ipPrefixes/ipPrefix[name=`"$($Prefix.name)`" and ipAddress=`"$($Prefix.ipAddress)`"]" - write-debug "XPath query for prefix nodes to remove is: $xpathQuery" - $PrefixToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query $xpathQuery) + Write-Debug "XPath query for prefix nodes to remove is: $xpathQuery" + $PrefixToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query $xpathQuery) if ( $PrefixToRemove ) { - write-debug "PrefixToRemove Element is: `n $($PrefixToRemove.OuterXml | format-xml) " + Write-Debug "PrefixToRemove Element is: `n $($PrefixToRemove.OuterXml | Format-XML) " $routing.routingGlobalConfig.ipPrefixes.RemoveChild($PrefixToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -21000,9 +21150,9 @@ function Remove-NsxLogicalRouterPrefix { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -21040,9 +21190,9 @@ function Get-NsxLogicalRouterBgp { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting ) begin { @@ -21054,8 +21204,8 @@ function Get-NsxLogicalRouterBgp { #We append the LogicalRouter-id to the associated Routing config XML to enable pipeline workflows and #consistent readable output - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::bgp')) { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::bgp').CloneNode($True) + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::bgp')) { + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::bgp').CloneNode($True) Add-XmlElement -xmlRoot $bgp -xmlElementName "logicalrouterId" -xmlElementText $LogicalRouterRouting.LogicalRouterId $bgp } @@ -21082,37 +21232,37 @@ function Set-NsxLogicalRouterBgp { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$EnableBGP, - [Parameter (Mandatory=$False)] - [IpAddress]$RouterId, - [Parameter (Mandatory=$False)] - [ValidateRange(0,65535)] - [int]$LocalAS, - [Parameter (Mandatory=$False)] - [switch]$GracefulRestart, - [Parameter (Mandatory=$False)] - [switch]$DefaultOriginate, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$EnableBGP, + [Parameter (Mandatory = $False)] + [IpAddress]$RouterId, + [Parameter (Mandatory = $False)] + [ValidateRange(0, 65535)] + [int]$LocalAS, + [Parameter (Mandatory = $False)] + [switch]$GracefulRestart, + [Parameter (Mandatory = $False)] + [switch]$DefaultOriginate, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { if ( $DefaultOriginate ) { if ( -not $connection.version ) { - write-warning "Setting defaultOriginate on a logical router is not supported NSX 6.3.0 or later and current NSX version could not be determined." + Write-Warning "Setting defaultOriginate on a logical router is not supported NSX 6.3.0 or later and current NSX version could not be determined." } elseif ( [version]$connection.version -ge [version]"6.3.0") { throw "Setting defaultOriginate on a logical router is not supported NSX 6.3.0 or later." @@ -21127,21 +21277,21 @@ function Set-NsxLogicalRouterBgp { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::bgp') if ( -not $bgp ) { #bgp node does not exist. [System.XML.XMLElement]$bgp = $_LogicalRouterRouting.ownerDocument.CreateElement("bgp") - $_LogicalRouterRouting.appendChild($bgp) | out-null + $_LogicalRouterRouting.appendChild($bgp) | Out-Null } # Check bgp enablement if ($PsBoundParameters.ContainsKey('EnableBGP')) { # BGP option is specified - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::enabled')) { #Enabled element exists. Update it. $bgp.enabled = $EnableBGP.ToString().ToLower() } @@ -21150,11 +21300,12 @@ function Set-NsxLogicalRouterBgp { Add-XmlElement -xmlRoot $bgp -xmlElementName "enabled" -xmlElementText $EnableBGP.ToString().ToLower() } } - elseif (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'descendant::enabled') { + elseif (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'descendant::enabled') { # BGP option is not specified but enabled if ( $bgp.enabled -eq 'true' ) { - # Assume bgp is already enabled. - } else { + # Assume bgp is already enabled. + } + else { throw "EnableBGP is not specified or BGP is not enabled on logicalrouter $logicalrouterID. Please specify option EnableBGP" } } @@ -21162,7 +21313,7 @@ function Set-NsxLogicalRouterBgp { throw "EnableBGP is not specified or BGP is not enabled on logicalrouter $logicalrouterID. Please specify option EnableBGP" } $xmlGlobalConfig = $_LogicalRouterRouting.routingGlobalConfig - $xmlRouterId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -Query 'child::routerId') + $xmlRouterId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -query 'child::routerId') if ( $EnableBGP ) { if ( -not ($xmlRouterId -or $PsBoundParameters.ContainsKey("RouterId"))) { #Existing config missing and no new value set... @@ -21174,14 +21325,14 @@ function Set-NsxLogicalRouterBgp { if ($xmlRouterId) { $xmlRouterId = $RouterId.IPAddresstoString } - else{ + else { Add-XmlElement -xmlRoot $xmlGlobalConfig -xmlElementName "routerId" -xmlElementText $RouterId.IPAddresstoString } } } if ( $PsBoundParameters.ContainsKey("LocalAS")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::localAS')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::localAS')) { #LocalAS element exists, update it. $bgp.localAS = $LocalAS.ToString() } @@ -21190,12 +21341,12 @@ function Set-NsxLogicalRouterBgp { Add-XmlElement -xmlRoot $bgp -xmlElementName "localAS" -xmlElementText $LocalAS.ToString() } } - elseif ( (-not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::localAS')) -and $EnableBGP )) { + elseif ( (-not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::localAS')) -and $EnableBGP )) { throw "Existing configuration has no Local AS number specified. Local AS must be set to enable BGP." } if ( $PsBoundParameters.ContainsKey("GracefulRestart")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::gracefulRestart')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::gracefulRestart')) { #element exists, update it. $bgp.gracefulRestart = $GracefulRestart.ToString().ToLower() } @@ -21206,7 +21357,7 @@ function Set-NsxLogicalRouterBgp { } if ( $PsBoundParameters.ContainsKey("DefaultOriginate")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::defaultOriginate')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::defaultOriginate')) { #element exists, update it. $bgp.defaultOriginate = $DefaultOriginate.ToString().ToLower() } @@ -21220,7 +21371,7 @@ function Set-NsxLogicalRouterBgp { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -21230,10 +21381,10 @@ function Set-NsxLogicalRouterBgp { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterBgp + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterBgp } } @@ -21276,18 +21427,18 @@ function Get-NsxLogicalRouterBgpNeighbour { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [String]$Network, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [ipAddress]$IpAddress, - [Parameter (Mandatory=$false)] - [ValidateRange(0,65535)] - [int]$RemoteAS + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [String]$Network, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [ipAddress]$IpAddress, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 65535)] + [int]$RemoteAS ) begin { @@ -21295,23 +21446,23 @@ function Get-NsxLogicalRouterBgpNeighbour { process { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::bgp') if ( $bgp ) { $_bgp = $bgp.CloneNode($True) - $BgpNeighbours = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_bgp -Query 'child::bgpNeighbours') + $BgpNeighbours = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_bgp -query 'child::bgpNeighbours') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called bgpNeighbour. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $BgpNeighbours -Query 'child::bgpNeighbour')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $BgpNeighbours -query 'child::bgpNeighbour')) { $NeighbourCollection = $BgpNeighbours.bgpNeighbour if ( $PsBoundParameters.ContainsKey('IpAddress')) { - $NeighbourCollection = $NeighbourCollection | where-object { $_.ipAddress -eq $IpAddress } + $NeighbourCollection = $NeighbourCollection | Where-Object { $_.ipAddress -eq $IpAddress } } if ( $PsBoundParameters.ContainsKey('RemoteAS')) { - $NeighbourCollection = $NeighbourCollection | where-object { $_.remoteAS -eq $RemoteAS } + $NeighbourCollection = $NeighbourCollection | Where-Object { $_.remoteAS -eq $RemoteAS } } foreach ( $Neighbour in $NeighbourCollection ) { @@ -21357,44 +21508,44 @@ function New-NsxLogicalRouterBgpNeighbour { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$true)] - [ValidateNotNullorEmpty()] - [ipAddress]$IpAddress, - [Parameter (Mandatory=$true)] - [ValidateRange(0,65535)] - [int]$RemoteAS, - [Parameter (Mandatory=$true)] - [ValidateNotNullorEmpty()] - [ipAddress]$ForwardingAddress, - [Parameter (Mandatory=$true)] - [ValidateNotNullorEmpty()] - [ipAddress]$ProtocolAddress, - [Parameter (Mandatory=$false)] - [ValidateRange(0,65535)] - [int]$Weight, - [Parameter (Mandatory=$false)] - [ValidateRange(2,65535)] - [int]$HoldDownTimer, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65534)] - [int]$KeepAliveTimer, - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [string]$Password, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $true)] + [ValidateNotNullorEmpty()] + [ipAddress]$IpAddress, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 65535)] + [int]$RemoteAS, + [Parameter (Mandatory = $true)] + [ValidateNotNullorEmpty()] + [ipAddress]$ForwardingAddress, + [Parameter (Mandatory = $true)] + [ValidateNotNullorEmpty()] + [ipAddress]$ProtocolAddress, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 65535)] + [int]$Weight, + [Parameter (Mandatory = $false)] + [ValidateRange(2, 65535)] + [int]$HoldDownTimer, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65534)] + [int]$KeepAliveTimer, + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [string]$Password, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -21407,16 +21558,16 @@ function New-NsxLogicalRouterBgpNeighbour { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Create the new bgpNeighbour element. $Neighbour = $_LogicalRouterRouting.ownerDocument.CreateElement('bgpNeighbour') #Need to do an xpath query here rather than use PoSH dot notation to get the bgp element, #as it might not exist which wil cause PoSH to throw in stric mode. - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::bgp') if ( $bgp ) { - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bgp -Query 'child::bgpNeighbours').AppendChild($Neighbour) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bgp -query 'child::bgpNeighbours').AppendChild($Neighbour) | Out-Null Add-XmlElement -xmlRoot $Neighbour -xmlElementName "ipAddress" -xmlElementText $IpAddress.ToString() Add-XmlElement -xmlRoot $Neighbour -xmlElementName "remoteAS" -xmlElementText $RemoteAS.ToString() @@ -21445,7 +21596,7 @@ function New-NsxLogicalRouterBgpNeighbour { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -21455,10 +21606,10 @@ function New-NsxLogicalRouterBgpNeighbour { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterBgpNeighbour -IpAddress $IpAddress -RemoteAS $RemoteAS + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterBgpNeighbour -IpAddress $IpAddress -RemoteAS $RemoteAS } } else { @@ -21495,19 +21646,19 @@ function Remove-NsxLogicalRouterBgpNeighbour { PS C:\> Get-NsxLogicalRouter LogicalRouter01 | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterBgpNeighbour | where-object { $_.ipaddress -eq '1.1.1.2' } | Remove-NsxLogicalRouterBgpNeighbour #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterBgpNeighbour $_ })] - [System.Xml.XmlElement]$BgpNeighbour, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterBgpNeighbour $_ })] + [System.Xml.XmlElement]$BgpNeighbour, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -21517,13 +21668,13 @@ function Remove-NsxLogicalRouterBgpNeighbour { #Get the routing config for our LogicalRouter $logicalrouterId = $BgpNeighbour.logicalrouterId - $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterRouting + $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterRouting #Remove the logicalrouterId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::logicalrouterId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::logicalrouterId')) ) | Out-Null #Validate the BGP node exists on the logicalrouter - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::bgp')) { throw "BGP is not enabled on ESG $logicalrouterId. Enable BGP and try again." } + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::bgp')) { throw "BGP is not enabled on ESG $logicalrouterId. Enable BGP and try again." } #Need to do an xpath query here to query for a bgp neighbour that matches the one passed in. #Union of ipaddress and remote AS should be unique (though this is not enforced by the API, @@ -21533,19 +21684,19 @@ function Remove-NsxLogicalRouterBgpNeighbour { #matching on filters to better handle uniquness amongst bgp neighbours with same ip and remoteAS $xpathQuery = "//bgpNeighbours/bgpNeighbour[ipAddress=`"$($BgpNeighbour.ipAddress)`" and remoteAS=`"$($BgpNeighbour.remoteAS)`"]" - write-debug "XPath query for neighbour nodes to remove is: $xpathQuery" - $NeighbourToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.bgp -Query $xpathQuery) + Write-Debug "XPath query for neighbour nodes to remove is: $xpathQuery" + $NeighbourToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.bgp -query $xpathQuery) if ( $NeighbourToRemove ) { - write-debug "NeighbourToRemove Element is: `n $($NeighbourToRemove.OuterXml | format-xml) " + Write-Debug "NeighbourToRemove Element is: `n $($NeighbourToRemove.OuterXml | Format-XML) " $routing.bgp.bgpNeighbours.RemoveChild($NeighbourToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -21555,9 +21706,9 @@ function Remove-NsxLogicalRouterBgpNeighbour { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -21595,9 +21746,9 @@ function Get-NsxLogicalRouterOspf { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting ) begin { @@ -21609,7 +21760,7 @@ function Get-NsxLogicalRouterOspf { #We append the LogicalRouter-id to the associated Routing config XML to enable pipeline workflows and #consistent readable output - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::ospf')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::ospf')) { $ospf = $LogicalRouterRouting.ospf.CloneNode($True) Add-XmlElement -xmlRoot $ospf -xmlElementName "logicalrouterId" -xmlElementText $LogicalRouterRouting.LogicalRouterId $ospf @@ -21638,40 +21789,40 @@ function Set-NsxLogicalRouterOspf { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$EnableOSPF, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [ipAddress]$ProtocolAddress, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [ipAddress]$ForwardingAddress, - [Parameter (Mandatory=$False)] - [IpAddress]$RouterId, - [Parameter (Mandatory=$False)] - [switch]$GracefulRestart, - [Parameter (Mandatory=$False)] - [switch]$DefaultOriginate, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$EnableOSPF, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [ipAddress]$ProtocolAddress, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [ipAddress]$ForwardingAddress, + [Parameter (Mandatory = $False)] + [IpAddress]$RouterId, + [Parameter (Mandatory = $False)] + [switch]$GracefulRestart, + [Parameter (Mandatory = $False)] + [switch]$DefaultOriginate, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { if ( $DefaultOriginate ) { if ( -not $connection.version ) { - write-warning "Setting defaultOriginate on a logical router is not supported NSX 6.3.0 or later and current NSX version could not be determined." + Write-Warning "Setting defaultOriginate on a logical router is not supported NSX 6.3.0 or later and current NSX version could not be determined." } elseif ( [version]$connection.version -ge [version]"6.3.0") { throw "Setting defaultOriginate on a logical router is not supported NSX 6.3.0 or later." @@ -21686,18 +21837,18 @@ function Set-NsxLogicalRouterOspf { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::ospf') if ( -not $ospf ) { #ospf node does not exist. [System.XML.XMLElement]$ospf = $_LogicalRouterRouting.ownerDocument.CreateElement("ospf") - $_LogicalRouterRouting.appendChild($ospf) | out-null + $_LogicalRouterRouting.appendChild($ospf) | Out-Null } if ( $PsBoundParameters.ContainsKey('EnableOSPF') ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::enabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::enabled')) { #Enabled element exists. Update it. $ospf.enabled = $EnableOSPF.ToString().ToLower() } @@ -21705,28 +21856,30 @@ function Set-NsxLogicalRouterOspf { #Enabled element does not exist... Add-XmlElement -xmlRoot $ospf -xmlElementName "enabled" -xmlElementText $EnableOSPF.ToString().ToLower() } - } - elseif ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::enabled')) { - # OSPF option is not specified but enabled - if ( $ospf.enabled -eq 'true' ) { - # Assume ospf is already enabled. - } else { - throw "EnableOSPF is not specified or OSPF is not enabled on logicalrouter $logicalrouterID. Please specify option EnableOSPF" } - } else { - throw "EnableOSPF is not specified or OSPF is not enabled on logicalrouter $logicalrouterID. Please specify option EnableOSPF" - } + elseif ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::enabled')) { + # OSPF option is not specified but enabled + if ( $ospf.enabled -eq 'true' ) { + # Assume ospf is already enabled. + } + else { + throw "EnableOSPF is not specified or OSPF is not enabled on logicalrouter $logicalrouterID. Please specify option EnableOSPF" + } + } + else { + throw "EnableOSPF is not specified or OSPF is not enabled on logicalrouter $logicalrouterID. Please specify option EnableOSPF" + } - if ( $EnableOSPF -and (-not ($ProtocolAddress -or ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::protocolAddress'))))) { + if ( $EnableOSPF -and (-not ($ProtocolAddress -or ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::protocolAddress'))))) { throw "ProtocolAddress and ForwardingAddress are required to enable OSPF" } - if ( $EnableOSPF -and (-not ($ForwardingAddress -or ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::forwardingAddress'))))) { + if ( $EnableOSPF -and (-not ($ForwardingAddress -or ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::forwardingAddress'))))) { throw "ProtocolAddress and ForwardingAddress are required to enable OSPF" } if ( $PsBoundParameters.ContainsKey('ProtocolAddress') ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::protocolAddress')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::protocolAddress')) { # element exists. Update it. $ospf.protocolAddress = $ProtocolAddress.ToString().ToLower() } @@ -21737,7 +21890,7 @@ function Set-NsxLogicalRouterOspf { } if ( $PsBoundParameters.ContainsKey('ForwardingAddress') ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::forwardingAddress')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::forwardingAddress')) { # element exists. Update it. $ospf.forwardingAddress = $ForwardingAddress.ToString().ToLower() } @@ -21748,7 +21901,7 @@ function Set-NsxLogicalRouterOspf { } $xmlGlobalConfig = $_LogicalRouterRouting.routingGlobalConfig - $xmlRouterId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -Query 'child::routerId') + $xmlRouterId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlGlobalConfig -query 'child::routerId') if ( $EnableOSPF ) { if ( -not ($xmlRouterId -or $PsBoundParameters.ContainsKey("RouterId"))) { #Existing config missing and no new value set... @@ -21760,14 +21913,14 @@ function Set-NsxLogicalRouterOspf { if ($xmlRouterId) { $xmlRouterId = $RouterId.IPAddresstoString } - else{ + else { Add-XmlElement -xmlRoot $xmlGlobalConfig -xmlElementName "routerId" -xmlElementText $RouterId.IPAddresstoString } } } if ( $PsBoundParameters.ContainsKey("GracefulRestart")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::gracefulRestart')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::gracefulRestart')) { #element exists, update it. $ospf.gracefulRestart = $GracefulRestart.ToString().ToLower() } @@ -21778,7 +21931,7 @@ function Set-NsxLogicalRouterOspf { } if ( $PsBoundParameters.ContainsKey("DefaultOriginate")) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::defaultOriginate')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::defaultOriginate')) { #element exists, update it. $ospf.defaultOriginate = $DefaultOriginate.ToString().ToLower() } @@ -21793,7 +21946,7 @@ function Set-NsxLogicalRouterOspf { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -21803,10 +21956,10 @@ function Set-NsxLogicalRouterOspf { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterOspf + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterOspf } } @@ -21839,12 +21992,12 @@ function Get-NsxLogicalRouterOspfArea { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$false)] - [ValidateRange(0,4294967295)] - [int]$AreaId + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 4294967295)] + [int]$AreaId ) begin { @@ -21852,19 +22005,19 @@ function Get-NsxLogicalRouterOspfArea { process { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::ospf') if ( $ospf ) { $_ospf = $ospf.CloneNode($True) - $OspfAreas = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ospf -Query 'child::ospfAreas') + $OspfAreas = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ospf -query 'child::ospfAreas') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called ospfArea. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $OspfAreas -Query 'child::ospfArea')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $OspfAreas -query 'child::ospfArea')) { $AreaCollection = $OspfAreas.ospfArea if ( $PsBoundParameters.ContainsKey('AreaId')) { - $AreaCollection = $AreaCollection | where-object { $_.areaId -eq $AreaId } + $AreaCollection = $AreaCollection | Where-Object { $_.areaId -eq $AreaId } } foreach ( $Area in $AreaCollection ) { @@ -21908,19 +22061,19 @@ function Remove-NsxLogicalRouterOspfArea { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterOspfArea $_ })] - [System.Xml.XmlElement]$OspfArea, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterOspfArea $_ })] + [System.Xml.XmlElement]$OspfArea, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -21930,29 +22083,29 @@ function Remove-NsxLogicalRouterOspfArea { #Get the routing config for our LogicalRouter $logicalrouterId = $OspfArea.logicalrouterId - $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterRouting + $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterRouting #Remove the logicalrouterId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::logicalrouterId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::logicalrouterId')) ) | Out-Null #Validate the OSPF node exists on the logicalrouter - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::ospf')) { throw "OSPF is not enabled on ESG $logicalrouterId. Enable OSPF and try again." } + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::ospf')) { throw "OSPF is not enabled on ESG $logicalrouterId. Enable OSPF and try again." } if ( -not ($routing.ospf.enabled -eq 'true') ) { throw "OSPF is not enabled on ESG $logicalrouterId. Enable OSPF and try again." } $xpathQuery = "//ospfAreas/ospfArea[areaId=`"$($OspfArea.areaId)`"]" - write-debug "XPath query for area nodes to remove is: $xpathQuery" - $AreaToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -Query $xpathQuery) + Write-Debug "XPath query for area nodes to remove is: $xpathQuery" + $AreaToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -query $xpathQuery) if ( $AreaToRemove ) { - write-debug "AreaToRemove Element is: `n $($AreaToRemove.OuterXml | format-xml) " + Write-Debug "AreaToRemove Element is: `n $($AreaToRemove.OuterXml | Format-XML) " $routing.ospf.ospfAreas.RemoveChild($AreaToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -21962,9 +22115,9 @@ function Remove-NsxLogicalRouterOspfArea { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -22004,32 +22157,32 @@ function New-NsxLogicalRouterOspfArea { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$true)] - [ValidateRange(0,4294967295)] - [uint32]$AreaId, - [Parameter (Mandatory=$false)] - [ValidateSet("normal","nssa",IgnoreCase = $false)] - [string]$Type, - [Parameter (Mandatory=$false)] - [ValidateSet("none","password","md5",IgnoreCase = $false)] - [string]$AuthenticationType="none", - [Parameter (Mandatory=$false)] - [ValidateNotNullorEmpty()] - [string]$Password, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 4294967295)] + [uint32]$AreaId, + [Parameter (Mandatory = $false)] + [ValidateSet("normal", "nssa", IgnoreCase = $false)] + [string]$Type, + [Parameter (Mandatory = $false)] + [ValidateSet("none", "password", "md5", IgnoreCase = $false)] + [string]$AuthenticationType = "none", + [Parameter (Mandatory = $false)] + [ValidateNotNullorEmpty()] + [string]$Password, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -22042,16 +22195,16 @@ function New-NsxLogicalRouterOspfArea { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Create the new ospfArea element. $Area = $_LogicalRouterRouting.ownerDocument.CreateElement('ospfArea') #Need to do an xpath query here rather than use PoSH dot notation to get the ospf element, #as it might not exist which wil cause PoSH to throw in stric mode. - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::ospf') if ( $ospf ) { - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::ospfAreas').AppendChild($Area) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::ospfAreas').AppendChild($Area) | Out-Null Add-XmlElement -xmlRoot $Area -xmlElementName "areaId" -xmlElementText $AreaId.ToString() @@ -22076,7 +22229,7 @@ function New-NsxLogicalRouterOspfArea { throw "Must specify a password if Authentication type is not none." } $Authentication = $Area.ownerDocument.CreateElement("authentication") - $Area.AppendChild( $Authentication ) | out-null + $Area.AppendChild( $Authentication ) | Out-Null Add-XmlElement -xmlRoot $Authentication -xmlElementName "type" -xmlElementText $AuthenticationType Add-XmlElement -xmlRoot $Authentication -xmlElementName "value" -xmlElementText $Password @@ -22088,7 +22241,7 @@ function New-NsxLogicalRouterOspfArea { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -22098,10 +22251,10 @@ function New-NsxLogicalRouterOspfArea { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterOspfArea -AreaId $AreaId + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterOspfArea -AreaId $AreaId } } else { @@ -22143,15 +22296,15 @@ function Get-NsxLogicalRouterOspfInterface { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$false)] - [ValidateRange(0,4294967295)] - [int]$AreaId, - [Parameter (Mandatory=$false)] - [ValidateRange(0,200)] - [int]$vNicId + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 4294967295)] + [int]$AreaId, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 200)] + [int]$vNicId ) begin { @@ -22159,23 +22312,23 @@ function Get-NsxLogicalRouterOspfInterface { process { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::ospf') if ( $ospf ) { $_ospf = $ospf.CloneNode($True) - $OspfInterfaces = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ospf -Query 'child::ospfInterfaces') + $OspfInterfaces = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ospf -query 'child::ospfInterfaces') #Need to use an xpath query here, as dot notation will throw in strict mode if there is not childnode called ospfArea. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $OspfInterfaces -Query 'child::ospfInterface')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $OspfInterfaces -query 'child::ospfInterface')) { $InterfaceCollection = $OspfInterfaces.ospfInterface if ( $PsBoundParameters.ContainsKey('AreaId')) { - $InterfaceCollection = $InterfaceCollection | where-object { $_.areaId -eq $AreaId } + $InterfaceCollection = $InterfaceCollection | Where-Object { $_.areaId -eq $AreaId } } if ( $PsBoundParameters.ContainsKey('vNicId')) { - $InterfaceCollection = $InterfaceCollection | where-object { $_.vnic -eq $vNicId } + $InterfaceCollection = $InterfaceCollection | Where-Object { $_.vnic -eq $vNicId } } foreach ( $Interface in $InterfaceCollection ) { @@ -22224,19 +22377,19 @@ function Remove-NsxLogicalRouterOspfInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterOspfInterface $_ })] - [System.Xml.XmlElement]$OspfInterface, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterOspfInterface $_ })] + [System.Xml.XmlElement]$OspfInterface, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -22246,29 +22399,29 @@ function Remove-NsxLogicalRouterOspfInterface { #Get the routing config for our LogicalRouter $logicalrouterId = $OspfInterface.logicalrouterId - $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterRouting + $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterRouting #Remove the logicalrouterId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::logicalrouterId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::logicalrouterId')) ) | Out-Null #Validate the OSPF node exists on the logicalrouter - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::ospf')) { throw "OSPF is not enabled on ESG $logicalrouterId. Enable OSPF and try again." } + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::ospf')) { throw "OSPF is not enabled on ESG $logicalrouterId. Enable OSPF and try again." } if ( -not ($routing.ospf.enabled -eq 'true') ) { throw "OSPF is not enabled on ESG $logicalrouterId. Enable OSPF and try again." } $xpathQuery = "//ospfInterfaces/ospfInterface[areaId=`"$($OspfInterface.areaId)`"]" - write-debug "XPath query for interface nodes to remove is: $xpathQuery" - $InterfaceToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -Query $xpathQuery) + Write-Debug "XPath query for interface nodes to remove is: $xpathQuery" + $InterfaceToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing.ospf -query $xpathQuery) if ( $InterfaceToRemove ) { - write-debug "InterfaceToRemove Element is: `n $($InterfaceToRemove.OuterXml | format-xml) " + Write-Debug "InterfaceToRemove Element is: `n $($InterfaceToRemove.OuterXml | Format-XML) " $routing.ospf.ospfInterfaces.RemoveChild($InterfaceToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -22278,9 +22431,9 @@ function Remove-NsxLogicalRouterOspfInterface { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -22315,39 +22468,39 @@ function New-NsxLogicalRouterOspfInterface { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$true)] - [ValidateRange(0,4294967295)] - [uint32]$AreaId, - [Parameter (Mandatory=$true)] - [ValidateRange(0,200)] - [int]$Vnic, - [Parameter (Mandatory=$false)] - [ValidateRange(1,255)] - [int]$HelloInterval, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$DeadInterval, - [Parameter (Mandatory=$false)] - [ValidateRange(0,255)] - [int]$Priority, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$Cost, - [Parameter (Mandatory=$false)] - [switch]$IgnoreMTU, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 4294967295)] + [uint32]$AreaId, + [Parameter (Mandatory = $true)] + [ValidateRange(0, 200)] + [int]$Vnic, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 255)] + [int]$HelloInterval, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$DeadInterval, + [Parameter (Mandatory = $false)] + [ValidateRange(0, 255)] + [int]$Priority, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$Cost, + [Parameter (Mandatory = $false)] + [switch]$IgnoreMTU, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -22361,16 +22514,16 @@ function New-NsxLogicalRouterOspfInterface { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Create the new ospfInterface element. $Interface = $_LogicalRouterRouting.ownerDocument.CreateElement('ospfInterface') #Need to do an xpath query here rather than use PoSH dot notation to get the ospf element, #as it might not exist which wil cause PoSH to throw in stric mode. - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::ospf') if ( $ospf ) { - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ospf -Query 'child::ospfInterfaces').AppendChild($Interface) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ospf -query 'child::ospfInterfaces').AppendChild($Interface) | Out-Null Add-XmlElement -xmlRoot $Interface -xmlElementName "areaId" -xmlElementText $AreaId.ToString() Add-XmlElement -xmlRoot $Interface -xmlElementName "vnic" -xmlElementText $Vnic.ToString() @@ -22401,7 +22554,7 @@ function New-NsxLogicalRouterOspfInterface { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -22411,10 +22564,10 @@ function New-NsxLogicalRouterOspfInterface { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterOspfInterface -AreaId $AreaId + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterOspfInterface -AreaId $AreaId } } else { @@ -22452,14 +22605,14 @@ function Get-NsxLogicalRouterRedistributionRule { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$false)] - [ValidateSet("ospf","bgp")] - [string]$Learner, - [Parameter (Mandatory=$false)] - [int]$Id + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $false)] + [ValidateSet("ospf", "bgp")] + [string]$Learner, + [Parameter (Mandatory = $false)] + [int]$Id ) begin { @@ -22470,12 +22623,12 @@ function Get-NsxLogicalRouterRedistributionRule { #Rules can be defined in either ospf or bgp (isis as well, but who cares huh? :) ) if ( ( -not $PsBoundParameters.ContainsKey('Learner')) -or ($PsBoundParameters.ContainsKey('Learner') -and $Learner -eq 'ospf')) { - $ospf = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::ospf') + $ospf = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::ospf') if ( $ospf ) { $_ospf = $ospf.CloneNode($True) - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ospf -Query 'child::redistribution/rules/rule') ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ospf -query 'child::redistribution/rules/rule') ) { $OspfRuleCollection = $_ospf.redistribution.rules.rule @@ -22490,7 +22643,7 @@ function Get-NsxLogicalRouterRedistributionRule { } if ( $PsBoundParameters.ContainsKey('Id')) { - $OspfRuleCollection = $OspfRuleCollection | where-object { $_.id -eq $Id } + $OspfRuleCollection = $OspfRuleCollection | Where-Object { $_.id -eq $Id } } $OspfRuleCollection @@ -22500,11 +22653,11 @@ function Get-NsxLogicalRouterRedistributionRule { if ( ( -not $PsBoundParameters.ContainsKey('Learner')) -or ($PsBoundParameters.ContainsKey('Learner') -and $Learner -eq 'bgp')) { - $bgp = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -Query 'child::bgp') + $bgp = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LogicalRouterRouting -query 'child::bgp') if ( $bgp ) { $_bgp = $bgp.CloneNode($True) - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_bgp -Query 'child::redistribution/rules/rule') ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_bgp -query 'child::redistribution/rules/rule') ) { $BgpRuleCollection = $_bgp.redistribution.rules.rule @@ -22518,7 +22671,7 @@ function Get-NsxLogicalRouterRedistributionRule { } if ( $PsBoundParameters.ContainsKey('Id')) { - $BgpRuleCollection = $BgpRuleCollection | where-object { $_.id -eq $Id } + $BgpRuleCollection = $BgpRuleCollection | Where-Object { $_.id -eq $Id } } $BgpRuleCollection } @@ -22557,19 +22710,19 @@ function Remove-NsxLogicalRouterRedistributionRule { Remove all ospf redistribution rules from LogicalRouter01 #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRedistributionRule $_ })] - [System.Xml.XmlElement]$RedistributionRule, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRedistributionRule $_ })] + [System.Xml.XmlElement]$RedistributionRule, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -22579,13 +22732,13 @@ function Remove-NsxLogicalRouterRedistributionRule { #Get the routing config for our LogicalRouter $logicalrouterId = $RedistributionRule.logicalrouterId - $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterRouting + $routing = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterRouting #Remove the logicalrouterId element from the XML as we need to post it... - $routing.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query 'child::logicalrouterId')) ) | out-null + $routing.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query 'child::logicalrouterId')) ) | Out-Null #Validate the learner protocol node exists on the logicalrouter - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query "child::$($RedistributionRule.learner)")) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query "child::$($RedistributionRule.learner)")) { throw "Rule learner protocol $($RedistributionRule.learner) is not enabled on LogicalRouter $logicalrouterId. Use Get-NsxLogicalRouter | Get-NsxLogicalRouterrouting | Get-NsxLogicalRouterRedistributionRule to get the rule you want to remove." } @@ -22593,30 +22746,30 @@ function Remove-NsxLogicalRouterRedistributionRule { $xpathQuery = "child::$($RedistributionRule.learner)/redistribution/rules/rule[action=`"$($RedistributionRule.action)`"" $xPathQuery += " and from/connected=`"$($RedistributionRule.from.connected)`" and from/static=`"$($RedistributionRule.from.static)`"" $xPathQuery += " and from/ospf=`"$($RedistributionRule.from.ospf)`" and from/bgp=`"$($RedistributionRule.from.bgp)`"" - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -Query 'child::from/isis')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -query 'child::from/isis')) { $xPathQuery += " and from/isis=`"$($RedistributionRule.from.isis)`"" } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -Query 'child::prefixName')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $RedistributionRule -query 'child::prefixName')) { $xPathQuery += " and prefixName=`"$($RedistributionRule.prefixName)`"" } $xPathQuery += "]" - write-debug "XPath query for rule node to remove is: $xpathQuery" + Write-Debug "XPath query for rule node to remove is: $xpathQuery" - $RuleToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $routing -Query $xpathQuery) + $RuleToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $routing -query $xpathQuery) if ( $RuleToRemove ) { - write-debug "RuleToRemove Element is: `n $($RuleToRemove | format-xml) " + Write-Debug "RuleToRemove Element is: `n $($RuleToRemove | Format-XML) " $routing.$($RedistributionRule.Learner).redistribution.rules.RemoveChild($RuleToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/routing/config" $body = $routing.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -22626,9 +22779,9 @@ function Remove-NsxLogicalRouterRedistributionRule { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -22662,35 +22815,35 @@ function New-NsxLogicalRouterRedistributionRule { Create a new permit Redistribution Rule for prefix test (note, prefix must already exist, and is case sensistive) for ospf. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLogicalRouterRouting $_ })] - [System.Xml.XmlElement]$LogicalRouterRouting, - [Parameter (Mandatory=$True)] - [ValidateSet("ospf","bgp",IgnoreCase=$false)] - [String]$Learner, - [Parameter (Mandatory=$false)] - [String]$PrefixName, - [Parameter (Mandatory=$false)] - [switch]$FromConnected, - [Parameter (Mandatory=$false)] - [switch]$FromStatic, - [Parameter (Mandatory=$false)] - [switch]$FromOspf, - [Parameter (Mandatory=$false)] - [switch]$FromBgp, - [Parameter (Mandatory=$False)] - [ValidateSet("permit","deny",IgnoreCase=$false)] - [String]$Action="permit", - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalRouterRouting $_ })] + [System.Xml.XmlElement]$LogicalRouterRouting, + [Parameter (Mandatory = $True)] + [ValidateSet("ospf", "bgp", IgnoreCase = $false)] + [String]$Learner, + [Parameter (Mandatory = $false)] + [String]$PrefixName, + [Parameter (Mandatory = $false)] + [switch]$FromConnected, + [Parameter (Mandatory = $false)] + [switch]$FromStatic, + [Parameter (Mandatory = $false)] + [switch]$FromOspf, + [Parameter (Mandatory = $false)] + [switch]$FromBgp, + [Parameter (Mandatory = $False)] + [ValidateSet("permit", "deny", IgnoreCase = $false)] + [String]$Action = "permit", + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -22704,11 +22857,11 @@ function New-NsxLogicalRouterRedistributionRule { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterRouting.logicalrouterId - $_LogicalRouterRouting.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterRouting.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query 'child::logicalrouterId')) ) | Out-Null #Need to do an xpath query here rather than use PoSH dot notation to get the protocol element, #as it might not exist which wil cause PoSH to throw in stric mode. - $ProtocolElement = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -Query "child::$Learner") + $ProtocolElement = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterRouting -query "child::$Learner") if ( (-not $ProtocolElement) -or ($ProtocolElement.Enabled -ne 'true')) { @@ -22718,7 +22871,7 @@ function New-NsxLogicalRouterRedistributionRule { #Create the new rule element. $Rule = $_LogicalRouterRouting.ownerDocument.CreateElement('rule') - (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ProtocolElement -Query 'child::redistribution/rules').AppendChild($Rule) | Out-Null + (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ProtocolElement -query 'child::redistribution/rules').AppendChild($Rule) | Out-Null Add-XmlElement -xmlRoot $Rule -xmlElementName "action" -xmlElementText $Action if ( $PsBoundParameters.ContainsKey("PrefixName") ) { @@ -22728,7 +22881,7 @@ function New-NsxLogicalRouterRedistributionRule { #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. if ( $PsBoundParameters.ContainsKey('FromConnected') -or $PsBoundParameters.ContainsKey('FromStatic') -or - $PsBoundParameters.ContainsKey('FromOspf') -or $PsBoundParameters.ContainsKey('FromBgp') ) { + $PsBoundParameters.ContainsKey('FromOspf') -or $PsBoundParameters.ContainsKey('FromBgp') ) { $FromElement = $Rule.ownerDocument.CreateElement('from') $Rule.AppendChild($FromElement) | Out-Null @@ -22754,7 +22907,7 @@ function New-NsxLogicalRouterRedistributionRule { $body = $_LogicalRouterRouting.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -22764,10 +22917,10 @@ function New-NsxLogicalRouterRedistributionRule { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - (Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterRedistributionRule -Learner $Learner)[-1] + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + (Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterRouting | Get-NsxLogicalRouterRedistributionRule -Learner $Learner)[-1] } } @@ -22807,9 +22960,9 @@ function Get-NsxLogicalRouterBridging { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouter $_ })] - [System.Xml.XmlElement]$LogicalRouter + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouter $_ })] + [System.Xml.XmlElement]$LogicalRouter ) begin { @@ -22857,23 +23010,23 @@ function Set-NsxLogicalRouterBridging { Enable bridging on the LogicalRouter called BridgeRouter #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #LogicalRouter Bridging object as retrieved by Get-NsxLogicalRouterBridging - [ValidateScript({ ValidateLogicalRouterBridging $_ })] - [System.Xml.XmlElement]$LogicalRouterBridging, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$True)] - #Enable Bridge support. - [switch]$Enabled, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #LogicalRouter Bridging object as retrieved by Get-NsxLogicalRouterBridging + [ValidateScript( { ValidateLogicalRouterBridging $_ })] + [System.Xml.XmlElement]$LogicalRouterBridging, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $True)] + #Enable Bridge support. + [switch]$Enabled, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -22888,7 +23041,7 @@ function Set-NsxLogicalRouterBridging { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterBridging.logicalrouterId - $_LogicalRouterBridging.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterBridging -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterBridging.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterBridging -query 'child::logicalrouterId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -22901,7 +23054,7 @@ function Set-NsxLogicalRouterBridging { $body = $_LogicalRouterBridging.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -22911,10 +23064,10 @@ function Set-NsxLogicalRouterBridging { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterBridging + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterBridging } } @@ -22949,24 +23102,24 @@ function New-NsxLogicalRouterBridge { Create a bridge between vdportgroup $bridgepg1 and logical switch $bridgels1 on logicalrouter BridgeRouter. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLogicalRouterBridging $_ })] - [System.Xml.XmlElement]$LogicalRouterBridging, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$True)] - [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop]$PortGroup, - [Parameter (Mandatory=$True)] - [ValidateScript({ ValidateLogicalSwitchOrDistributedPortGroup $_ } )] - [System.Xml.XmlElement]$LogicalSwitch, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLogicalRouterBridging $_ })] + [System.Xml.XmlElement]$LogicalRouterBridging, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $True)] + [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedPortGroupInterop]$PortGroup, + [Parameter (Mandatory = $True)] + [ValidateScript( { ValidateLogicalSwitchOrDistributedPortGroup $_ } )] + [System.Xml.XmlElement]$LogicalSwitch, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -22979,7 +23132,7 @@ function New-NsxLogicalRouterBridge { #Store the logicalrouterId and remove it from the XML as we need to post it... $logicalrouterId = $_LogicalRouterBridging.logicalrouterId - $_LogicalRouterBridging.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterBridging -Query 'child::logicalrouterId')) ) | out-null + $_LogicalRouterBridging.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LogicalRouterBridging -query 'child::logicalrouterId')) ) | Out-Null #Create the new bridge element. $Bridge = $_LogicalRouterBridging.ownerDocument.CreateElement('bridge') @@ -22995,10 +23148,10 @@ function New-NsxLogicalRouterBridge { $URI = "/api/4.0/edges/$($LogicalRouterId)/bridging/config" $body = $_LogicalRouterBridging.OuterXml - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed - Get-NsxLogicalRouter -objectId $LogicalRouterId -connection $connection | Get-NsxLogicalRouterBridging | Get-NsxLogicalRouterBridge -Name $Name + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed + Get-NsxLogicalRouter -objectId $LogicalRouterId -Connection $connection | Get-NsxLogicalRouterBridging | Get-NsxLogicalRouterBridge -Name $Name } @@ -23032,19 +23185,19 @@ function Get-NsxLogicalRouterBridge { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #Logical Router Bridging Configuration as returned by Get-NsxLogicalRouterBridging - [ValidateScript({ ValidateLogicalRouterBridging $_ })] - [System.Xml.XmlElement]$LogicalRouterBridging, - [Parameter(Mandatory=$False, ParameterSetName="Name")] - #Bridge instance name - [string]$Name, - [Parameter(Mandatory=$False, ParameterSetName="BridgeId")] - #Bridge Instance Id - [int]$BridgeId + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #Logical Router Bridging Configuration as returned by Get-NsxLogicalRouterBridging + [ValidateScript( { ValidateLogicalRouterBridging $_ })] + [System.Xml.XmlElement]$LogicalRouterBridging, + [Parameter(Mandatory = $False, ParameterSetName = "Name")] + #Bridge instance name + [string]$Name, + [Parameter(Mandatory = $False, ParameterSetName = "BridgeId")] + #Bridge Instance Id + [int]$BridgeId ) @@ -23055,17 +23208,17 @@ function Get-NsxLogicalRouterBridge { process { $logicalrouterId = $LogicalRouterBridging.logicalrouterId - if ( Invoke-XpathQuery -Node $LogicalRouterBridging -Querymethod SelectNodes -Query "child::bridge") { + if ( Invoke-XpathQuery -Node $LogicalRouterBridging -QueryMethod SelectNodes -query "child::bridge") { #Add LogicalRouterId so we can easily retrieve later in a remove pipeline. foreach ( $bridge in $LogicalRouterBridging.bridge ) { Add-XmlElement -xmlRoot $Bridge -xmlElementName "logicalrouterId" -xmlElementText $logicalrouterId } if ( $PSBoundParameters.ContainsKey("Name")) { - $LogicalRouterBridging.bridge | where-object { $_.Name -eq $Name } + $LogicalRouterBridging.bridge | Where-Object { $_.Name -eq $Name } } elseif ( $PSBoundParameters.ContainsKey("BridgeId")) { - $LogicalRouterBridging.bridge | where-object { $_.bridgeId -eq $BridgeId } + $LogicalRouterBridging.bridge | Where-Object { $_.bridgeId -eq $BridgeId } } else { $LogicalRouterBridging.bridge @@ -23105,20 +23258,20 @@ function Remove-NsxLogicalRouterBridge { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - #The bridge instance to remove as retrieved by Get-NsxLogicalRouterBridge. - [ValidateScript({ ValidateLogicalRouterBridge $_ })] - [System.Xml.XmlElement]$BridgeInstance, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + #The bridge instance to remove as retrieved by Get-NsxLogicalRouterBridge. + [ValidateScript( { ValidateLogicalRouterBridge $_ })] + [System.Xml.XmlElement]$BridgeInstance, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -23128,23 +23281,23 @@ function Remove-NsxLogicalRouterBridge { #Get the routing config for our LogicalRouter $logicalrouterId = $BridgeInstance.logicalrouterId - $bridging = Get-NsxLogicalRouter -objectId $logicalrouterId -connection $connection | Get-NsxLogicalRouterBridging + $bridging = Get-NsxLogicalRouter -objectId $logicalrouterId -Connection $connection | Get-NsxLogicalRouterBridging #Remove the logicalrouterId element from the XML as we need to post it... - $bridging.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bridging -Query 'child::logicalrouterId')) ) | out-null + $bridging.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bridging -query 'child::logicalrouterId')) ) | Out-Null #Need to do an xpath query here to query for a bridge that matches the one passed in. - $BridgeToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $bridging -Query "child::bridge[bridgeId=`"$($BridgeInstance.bridgeId)`"]" ) + $BridgeToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $bridging -query "child::bridge[bridgeId=`"$($BridgeInstance.bridgeId)`"]" ) if ( $BridgeToRemove ) { - write-debug "$($MyInvocation.MyCommand.Name) : BridgeToRemove Element is: `n $($BridgeToRemove.OuterXml | format-xml) " + Write-Debug "$($MyInvocation.MyCommand.Name) : BridgeToRemove Element is: `n $($BridgeToRemove.OuterXml | Format-XML) " $bridging.RemoveChild($BridgeToRemove) | Out-Null $URI = "/api/4.0/edges/$($LogicalRouterId)/bridging/config" $body = $bridging.OuterXml if ( $confirm ) { - $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." + $message = "LogicalRouter routing update will modify existing LogicalRouter configuration." $question = "Proceed with Update of LogicalRouter $($LogicalRouterId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -23154,9 +23307,9 @@ function Remove-NsxLogicalRouterBridge { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update LogicalRouter $($LogicalRouterId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update LogicalRouter $($LogicalRouterId)" -completed + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update LogicalRouter $($LogicalRouterId)" -Completed } } else { @@ -23189,37 +23342,37 @@ function Get-NsxSecurityGroup { #> - [CmdLetBinding(DefaultParameterSetName="Default")] + [CmdLetBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$false,ParameterSetName="objectId")] - #Get SecurityGroups by objectid - [string]$objectId, - [Parameter (Mandatory=$false,ParameterSetName="Name", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] - #Get SecurityGroups by name - [string]$name, - [Parameter (Mandatory=$false)] - #ScopeId of IPSet. Can define multiple scopeIds in a list to iterate accross scopes. - [string[]]$scopeId, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] - #Return only Universal objects - [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] - #Return only Locally scoped objects - [switch]$LocalOnly, - [Parameter (Mandatory=$true, ParameterSetName="VirtualMachine", ValueFromPipeLine=$true)] - #Virtual Machine to check for group membership - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$false)] - #Include default system security group - [switch]$IncludeSystem=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, ParameterSetName = "objectId")] + #Get SecurityGroups by objectid + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] + #Get SecurityGroups by name + [string]$name, + [Parameter (Mandatory = $false)] + #ScopeId of IPSet. Can define multiple scopeIds in a list to iterate accross scopes. + [string[]]$scopeId, + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] + #Return only Universal objects + [switch]$UniversalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] + #Return only Locally scoped objects + [switch]$LocalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "VirtualMachine", ValueFromPipeLine = $true)] + #Virtual Machine to check for group membership + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, + [Parameter (Mandatory = $false)] + #Include default system security group + [switch]$IncludeSystem = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -23248,8 +23401,8 @@ function Get-NsxSecurityGroup { $VMMoRef = $VirtualMachine.ExtensionData.Moref.Value $uri = "/api/2.0/services/securitygroup/lookup/virtualmachine/$VMMoRef" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::securitygroup')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::securitygroup')) { $response.securitygroups.securityGroups.securityGroup } } @@ -23258,18 +23411,19 @@ function Get-NsxSecurityGroup { foreach ($scope in $scopeid ) { #All Security Groups $URI = "/api/2.0/services/securitygroup/scope/$scope" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::list/securitygroup')) { - if ( $Name ) { - $sg += $response.list.securitygroup | where-object { $_.name -eq $name } - } else { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::list/securitygroup')) { + if ( $Name ) { + $sg += $response.list.securitygroup | Where-Object { $_.name -eq $name } + } + else { $sg += $response.list.securitygroup } } } #Filter default if switch not set if ( -not $IncludeSystem ) { - $sg | where-object { ( $_.objectId -ne 'securitygroup-1') } + $sg | Where-Object { ( $_.objectId -ne 'securitygroup-1') } } else { $sg @@ -23279,13 +23433,13 @@ function Get-NsxSecurityGroup { #Just getting a single Security group $URI = "/api/2.0/services/securitygroup/$objectId" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::securitygroup')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::securitygroup')) { $sg = $response.securitygroup } #Filter default if switch not set if ( -not $IncludeSystem ) { - $sg | where-object { ( $_.objectId -ne 'securitygroup-1') } + $sg | Where-Object { ( $_.objectId -ne 'securitygroup-1') } } else { $sg @@ -23296,7 +23450,7 @@ function Get-NsxSecurityGroup { end {} } -function New-NsxSecurityGroup { +function New-NsxSecurityGroup { <# .SYNOPSIS @@ -23335,45 +23489,46 @@ function New-NsxSecurityGroup { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - #Name of the Security Group - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - #Optional description for the new Security Group - [ValidateNotNull()] - [string]$Description = "", - [Parameter (Mandatory=$false)] - #Static include membership - [ValidateScript({ ValidateSecurityGroupMember $_ })] - [object[]]$IncludeMember, - [Parameter (Mandatory=$false)] - #Static exclude membership - [ValidateScript({ ValidateSecurityGroupMember $_ })] - [object[]]$ExcludeMember, - [Parameter (Mandatory=$false)] - #Scope of object. For universal object creation, use the -Universal switch. - [ValidateScript({ + [Parameter (Mandatory = $true)] + #Name of the Security Group + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + #Optional description for the new Security Group + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $false)] + #Static include membership + [ValidateScript( { ValidateSecurityGroupMember $_ })] + [object[]]$IncludeMember, + [Parameter (Mandatory = $false)] + #Static exclude membership + [ValidateScript( { ValidateSecurityGroupMember $_ })] + [object[]]$ExcludeMember, + [Parameter (Mandatory = $false)] + #Scope of object. For universal object creation, use the -Universal switch. + [ValidateScript( { if ($_ -match "^globalroot-0$|universalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | universalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - #Create the IPSet as Universal object. - [switch]$Universal=$false, - [Parameter (Mandatory=$false)] - #Return only an object ID, not the full object. - [switch]$ReturnObjectIdOnly=$false, - [Parameter (Mandatory=$False)] - #Flag to allow static membership of Universal Security Tags and dynamic membership via VM Name. See https://blogs.vmware.com/networkvirtualization/2017/02/nsx-6-3-cross-vc-nsx-security-enhancements.html/ - [switch]$ActiveStandbyDeployment=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + #Create the IPSet as Universal object. + [switch]$Universal = $false, + [Parameter (Mandatory = $false)] + #Return only an object ID, not the full object. + [switch]$ReturnObjectIdOnly = $false, + [Parameter (Mandatory = $False)] + #Flag to allow static membership of Universal Security Tags and dynamic membership via VM Name. See https://blogs.vmware.com/networkvirtualization/2017/02/nsx-6-3-cross-vc-nsx-security-enhancements.html/ + [switch]$ActiveStandbyDeployment = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -23386,7 +23541,7 @@ function New-NsxSecurityGroup { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("securitygroup") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description @@ -23395,12 +23550,13 @@ function New-NsxSecurityGroup { foreach ( $Member in $IncludeMember) { [System.XML.XMLElement]$xmlMember = $XMLDoc.CreateElement("member") - $xmlroot.appendChild($xmlMember) | out-null + $xmlroot.appendChild($xmlMember) | Out-Null #This is probably not safe - need to review all possible input types to confirm. if ($Member -is [System.Xml.XmlElement] ) { Add-XmlElement -xmlRoot $xmlMember -xmlElementName "objectId" -xmlElementText $member.objectId - } else { + } + else { Add-XmlElement -xmlRoot $xmlMember -xmlElementName "objectId" -xmlElementText $member.ExtensionData.MoRef.Value } } @@ -23409,12 +23565,13 @@ function New-NsxSecurityGroup { if ( $excludeMember ) { foreach ( $Member in $ExcludeMember) { [System.XML.XMLElement]$xmlMember = $XMLDoc.CreateElement("excludeMember") - $xmlroot.appendChild($xmlMember) | out-null + $xmlroot.appendChild($xmlMember) | Out-Null #This is probably not safe - need to review all possible input types to confirm. if ($Member -is [System.Xml.XmlElement] ) { Add-XmlElement -xmlRoot $xmlMember -xmlElementName "objectId" -xmlElementText $member.objectId - } else { + } + else { Add-XmlElement -xmlRoot $xmlMember -xmlElementName "objectId" -xmlElementText $member.ExtensionData.MoRef.Value } } @@ -23422,24 +23579,24 @@ function New-NsxSecurityGroup { if (( $ActiveStandbyDeployment ) -and ( $Universal )) { [System.XML.XMLElement]$xmlMember = $XMLDoc.CreateElement("extendedAttributes") - $xmlroot.appendChild($xmlMember) | out-null + $xmlroot.appendChild($xmlMember) | Out-Null [System.XML.XMLElement]$xmlsubMember = $XMLDoc.CreateElement("extendedAttribute") Add-XmlElement -xmlRoot $xmlSubMember -xmlElementName "name" -xmlElementText "localMembersOnly" Add-XmlElement -xmlRoot $xmlSubMember -xmlElementName "value" -xmlElementText "true" - $xmlmember.appendChild($xmlsubMember) | out-null + $xmlmember.appendChild($xmlsubMember) | Out-Null } #Do the post $body = $xmlroot.OuterXml - if ( $universal ) { $scopeId = "universalroot-0"} + if ( $universal ) { $scopeId = "universalroot-0" } $URI = "/api/2.0/services/securitygroup/bulk/$($scopeId.ToLower())" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection if ( $ReturnObjectIdOnly) { $response.content } else { - Get-NsxSecuritygroup -objectId $response.content -connection $connection + Get-NsxSecurityGroup -objectId $response.content -Connection $connection } } end {} @@ -23473,23 +23630,23 @@ function Remove-NsxSecurityGroup { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #SecurityGroup object as returned by get-nsxsecuritygroup - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$False)] - #Disable confirmation prompt - [switch]$confirm=$true, - [Parameter (Mandatory=$False)] - #Force deletion of in use or system objects - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #SecurityGroup object as returned by get-nsxsecuritygroup + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $False)] + #Disable confirmation prompt + [switch]$confirm = $true, + [Parameter (Mandatory = $False)] + #Force deletion of in use or system objects + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -23500,11 +23657,11 @@ function Remove-NsxSecurityGroup { process { if (($SecurityGroup.ObjectId -eq 'securitygroup-1') -and ( -not $force)) { - write-warning "Not removing $($SecurityGroup.Name) as it is a default SecurityGroup. Use -Force to force deletion." + Write-Warning "Not removing $($SecurityGroup.Name) as it is a default SecurityGroup. Use -Force to force deletion." } else { if ( $confirm ) { - $message = "Security Group removal is permanent." + $message = "Security Group removal is permanent." $question = "Proceed with removal of Security group $($SecurityGroup.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -23522,9 +23679,9 @@ function Remove-NsxSecurityGroup { $URI = "/api/2.0/services/securitygroup/$($SecurityGroup.ObjectId)?force=false" } - Write-Progress -activity "Remove Security Group $($SecurityGroup.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Security Group $($SecurityGroup.Name)" -completed + Write-Progress -Activity "Remove Security Group $($SecurityGroup.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Security Group $($SecurityGroup.Name)" -Completed } } @@ -23569,13 +23726,13 @@ function Get-NsxSecurityGroupMemberTypes { param ( - [Parameter (Mandatory=$false)] - #Scopeid - default globalroot-0 - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + #Scopeid - default globalroot-0 + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -23584,7 +23741,7 @@ function Get-NsxSecurityGroupMemberTypes { process { $URI = "/api/2.0/services/securitygroup/scope/$scopeId/memberTypes" - $response = Invoke-NsxWebRequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection [xml]$Members = $response.Content $members.list.objecttype.typeName } @@ -23615,31 +23772,31 @@ function Add-NsxSecurityGroupMember { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #SecurityGroup whose membership is to be modified. - [ValidateNotNullOrEmpty()] - [object]$SecurityGroup, - [Parameter (Mandatory=$False)] - #Throw an error if the member already exists (by default will ignore) - [switch]$FailIfExists=$false, - [Parameter (Mandatory=$False)] - #The specified members are to be added to the security group as exclusions - [switch]$MemberIsExcluded=$false, - [Parameter (Mandatory=$true)] - #The member(s) to be added - [ValidateScript({ ValidateSecurityGroupMember $_ })] - [object[]]$Member, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #SecurityGroup whose membership is to be modified. + [ValidateNotNullOrEmpty()] + [object]$SecurityGroup, + [Parameter (Mandatory = $False)] + #Throw an error if the member already exists (by default will ignore) + [switch]$FailIfExists = $false, + [Parameter (Mandatory = $False)] + #The specified members are to be added to the security group as exclusions + [switch]$MemberIsExcluded = $false, + [Parameter (Mandatory = $true)] + #The member(s) to be added + [ValidateScript( { ValidateSecurityGroupMember $_ })] + [object[]]$Member, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { #Populate the global membertype cache if not already done #Using the API rather than hardcoding incase this changes with versions of NSX - if ( -not (test-path Variable:\NsxMemberTypes) ) { + if ( -not (Test-Path Variable:\NsxMemberTypes) ) { $script:NsxMemberTypes = Get-NsxSecurityGroupMemberTypes } } @@ -23652,7 +23809,7 @@ function Add-NsxSecurityGroupMember { } elseif ( ($securityGroup -is [string]) -and ($SecurityGroup -match "securitygroup-\d+")) { $SecurityGroupId = $securityGroup - $_SecurityGroup = Get-NsxSecurityGroup -objectId $SecurityGroupId -connection $connection + $_SecurityGroup = Get-NsxSecurityGroup -objectId $SecurityGroupId -Connection $connection } else { throw "Invalid SecurityGroup specified. Specify a PowerNSX SecurityGroup object or a valid securitygroup objectid." @@ -23667,7 +23824,7 @@ function Add-NsxSecurityGroupMember { elseif ( ($_Member -is [string]) -and ($_Member -match "^vm-\d+$|^resgroup-\d+$|^dvportgroup-\d+$|^directory_group-\d+$|^domain-c\d+$" )) { $MemberMoref = $_Member } - elseif ( ($_Member -is [string] ) -and ( [guid]::tryparse(($_Member -replace ".\d{3}$",""), [ref][guid]::Empty)) ) { + elseif ( ($_Member -is [string] ) -and ( [guid]::tryparse(($_Member -replace ".\d{3}$", ""), [ref][guid]::Empty)) ) { $MemberMoref = $_Member } elseif (( $_Member -is [string]) -and ( $NsxMemberTypes -contains ($_Member -replace "-\d+$") ) ) { @@ -23676,7 +23833,7 @@ function Add-NsxSecurityGroupMember { elseif ( $_Member -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($_Member.parent | get-view).config.instanceuuid + $vmUuid = ($_Member.parent | Get-View).config.instanceuuid $MemberMoref = "$vmUuid.$($_Member.id.substring($_Member.id.length-3))" } @@ -23707,9 +23864,9 @@ function Add-NsxSecurityGroupMember { } $URI = "/api/2.0/services/securitygroup/bulk/$($SecurityGroupId)" - Write-Progress -activity "Updating membership of Security Group $SecurityGroupId" - $null = invoke-nsxwebrequest -method "put" -uri $URI -connection $connection -body $_SecurityGroup.OuterXml - write-progress -activity "Updating membership of Security Group $SecurityGroupId" -completed + Write-Progress -Activity "Updating membership of Security Group $SecurityGroupId" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -connection $connection -body $_SecurityGroup.OuterXml + Write-Progress -Activity "Updating membership of Security Group $SecurityGroupId" -Completed } #Get-NsxSecurityGroup -objectId $SecurityGroup.objectId -connection $connection } @@ -23739,24 +23896,24 @@ function Remove-NsxSecurityGroupMember { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [object]$SecurityGroup, - [Parameter (Mandatory=$False)] - [switch]$FailIfAbsent=$true, - [Parameter (Mandatory=$False)] - #The specified exclude members are to be removed from the security group - [switch]$MemberIsExcluded=$false, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateSecurityGroupMember $_ })] - [object[]]$Member, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [object]$SecurityGroup, + [Parameter (Mandatory = $False)] + [switch]$FailIfAbsent = $true, + [Parameter (Mandatory = $False)] + #The specified exclude members are to be removed from the security group + [switch]$MemberIsExcluded = $false, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateSecurityGroupMember $_ })] + [object[]]$Member, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -23764,7 +23921,7 @@ function Remove-NsxSecurityGroupMember { #Populate the global membertype cache if not already done #Using the API rather than hardcoding incase this changes with versions of NSX - if ( -not (test-path Variable:\NsxMemberTypes) ) { + if ( -not (Test-Path Variable:\NsxMemberTypes) ) { $script:NsxMemberTypes = Get-NsxSecurityGroupMemberTypes } } @@ -23778,7 +23935,7 @@ function Remove-NsxSecurityGroupMember { } elseif ( ($securityGroup -is [string]) -and ($SecurityGroup -match "securitygroup-\d+")) { $SecurityGroupId = $securityGroup - $_SecurityGroup = Get-NsxSecurityGroup -objectId $SecurityGroupId -connection $connection + $_SecurityGroup = Get-NsxSecurityGroup -objectId $SecurityGroupId -Connection $connection } else { throw "Invalid SecurityGroup specified. Specify a PowerNSX SecurityGroup object or a valid securitygroup objectid." @@ -23794,7 +23951,7 @@ function Remove-NsxSecurityGroupMember { $MemberMoref = $_Member } - elseif ( ($_Member -is [string] ) -and ( [guid]::tryparse(($_Member -replace ".\d{3}$",""), [ref][guid]::Empty)) ) { + elseif ( ($_Member -is [string] ) -and ( [guid]::tryparse(($_Member -replace ".\d{3}$", ""), [ref][guid]::Empty)) ) { $MemberMoref = $_Member } elseif (( $_Member -is [string]) -and ( $NsxMemberTypes -contains ($_Member -replace "-\d+$") ) ) { @@ -23803,7 +23960,7 @@ function Remove-NsxSecurityGroupMember { elseif ( $_Member -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($_Member.parent | get-view).config.instanceuuid + $vmUuid = ($_Member.parent | Get-View).config.instanceuuid $MemberMoref = "$vmUuid.$($_Member.id.substring($_Member.id.length-3))" } @@ -23825,7 +23982,7 @@ function Remove-NsxSecurityGroupMember { if ( $FailIfAbsent) { #To support the prior functionality of failIfAbsent, we have to check ourselves... if ( $null -eq $existingMember ) { - throw "Member $(if ($_Member | Get-Member -memberType Properties -name Name) {$_member.name}) ($MemberMoref) is not a member of the specified SecurityGroup." + throw "Member $(if ($_Member | Get-Member -MemberType Properties -Name Name) {$_member.name}) ($MemberMoref) is not a member of the specified SecurityGroup." } } @@ -23841,9 +23998,9 @@ function Remove-NsxSecurityGroupMember { # member/excludeMember object via the xPath query if ($modified) { $URI = "/api/2.0/services/securitygroup/bulk/$($SecurityGroupId)" - Write-Progress -activity "Updating membership of Security Group $SecurityGroupId" - $null = invoke-nsxwebrequest -method "put" -uri $URI -connection $connection -body $_SecurityGroup.OuterXml - write-progress -activity "Updating membership of Security Group $SecurityGroupId" -completed + Write-Progress -Activity "Updating membership of Security Group $SecurityGroupId" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -connection $connection -body $_SecurityGroup.OuterXml + Write-Progress -Activity "Updating membership of Security Group $SecurityGroupId" -Completed } } @@ -24043,25 +24200,25 @@ function New-NsxDynamicCriteriaSpec { #> - [CmdletBinding(DefaultParameterSetName="search")] + [CmdletBinding(DefaultParameterSetName = "search")] param ( - [Parameter(Mandatory=$true, ParameterSetName="search")] - # The attribute that is to be evaluated. The list of keys is described in the help description. - [ ValidateSet("VMName", "ComputerName", "OSName", "SecurityTag") ] - [String]$Key, - [Parameter(Mandatory=$true, ParameterSetName="search")] - # The condition used to evaluate the criteria value against the its key - [ ValidateSet("contains", "ends_with", "starts_with", "equals", "notequals", "regex") ] - [String]$Condition, - [Parameter(Mandatory=$true, ParameterSetName="search")] - # The value of the criteria to be evaluated. - [ ValidateNotNullOrEmpty() ] - [String]$Value, - [Parameter(Mandatory=$true, ParameterSetName="entity")] - # The Entity to be matched. This can be a Valie PowerNSX such as logical switch or PowerCLI object such as VM. - [ ValidateNotNullOrEmpty() ] - [object]$Entity + [Parameter(Mandatory = $true, ParameterSetName = "search")] + # The attribute that is to be evaluated. The list of keys is described in the help description. + [ ValidateSet("VMName", "ComputerName", "OSName", "SecurityTag") ] + [String]$Key, + [Parameter(Mandatory = $true, ParameterSetName = "search")] + # The condition used to evaluate the criteria value against the its key + [ ValidateSet("contains", "ends_with", "starts_with", "equals", "notequals", "regex") ] + [String]$Condition, + [Parameter(Mandatory = $true, ParameterSetName = "search")] + # The value of the criteria to be evaluated. + [ ValidateNotNullOrEmpty() ] + [String]$Value, + [Parameter(Mandatory = $true, ParameterSetName = "entity")] + # The Entity to be matched. This can be a Valie PowerNSX such as logical switch or PowerCLI object such as VM. + [ ValidateNotNullOrEmpty() ] + [object]$Entity ) begin { @@ -24071,7 +24228,7 @@ function New-NsxDynamicCriteriaSpec { #Populate the global membertype cache if not already done #Using the API rather than hardcoding incase this changes with versions of NSX - if ( -not (test-path Variable:\NsxMemberTypes) ) { + if ( -not (Test-Path Variable:\NsxMemberTypes) ) { $script:NsxMemberTypes = Get-NsxSecurityGroupMemberTypes } @@ -24089,7 +24246,7 @@ function New-NsxDynamicCriteriaSpec { [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlDynamicCriteria = $XMLDoc.CreateElement("dynamicCriteria") - $xmlDoc.appendChild($xmlDynamicCriteria) | out-null + $xmlDoc.appendChild($xmlDynamicCriteria) | Out-Null if ($PSCmdlet.ParameterSetName -eq "entity") { @@ -24101,7 +24258,7 @@ function New-NsxDynamicCriteriaSpec { $EntityObjectId = $entity } # Match NIC identifier specified by user (eg UUID.000) - elseif ( ($entity -is [string] ) -and ( [guid]::tryparse(($entity -replace ".\d{3}$",""), [ref][guid]::Empty)) ) { + elseif ( ($entity -is [string] ) -and ( [guid]::tryparse(($entity -replace ".\d{3}$", ""), [ref][guid]::Empty)) ) { $EntityObjectId = $entity } elseif (( $entity -is [string]) -and ( $NsxMemberTypes -contains ($entity -replace "-\d+$") ) ) { @@ -24110,7 +24267,7 @@ function New-NsxDynamicCriteriaSpec { elseif ( $entity -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($entity.parent | get-view).config.instanceuuid + $vmUuid = ($entity.parent | Get-View).config.instanceuuid $EntityObjectId = "$vmUuid.$($entity.id.substring($entity.id.length-3))" } elseif (( $entity -is [VMware.VimAutomation.ViCore.Interop.V1.VIObjectInterop]) -and ( $NsxMemberTypes -contains $entity.ExtensionData.MoRef.Type)) { @@ -24132,7 +24289,7 @@ function New-NsxDynamicCriteriaSpec { $xmlDynamicCriteria } - end{} + end {} } function Add-NsxDynamicMemberSet { @@ -24206,30 +24363,30 @@ function Add-NsxDynamicMemberSet { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1) ] - # SecurityGroup whose membership is to be modified. - [ValidateNotNullOrEmpty()] - [object]$SecurityGroup, - [Parameter (Mandatory=$false) ] - # Dynamic Criteria Set operator BETWEEN sets. In the UI, this is the AND/OR drop down displayed between member sets. - # This value is ignored if the set being added is the first set being added to the Dynamic Member Definition of a Security Group - [ValidateSet("OR", "AND")] - [String]$SetOperator, - [Parameter (Mandatory=$true) ] - # Dynamic Criteria operator for criteria WITHIN the set being added. In the UI, this is the Match: ANY/ALL drop down displayed at the top of each Dynamic Member Set. - [ValidateSet("ANY", "ALL")] - [String]$CriteriaOperator, - [Parameter (Mandatory=$true) ] - # Dynamic criteria spec/s as generated by New-NsxDynamicCriteriaSpec - [ValidateScript( { ValidateDynamicCriteriaSpec $_ })] - [System.Xml.XmlElement[]]$DynamicCriteriaSpec, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1) ] + # SecurityGroup whose membership is to be modified. + [ValidateNotNullOrEmpty()] + [object]$SecurityGroup, + [Parameter (Mandatory = $false) ] + # Dynamic Criteria Set operator BETWEEN sets. In the UI, this is the AND/OR drop down displayed between member sets. + # This value is ignored if the set being added is the first set being added to the Dynamic Member Definition of a Security Group + [ValidateSet("OR", "AND")] + [String]$SetOperator, + [Parameter (Mandatory = $true) ] + # Dynamic Criteria operator for criteria WITHIN the set being added. In the UI, this is the Match: ANY/ALL drop down displayed at the top of each Dynamic Member Set. + [ValidateSet("ANY", "ALL")] + [String]$CriteriaOperator, + [Parameter (Mandatory = $true) ] + # Dynamic criteria spec/s as generated by New-NsxDynamicCriteriaSpec + [ValidateScript( { ValidateDynamicCriteriaSpec $_ })] + [System.Xml.XmlElement[]]$DynamicCriteriaSpec, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -24244,7 +24401,7 @@ function Add-NsxDynamicMemberSet { } elseif ( ($securityGroup -is [string]) -and ($SecurityGroup -match "securitygroup-\d+")) { $SecurityGroupId = $securityGroup - $_SecurityGroup = Get-NsxSecurityGroup -objectId $SecurityGroupId -connection $connection + $_SecurityGroup = Get-NsxSecurityGroup -objectId $SecurityGroupId -Connection $connection } else { throw "Invalid SecurityGroup specified. Specify a PowerNSX SecurityGroup object or a valid securitygroup objectid." @@ -24253,14 +24410,14 @@ function Add-NsxDynamicMemberSet { # First we need to verify if the Security Group object passed in via the # pipeline already has the dynamicMemberDefinition element created. If # not, then create the required XML structure - $dynamicMemberDefinitionElement = Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SecurityGroup -Query 'child::dynamicMemberDefinition' + $dynamicMemberDefinitionElement = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SecurityGroup -query 'child::dynamicMemberDefinition' if ( -not $dynamicMemberDefinitionElement ) { Add-XmlElement -xmlRoot $_SecurityGroup -xmlElementName "dynamicMemberDefinition" - $dynamicMemberDefinitionElement = Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_SecurityGroup -Query 'child::dynamicMemberDefinition' + $dynamicMemberDefinitionElement = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_SecurityGroup -query 'child::dynamicMemberDefinition' #Default the set operator for the first criteria set in a dynamic membership defintion to be 'OR' as the UI does. if ( $PSBoundParameters.ContainsKey("SetOperator")) { - write-warning "A Set Operator is not defined for the first dynamic membership set defined on a security group. The Set Operator value has been ignored." + Write-Warning "A Set Operator is not defined for the first dynamic membership set defined on a security group. The Set Operator value has been ignored." } $SetOperator = "OR" } @@ -24286,18 +24443,18 @@ function Add-NsxDynamicMemberSet { #Add the criteria operator to the spec elem Add-XmlElement -xmlRoot $specImport -xmlElementName "operator" -xmlElementText $_CriteriaOperator - $xmlRoot.appendChild($specImport) | out-null + $xmlRoot.appendChild($specImport) | Out-Null } - $xmlDynamicMemberDefinition.appendChild($xmlRoot) | out-null + $xmlDynamicMemberDefinition.appendChild($xmlRoot) | Out-Null #Do the post $body = $_SecurityGroup.OuterXml $URI = "/api/2.0/services/securitygroup/bulk/$($SecurityGroupId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection } - end{} + end {} } function Get-NsxDynamicMemberSet { @@ -24360,27 +24517,27 @@ function Get-NsxDynamicMemberSet { param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1) ] - # SecurityGroup to retrieve Dynamic Sets from. - [ValidateNotNullOrEmpty()] - [object]$SecurityGroup, - [Parameter (Mandatory=$false)] - #Get Member Set by index - [ValidateNotNullOrEmpty()] - [string]$Index, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1) ] + # SecurityGroup to retrieve Dynamic Sets from. + [ValidateNotNullOrEmpty()] + [object]$SecurityGroup, + [Parameter (Mandatory = $false)] + #Get Member Set by index + [ValidateNotNullOrEmpty()] + [string]$Index, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) process { - if (invoke-xpathquery -Node $SecurityGroup -querymethod SelectSingleNode -query "child::dynamicMemberDefinition/dynamicSet") { + if (Invoke-XpathQuery -Node $SecurityGroup -QueryMethod SelectSingleNode -query "child::dynamicMemberDefinition/dynamicSet") { $SetCount = 0 - foreach ( $CriteriaSet in $SecurityGroup.dynamicMemberDefinition.dynamicSet) { + foreach ( $CriteriaSet in $SecurityGroup.dynamicMemberDefinition.dynamicSet) { $ResultObj = @{} $SetCount++ #Use the first element in the set to determine the criteria operator @@ -24389,7 +24546,7 @@ function Get-NsxDynamicMemberSet { #Obfustcating it here to a per dynamic criteria set setting aligns #with how the UI operates. - $CriteriaOperator = ConvertFrom-NsxApiCriteriaOperator (invoke-xpathquery -Node $CriteriaSet -querymethod SelectSingleNode -query "child::dynamicCriteria").Operator + $CriteriaOperator = ConvertFrom-NsxApiCriteriaOperator (Invoke-XpathQuery -Node $CriteriaSet -QueryMethod SelectSingleNode -query "child::dynamicCriteria").Operator #Bash together an output string that reflects what the user would see in the UI... $CriteriaString = "Match: $CriteriaOperator" @@ -24397,11 +24554,11 @@ function Get-NsxDynamicMemberSet { foreach ( $Criteria in $CriteriaSet.dynamicCriteria ) { $CriteriaString += ", $(ConvertFrom-NsxApiCriteriaKey $Criteria.Key) $(ConvertFrom-NsxApiCriteriaCondition $Criteria.Criteria) $($Criteria.value)" $CriteriaObj = [pscustomobject]@{ - "Index" = $CriteriaCollection.Length + 1 - "Match" = $CriteriaOperator - "Key" = ConvertFrom-NsxApiCriteriaKey $Criteria.Key + "Index" = $CriteriaCollection.Length + 1 + "Match" = $CriteriaOperator + "Key" = ConvertFrom-NsxApiCriteriaKey $Criteria.Key "Condition" = ConvertFrom-NsxApiCriteriaCondition $Criteria.Criteria - "Value" = $Criteria.value + "Value" = $Criteria.value } $CriteriaCollection += $CriteriaObj } @@ -24438,14 +24595,14 @@ function Get-NsxDynamicMemberSet { [string[]]$DefaultProperties = 'Index', 'SecurityGroupName', 'SetOperator', 'CriteriaString' # Add the PSStandardMembers.DefaultDisplayPropertySet member - $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet,$DefaultProperties + $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet, $DefaultProperties $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]$ddps # Attach default display property set and output $output | Add-Member -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers if ( $PSBoundParameters.ContainsKey("Index") ) { - $output | Where-object { $_.index -eq $Index } + $output | Where-Object { $_.index -eq $Index } } else { $output @@ -24512,24 +24669,24 @@ function Remove-NsxDynamicMemberSet { Removes the first dynamic member set from the dynamic member definition of the security group Prod-WindowsServer #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - [CmdletBinding(DefaultParameterSetName="Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1) ] - # Dynamic member set to remove. - [ValidateScript({ ValidateDynamicMemberSet $_ })] - [object]$DynamicMemberSet, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1) ] + # Dynamic member set to remove. + [ValidateScript( { ValidateDynamicMemberSet $_ })] + [object]$DynamicMemberSet, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -24546,7 +24703,7 @@ function Remove-NsxDynamicMemberSet { Begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } @@ -24561,12 +24718,12 @@ function Remove-NsxDynamicMemberSet { if ( -not ($SgsToModify.ContainsKey($DynamicMemberSet.SecurityGroup.objectId))) { #We havent seen this SG before, add it to our tracking hashtable. We have to clone the node to avoid modifying the input object compoenent that is XML. - $SGsToModify.Add($DynamicMemberSet.SecurityGroup.objectId, [pscustomobject]@{"SecurityGroup"=$DynamicMemberSet.SecurityGroup.CloneNode($True); "NodesToRemove"=@()}) + $SGsToModify.Add($DynamicMemberSet.SecurityGroup.objectId, [pscustomobject]@{"SecurityGroup" = $DynamicMemberSet.SecurityGroup.CloneNode($True); "NodesToRemove" = @() }) } #Get the SG XML from our tracking hashtable to search on. $SecurityGroup = $SGsToModify[$DynamicMemberSet.SecurityGroup.objectId].SecurityGroup - $NodeToRemove = invoke-xpathquery -node $SecurityGroup.dynamicMemberDefinition -QueryMethod SelectSingleNode "child::dynamicSet[$($DynamicMemberSet.Index)]" + $NodeToRemove = Invoke-XpathQuery -Node $SecurityGroup.dynamicMemberDefinition -QueryMethod SelectSingleNode "child::dynamicSet[$($DynamicMemberSet.Index)]" if ( -not $NodeToRemove ) { throw "The Dynamic Member Set index $($DynamicMemberSet.Index) does not exist in the security group $($SecurityGroup.Name) ($($SecurityGroup.objectId)). This should not occur and indicates a fault in PowerNSX. Please report this bug at github.com/vmware/PowerNSX" } @@ -24588,7 +24745,7 @@ function Remove-NsxDynamicMemberSet { $uri = "/api/2.0/services/securitygroup/bulk/$($SgToModify.SecurityGroup.objectId)" $body = $SgToModify.SecurityGroup.outerXml if ( -not ( $Noconfirm )) { - $message = "Removal of dynamic member sets from Security Group $($SGToModify.SecurityGroup.Name) will result in a change in security posture." + $message = "Removal of dynamic member sets from Security Group $($SGToModify.SecurityGroup.Name) will result in a change in security posture." $question = "Are you sure you want to proceed with the update of Security Group $($SGToModify.SecurityGroup.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -24598,9 +24755,9 @@ function Remove-NsxDynamicMemberSet { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Security Group $($SGToModify.SecurityGroup.Name)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Security Group $($SGToModify.SecurityGroup.Name)" -completed + Write-Progress -Activity "Update Security Group $($SGToModify.SecurityGroup.Name)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Security Group $($SGToModify.SecurityGroup.Name)" -Completed } } @@ -24682,34 +24839,34 @@ function Add-NsxDynamicCriteria { param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1) ] - # SecurityGroup to retrieve Dynamic Sets from. - [ValidateScript({ ValidateDynamicMemberSet $_ })] - [object]$DynamicMemberSet, - [Parameter (Mandatory=$true, ParameterSetName="spec") ] - # Dynamic criteria spec/s as generated by New-NsxDynamicCriteriaSpec - [ValidateScript( { ValidateDynamicCriteriaSpec $_ })] - [System.Xml.XmlElement]$DynamicCriteriaSpec, - [Parameter (Mandatory=$true, ParameterSetName="search")] - # Dynamic Criteria Key - [ ValidateSet("VMName", "ComputerName", "OSName", "SecurityTag") ] - [String]$Key, - [Parameter (Mandatory=$true, ParameterSetName="search")] - # Dynamic Criteria Condition - [ ValidateSet("contains", "ends_with", "starts_with", "equals", "notequals", "regex") ] - [String]$Condition, - [Parameter (Mandatory=$true, ParameterSetName="search")] - # Dynamic Criteria Value to be matched against the key using the condition. - [ ValidateNotNullOrEmpty() ] - [String]$Value, - [Parameter (Mandatory=$true, ParameterSetName="entity")] - # A specific entity to match against. - [ ValidateNotNullOrEmpty() ] - [object]$Entity, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1) ] + # SecurityGroup to retrieve Dynamic Sets from. + [ValidateScript( { ValidateDynamicMemberSet $_ })] + [object]$DynamicMemberSet, + [Parameter (Mandatory = $true, ParameterSetName = "spec") ] + # Dynamic criteria spec/s as generated by New-NsxDynamicCriteriaSpec + [ValidateScript( { ValidateDynamicCriteriaSpec $_ })] + [System.Xml.XmlElement]$DynamicCriteriaSpec, + [Parameter (Mandatory = $true, ParameterSetName = "search")] + # Dynamic Criteria Key + [ ValidateSet("VMName", "ComputerName", "OSName", "SecurityTag") ] + [String]$Key, + [Parameter (Mandatory = $true, ParameterSetName = "search")] + # Dynamic Criteria Condition + [ ValidateSet("contains", "ends_with", "starts_with", "equals", "notequals", "regex") ] + [String]$Condition, + [Parameter (Mandatory = $true, ParameterSetName = "search")] + # Dynamic Criteria Value to be matched against the key using the condition. + [ ValidateNotNullOrEmpty() ] + [String]$Value, + [Parameter (Mandatory = $true, ParameterSetName = "entity")] + # A specific entity to match against. + [ ValidateNotNullOrEmpty() ] + [object]$Entity, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -24721,7 +24878,7 @@ function Add-NsxDynamicCriteria { $spec = New-NsxDynamicCriteriaSpec -Key $Key -Condition $Condition -Value $Value } "entity" { - $spec = New-NsxDynamicCriteriaSpec -entity $entity + $spec = New-NsxDynamicCriteriaSpec -Entity $entity } "spec" { $spec = $DynamicCriteriaSpec @@ -24732,7 +24889,7 @@ function Add-NsxDynamicCriteria { $SecurityGroupXML = $DynamicMemberSet.SecurityGroup.CloneNode($true) #Now get the specific set elem user has passed from the contained SG XML elem... - $dynamicMemberSetElement = Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $SecurityGroupXML -Query "child::dynamicMemberDefinition/dynamicSet[$($DynamicMemberSet.Index)]" + $dynamicMemberSetElement = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $SecurityGroupXML -query "child::dynamicMemberDefinition/dynamicSet[$($DynamicMemberSet.Index)]" if ( -not $dynamicMemberSetElement ) { #this shouldnt happen if we get a valid Dynamic Member Set throw "The specified Dynamic Member Set is not valid. This is not expected, please report this issue on the PowerNSX Github issues page - github.com/vmware/powernsx/issues" @@ -24742,12 +24899,12 @@ function Add-NsxDynamicCriteria { #Add the criteria operator to the spec elem. All Criteria must share the same operator, so we just grab the first one and copy it. Add-XmlElement -xmlRoot $specImport -xmlElementName "operator" -xmlElementText (ConvertTo-NsxApiCriteriaOperator $DynamicMemberSet.Criteria[0].Match).ToUpper() - $dynamicMemberSetElement.appendChild($specImport) | out-null + $dynamicMemberSetElement.appendChild($specImport) | Out-Null #Do the post $body = $SecurityGroupXML.OuterXml $URI = "/api/2.0/services/securitygroup/bulk/$($SecurityGroupXML.objectId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection Get-NsxSecurityGroup -objectId $SecurityGroupXML.objectId -Connection $Connection | Get-NsxDynamicMemberSet -Index $DynamicMemberSet.Index -Connection $Connection } @@ -24831,18 +24988,18 @@ function Get-NsxDynamicCriteria { param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1) ] - # Dynamic Member Set to retrieve Dynamic Criteria from. - [ValidateScript({ ValidateDynamicMemberSet $_ })] - [object]$DynamicMemberSet, - [Parameter (Mandatory=$false)] - #Get Criteria Member by index - [ValidateNotNullOrEmpty()] - [string]$Index, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1) ] + # Dynamic Member Set to retrieve Dynamic Criteria from. + [ValidateScript( { ValidateDynamicMemberSet $_ })] + [object]$DynamicMemberSet, + [Parameter (Mandatory = $false)] + #Get Criteria Member by index + [ValidateNotNullOrEmpty()] + [string]$Index, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -24852,27 +25009,27 @@ function Get-NsxDynamicCriteria { $output = [pscustomobject]@{ - "Index" = $Criteria.Index - "MemberSetIndex" = $DynamicMemberSet.Index + "Index" = $Criteria.Index + "MemberSetIndex" = $DynamicMemberSet.Index "SecurityGroupName" = $DynamicMemberSet."SecurityGroupName" - "Key" = $Criteria.Key - "Condition" = $Criteria.Condition - "Value" = $Criteria.Value - "SecurityGroup" = $DynamicMemberSet.SecurityGroup + "Key" = $Criteria.Key + "Condition" = $Criteria.Condition + "Value" = $Criteria.Value + "SecurityGroup" = $DynamicMemberSet.SecurityGroup } #Manipulating which output properties are displayed to supress SecurityGroup [string[]]$DefaultProperties = "Index", "MemberSetIndex", "SecurityGroupName", "Key", "Condition", "Value" # Add the PSStandardMembers.DefaultDisplayPropertySet member - $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet,$DefaultProperties + $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet, $DefaultProperties $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]$ddps # Attach default display property set and output $output | Add-Member -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers if ( $PSBoundParameters.ContainsKey("Index") ) { - $output | Where-object { $_.index -eq $Index } + $output | Where-Object { $_.index -eq $Index } } else { $output @@ -24951,24 +25108,24 @@ function Remove-NsxDynamicCriteria { Removes the first Dynamic Criteria from the first Dynamic Member Set of the security group webapp. This probably IS what you want to do! :) #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - [CmdletBinding(DefaultParameterSetName="Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1) ] - # SecurityGroup to retrieve Dynamic Sets from. - [ValidateScript({ ValidateDynamicCriteria $_ })] - [object]$DynamicCriteria, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1) ] + # SecurityGroup to retrieve Dynamic Sets from. + [ValidateScript( { ValidateDynamicCriteria $_ })] + [object]$DynamicCriteria, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -24985,7 +25142,7 @@ function Remove-NsxDynamicCriteria { Begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } @@ -25000,12 +25157,12 @@ function Remove-NsxDynamicCriteria { if ( -not ($SgsToModify.ContainsKey($DynamicCriteria.SecurityGroup.objectId))) { #We havent seen this SG before, add it to our tracking hashtable. We have to clone the node to avoid modifying the input object compoenent that is XML. - $SGsToModify.Add($DynamicCriteria.SecurityGroup.objectId, [pscustomobject]@{"SecurityGroup"=$DynamicCriteria.SecurityGroup.CloneNode($True); "NodesToRemove"=@()}) + $SGsToModify.Add($DynamicCriteria.SecurityGroup.objectId, [pscustomobject]@{"SecurityGroup" = $DynamicCriteria.SecurityGroup.CloneNode($True); "NodesToRemove" = @() }) } #Get the SG XML from our tracking hashtable to search on. $SecurityGroup = $SGsToModify[$DynamicCriteria.SecurityGroup.objectId].SecurityGroup - $NodeToRemove = invoke-xpathquery -Node $SecurityGroup.dynamicMemberDefinition -querymethod SelectSingleNode -query "child::dynamicSet[$($DynamicCriteria.MemberSetIndex)]/dynamicCriteria[$($DynamicCriteria.Index)]" + $NodeToRemove = Invoke-XpathQuery -Node $SecurityGroup.dynamicMemberDefinition -QueryMethod SelectSingleNode -query "child::dynamicSet[$($DynamicCriteria.MemberSetIndex)]/dynamicCriteria[$($DynamicCriteria.Index)]" if ( -not $NodeToRemove ) { throw "The Dynamic Criteria index $($DynamicCriteria.Index) within the Dynamic Member set index $($DynamicCriteria.MemberSetIndex) does not exist in the security group $($SecurityGroup.Name) ($($SecurityGroup.objectId)). This should not occur and indicates a fault in PowerNSX. Please report this bug at github.com/vmware/PowerNSX" } @@ -25013,7 +25170,7 @@ function Remove-NsxDynamicCriteria { #Add the node to remove to the tracking collection for this SG. We need to store the memberset index too so we can select it laster during the removal. $SGsToModify[$DynamicCriteria.SecurityGroup.objectId].NodesToRemove += [pscustomobject]@{ "MemberSetIndex" = $DynamicCriteria.MemberSetIndex - "NodeToRemove" = $NodeToRemove + "NodeToRemove" = $NodeToRemove } } @@ -25022,14 +25179,14 @@ function Remove-NsxDynamicCriteria { #Now we do the actual modification work. foreach ( $SGToModify in $SGsToModify.Values) { foreach ( $Node in $SgToModify.NodesToRemove ) { - $null = (invoke-xpathquery -Node $SecurityGroup.dynamicMemberDefinition -querymethod SelectSingleNode -query "child::dynamicSet[$($Node.MemberSetIndex)]").RemoveChild($Node.NodeToRemove) + $null = (Invoke-XpathQuery -Node $SecurityGroup.dynamicMemberDefinition -QueryMethod SelectSingleNode -query "child::dynamicSet[$($Node.MemberSetIndex)]").RemoveChild($Node.NodeToRemove) } #Post the updated SG XML. $uri = "/api/2.0/services/securitygroup/bulk/$($SgToModify.SecurityGroup.objectId)" $body = $SgToModify.SecurityGroup.outerXml if ( -not ( $Noconfirm )) { - $message = "Removal of dynamic criteria from the Dynamic Member set of a Security Group $($SGToModify.SecurityGroup.Name) will result in a change in security posture." + $message = "Removal of dynamic criteria from the Dynamic Member set of a Security Group $($SGToModify.SecurityGroup.Name) will result in a change in security posture." $question = "Are you sure you want to proceed with the update of Security Group $($SGToModify.SecurityGroup.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -25039,9 +25196,9 @@ function Remove-NsxDynamicCriteria { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Security Group $($SGToModify.SecurityGroup.Name)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Security Group $($SGToModify.SecurityGroup.Name)" -completed + Write-Progress -Activity "Update Security Group $($SGToModify.SecurityGroup.Name)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Security Group $($SGToModify.SecurityGroup.Name)" -Completed } } @@ -25071,25 +25228,25 @@ function New-NsxSecurityTag { #> param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [string]$Description, - [Parameter (Mandatory=$false)] - #This marks the tag as a universal object within the constructs of NSX - [switch]$Universal, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [string]$Description, + [Parameter (Mandatory = $false)] + #This marks the tag as a universal object within the constructs of NSX + [switch]$Universal, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { if ( $universal ) { if ( -not $connection.version ) { - write-warning "Universal security tags are not supported on NSX versions less than 6.3.0 and current NSX version could not be determined." + Write-Warning "Universal security tags are not supported on NSX versions less than 6.3.0 and current NSX version could not be determined." } elseif ( [version]$connection.version -lt [version]"6.3.0") { throw "Universal security tags are not supported on NSX versions less than 6.3.0" @@ -25102,8 +25259,8 @@ function New-NsxSecurityTag { [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("securityTag") [System.XML.XMLElement]$XmlNodes = $Xmldoc.CreateElement("type") - $xmlDoc.appendChild($xmlRoot) | out-null - $xmlRoot.appendChild($xmlnodes) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null + $xmlRoot.appendChild($xmlnodes) | Out-Null #Mandatory fields Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "objectTypeName" -xmlElementText "SecurityTag" @@ -25122,10 +25279,10 @@ function New-NsxSecurityTag { #Do the post $body = $xmlroot.OuterXml $URI = "/api/2.0/services/securitytags/tag" - $null = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $null = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection #Return our shiny new tag... - Get-NsxSecurityTag -name $Name -connection $connection + Get-NsxSecurityTag -Name $Name -Connection $connection } end {} @@ -25155,22 +25312,22 @@ function Get-NsxSecurityTag { Gets a specific Security Tag by name #> - param ( + param ( - [Parameter (Mandatory=$false, Position=1)] - #Get Security Tag by name - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - #Get security tag by objectId - [string]$objectId, - [Parameter (Mandatory=$false)] - #Include system security tags - [switch]$IncludeSystem=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, Position = 1)] + #Get Security Tag by name + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + #Get security tag by objectId + [string]$objectId, + [Parameter (Mandatory = $false)] + #Include system security tags + [switch]$IncludeSystem = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -25179,13 +25336,13 @@ function Get-NsxSecurityTag { if ( -not $PsBoundParameters.ContainsKey('objectId')) { #either all or by name $URI = "/api/2.0/services/securitytags/tag" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $securityTags = @() - if ($response.securityTags | Get-Member -memberType Properties -Name pagingInfo) { + if ($response.securityTags | Get-Member -MemberType Properties -Name pagingInfo) { $defaultPageSize = 1024 - $itemIndex = 0 + $itemIndex = 0 $startingIndex = 0 $pagingInfo = $response.securityTags.pagingInfo if ( [int]$paginginfo.totalCount -ne 0 ) { @@ -25206,7 +25363,7 @@ function Get-NsxSecurityTag { $startingIndex += $defaultPageSize $URI = "/api/2.0/services/securitytags/tag?pageSize=$defaultPageSize&startIndex=$startingIndex" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $pagingInfo = $response.securityTags.pagingInfo } @@ -25219,15 +25376,16 @@ function Get-NsxSecurityTag { $securityTags = $response.securityTags.securityTag } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::securityTags/securityTag')) { - if ( $PsBoundParameters.ContainsKey('Name')) { - $tags = $securityTags | where-object { $_.name -eq $name } - } else { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::securityTags/securityTag')) { + if ( $PsBoundParameters.ContainsKey('Name')) { + $tags = $securityTags | Where-Object { $_.name -eq $name } + } + else { $tags = $securityTags } if ( -not $IncludeSystem ) { - $tags | where-object { ( $_.systemResource -ne 'true') } + $tags | Where-Object { ( $_.systemResource -ne 'true') } } else { $tags @@ -25238,13 +25396,13 @@ function Get-NsxSecurityTag { #Just getting a single Security group by object id $URI = "/api/2.0/services/securitytags/tag/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::securityTag')) { + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::securityTag')) { $tags = $response.securitytag } if ( -not $IncludeSystem ) { - $tags | where-object { ( $_.systemResource -ne 'true') } + $tags | Where-Object { ( $_.systemResource -ne 'true') } } else { $tags @@ -25277,21 +25435,21 @@ function Remove-NsxSecurityTag { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript( { ValidateSecurityTag $_ })] - [System.Xml.XmlElement]$SecurityTag, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateSecurityTag $_ })] + [System.Xml.XmlElement]$SecurityTag, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -25302,11 +25460,11 @@ function Remove-NsxSecurityTag { process { if (($SecurityTag.systemResource -eq 'true') -and ( -not $force)) { - write-warning "Not removing $($SecurityTag.Name) as it is a default SecurityTag. Use -Force to force deletion." + Write-Warning "Not removing $($SecurityTag.Name) as it is a default SecurityTag. Use -Force to force deletion." } else { if ( $confirm ) { - $message = "Removal of Security Tags may impact desired Security Posture and expose your infrastructure. Please understand the impact of this change" + $message = "Removal of Security Tags may impact desired Security Posture and expose your infrastructure. Please understand the impact of this change" $question = "Proceed with removal of Security Tag $($SecurityTag.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -25319,9 +25477,9 @@ function Remove-NsxSecurityTag { if ($decision -eq 0) { $URI = "/api/2.0/services/securitytags/tag/$($SecurityTag.objectId)?force=$($Force.ToString().ToLower())" - Write-Progress -activity "Remove Security Tag $($SecurityTag.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Security Tag $($SecurityTag.Name)" -completed + Write-Progress -Activity "Remove Security Tag $($SecurityTag.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Security Tag $($SecurityTag.Name)" -Completed } } @@ -25362,20 +25520,20 @@ function Get-NsxSecurityTagAssignment { #> - [CmdLetBinding(DefaultParameterSetName="Tag")] + [CmdLetBinding(DefaultParameterSetName = "Tag")] param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "Tag")] - [ValidateScript( { ValidateSecurityTag $_ })] - [System.Xml.XmlElement]$SecurityTag, - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "VirtualMachine")] - [ValidateScript( { ValidateVirtualMachineOrTemplate $_ })] - [object[]]$VirtualMachine, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Tag")] + [ValidateScript( { ValidateSecurityTag $_ })] + [System.Xml.XmlElement]$SecurityTag, + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "VirtualMachine")] + [ValidateScript( { ValidateVirtualMachineOrTemplate $_ })] + [object[]]$VirtualMachine, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -25387,10 +25545,10 @@ function Get-NsxSecurityTagAssignment { 'Tag' { $URI = "/api/2.0/services/securitytags/tag/$($SecurityTag.objectId)/vm" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::basicinfolist/basicinfo') ) { - $nodes = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $response -Query 'descendant::basicinfolist/basicinfo') + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::basicinfolist/basicinfo') ) { + $nodes = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $response -query 'descendant::basicinfolist/basicinfo') foreach ($node in $nodes) { @@ -25402,18 +25560,18 @@ function Get-NsxSecurityTagAssignment { # buggered if I know where to look for it. Considering it exists somewhere # because its being returned as a valid object via the NSX API. try { - $vm = Get-Vm -Server $Connection.VIConnection -id "VirtualMachine-$($node.objectId)" -ErrorAction stop + $vm = Get-VM -Server $Connection.VIConnection -Id "VirtualMachine-$($node.objectId)" -ErrorAction stop } catch { try { - $vm = Get-Template -Server $Connection.VIConnection -id "VirtualMachine-$($node.objectId)" -ErrorAction stop + $vm = Get-Template -Server $Connection.VIConnection -Id "VirtualMachine-$($node.objectId)" -ErrorAction stop } catch { throw "Could not find object with MoRef $($node.objectId) using Get-VM or Get-Template." } } [pscustomobject]@{ - "SecurityTag" = $SecurityTag; + "SecurityTag" = $SecurityTag; "VirtualMachine" = $vm } } @@ -25423,17 +25581,17 @@ function Get-NsxSecurityTagAssignment { 'VirtualMachine' { ## for each VM object, get the NSX Security Tag(s) assigned to it, if any - $VirtualMachine | Foreach-Object { + $VirtualMachine | ForEach-Object { $oThisVM = $_ Write-Progress -Activity "Fetching Security Tags assigned to Virtual Machine '$oThisVM'" ## make the URI to use; leverage the value of the top-level property ".Id", for minor speed improvement over accessing .ExtensionData; this REST method was introduced in NSX v6.3.0 $URI = "/api/2.0/services/securitytags/vm/{0}" -f ($oThisVM.Id -replace "^VirtualMachine-", "") - [System.Xml.XmlDocument]$oRestResponse = Invoke-NsxRestMethod -Method "GET" -Uri $URI -Connection $connection + [System.Xml.XmlDocument]$oRestResponse = Invoke-NsxRestMethod -method "GET" -URI $URI -connection $connection ## for each SecurityTag object in .securityTags property of the response (if any), return a new object with SecurityTag and VirtualMachine properties (in the same way that the by-Tag parameterset behaves) if (-not [System.String]::IsNullOrEmpty($oRestResponse.securityTags)) { - $oRestResponse.securityTags.securityTag | Foreach-Object { + $oRestResponse.securityTags.securityTag | ForEach-Object { [pscustomobject]@{ - "SecurityTag" = $_ + "SecurityTag" = $_ "VirtualMachine" = $oThisVM } ## end new-object } ## end new-object @@ -25480,25 +25638,25 @@ function New-NsxSecurityTagAssignment { Assign all security tags containing "DMZ" in the name to multiple virtual machines #> - [CmdLetBinding(DefaultParameterSetName="VirtualMachine")] + [CmdLetBinding(DefaultParameterSetName = "VirtualMachine")] param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "VirtualMachine")] - [Parameter (Mandatory=$true, Position = 1, ParameterSetName = "SecurityTag")] - [ValidateNotNullorEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop[]]$VirtualMachine, - [Parameter (Mandatory=$true, Position = 1, ParameterSetName = "VirtualMachine")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName = "SecurityTag")] - [ValidateScript( { ValidateSecurityTag $_ })] - [System.Xml.XmlElement[]]$SecurityTag, - [Parameter (Mandatory=$true, ParameterSetName = "VirtualMachine")] - [switch]$ApplyTag, - [Parameter (Mandatory=$true, ParameterSetName = "SecurityTag")] - [switch]$ApplyToVm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "VirtualMachine")] + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "SecurityTag")] + [ValidateNotNullorEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop[]]$VirtualMachine, + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "VirtualMachine")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "SecurityTag")] + [ValidateScript( { ValidateSecurityTag $_ })] + [System.Xml.XmlElement[]]$SecurityTag, + [Parameter (Mandatory = $true, ParameterSetName = "VirtualMachine")] + [switch]$ApplyTag, + [Parameter (Mandatory = $true, ParameterSetName = "SecurityTag")] + [switch]$ApplyToVm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -25513,14 +25671,14 @@ function New-NsxSecurityTagAssignment { $vmMoid = $vm.ExtensionData.MoRef.Value $URI = "/api/2.0/services/securitytags/tag/$($TagIdentifierString)/vm/$($vmMoid)" - Write-Progress -activity "Adding Security Tag $($TagIdentifierString) to Virtual Machine $($vmMoid)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -connection $connection - Write-Progress -activity "Adding Security Tag $TagIdentifierString to Virtual Machine $($vmMoid)" -completed + Write-Progress -Activity "Adding Security Tag $($TagIdentifierString) to Virtual Machine $($vmMoid)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -connection $connection + Write-Progress -Activity "Adding Security Tag $TagIdentifierString to Virtual Machine $($vmMoid)" -Completed } } } - end{} + end {} } function Remove-NsxSecurityTagAssignment { @@ -25549,18 +25707,18 @@ function Remove-NsxSecurityTagAssignment { #> [CmdLetBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - [ValidateScript ({ ValidateTagAssignment $_ })] - [PSCustomObject]$TagAssignment, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript ( { ValidateTagAssignment $_ })] + [PSCustomObject]$TagAssignment, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -25568,7 +25726,7 @@ function Remove-NsxSecurityTagAssignment { process { if ( $confirm ) { - $message = "Removing Security Tag $($TagAssignment.SecurityTag.Name) from $($TagAssignment.VirtualMachine.name) may impact desired Security Posture and expose your infrastructure." + $message = "Removing Security Tag $($TagAssignment.SecurityTag.Name) from $($TagAssignment.VirtualMachine.name) may impact desired Security Posture and expose your infrastructure." $question = "Proceed with removal of Security Tag?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -25583,13 +25741,13 @@ function Remove-NsxSecurityTagAssignment { if ($decision -eq 0) { $URI = "/api/2.0/services/securitytags/tag/$($TagAssignment.SecurityTag.ObjectId)/vm/$($TagAssignment.VirtualMachine.ExtensionData.Moref.Value)" - Write-Progress -activity "Removing Security Tag $($TagAssignment.SecurityTag.ObjectId) to Virtual Machine $($TagAssignment.VirtualMachine.ExtensionData.Moref.Value)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Adding Security Tag $($TagAssignment.SecurityTag.ObjectId) to Virtual Machine $($TagAssignment.VirtualMachine.ExtensionData.Moref.Value)" -completed + Write-Progress -Activity "Removing Security Tag $($TagAssignment.SecurityTag.ObjectId) to Virtual Machine $($TagAssignment.VirtualMachine.ExtensionData.Moref.Value)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Adding Security Tag $($TagAssignment.SecurityTag.ObjectId) to Virtual Machine $($TagAssignment.VirtualMachine.ExtensionData.Moref.Value)" -Completed } } - end{} + end {} } function Get-NsxIpSet { @@ -25633,34 +25791,34 @@ function Get-NsxIpSet { #> - [CmdLetBinding(DefaultParameterSetName="Default")] + [CmdLetBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - #Objectid of IPSet - [string]$objectId, - [Parameter (Mandatory=$true,ParameterSetName="Name",Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] - #Name of IPSet - [string]$Name, - [Parameter (Mandatory=$false)] - #ScopeId of IPSet. Can define multiple scopeIds in a list to iterate accross scopes. - [string[]]$scopeId, - [Parameter (Mandatory=$false)] - #Return 'Readonly' (system) ipsets as well - [switch]$IncludeReadOnly=$false, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] - #Return only Universal objects - [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] - #Return only Locally scoped objects - [switch]$LocalOnly, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + #Objectid of IPSet + [string]$objectId, + [Parameter (Mandatory = $true, ParameterSetName = "Name", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] + #Name of IPSet + [string]$Name, + [Parameter (Mandatory = $false)] + #ScopeId of IPSet. Can define multiple scopeIds in a list to iterate accross scopes. + [string[]]$scopeId, + [Parameter (Mandatory = $false)] + #Return 'Readonly' (system) ipsets as well + [switch]$IncludeReadOnly = $false, + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] + #Return only Universal objects + [switch]$UniversalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] + #Return only Locally scoped objects + [switch]$LocalOnly, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -25690,18 +25848,19 @@ function Get-NsxIpSet { foreach ($scope in $scopeid ) { #All IPSets $URI = "/api/2.0/services/ipset/scope/$scope" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::list/ipset')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::list/ipset')) { if ( $name ) { - $ipsets += $response.list.ipset | where-object { $_.name -eq $name } - } else { + $ipsets += $response.list.ipset | Where-Object { $_.name -eq $name } + } + else { $ipsets += $response.list.ipset } } } if ( $ipsets -and ( -not $IncludeReadOnly )) { - $ipsets | where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $ipsets | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } elseif ( $ipsets ) { $ipsets @@ -25711,13 +25870,13 @@ function Get-NsxIpSet { #Just getting a single named Security group $URI = "/api/2.0/services/ipset/$objectId" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::ipset')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::ipset')) { $ipsets = $response.ipset } if ( -not $IncludeReadOnly ) { - $ipsets | where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $ipsets | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } else { $ipsets @@ -25771,41 +25930,42 @@ function New-NsxIpSet { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - #Name of the IpSet. - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - #Descript of the IPSet. - [ValidateNotNull()] - [string]$Description = "", - [Parameter (Mandatory=$false)] - #Single string of comma separated ipaddresses, or a collection of ip address strings. - [Alias ("IPAddresses")] - [string[]]$IPAddress, - [Parameter (Mandatory=$false)] - #Scope of object. For universal object creation, use the -Universal switch. - [ValidateScript({ + [Parameter (Mandatory = $true)] + #Name of the IpSet. + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + #Descript of the IPSet. + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $false)] + #Single string of comma separated ipaddresses, or a collection of ip address strings. + [Alias ("IPAddresses")] + [string[]]$IPAddress, + [Parameter (Mandatory = $false)] + #Scope of object. For universal object creation, use the -Universal switch. + [ValidateScript( { if ($_ -match "^globalroot-0$|universalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | universalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - #Create the IPSet as Universal object. - [switch]$Universal=$false, - [Parameter (Mandatory=$false)] - #Create the IPSet with the inheritance set. Allows the IP Set to be used at a lower scope. - [switch]$EnableInheritance=$false, - [Parameter (Mandatory=$false)] - #Return the objectid as a string rather than the whole XML object. - [switch]$ReturnObjectIdOnly=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + #Create the IPSet as Universal object. + [switch]$Universal = $false, + [Parameter (Mandatory = $false)] + #Create the IPSet with the inheritance set. Allows the IP Set to be used at a lower scope. + [switch]$EnableInheritance = $false, + [Parameter (Mandatory = $false)] + #Return the objectid as a string rather than the whole XML object. + [switch]$ReturnObjectIdOnly = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -25814,7 +25974,7 @@ function New-NsxIpSet { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("ipset") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description @@ -25826,16 +25986,16 @@ function New-NsxIpSet { } #Do the post - if ( $universal ) { $scopeId = "universalroot-0"} + if ( $universal ) { $scopeId = "universalroot-0" } $body = $xmlroot.OuterXml $URI = "/api/2.0/services/ipset/$($scopeId.ToLower())" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection if ( $ReturnObjectIdOnly) { $response.content } else { - Get-NsxIPSet -objectid $response.content -connection $connection + Get-NsxIpSet -objectId $response.content -Connection $connection } } end {} @@ -25863,20 +26023,20 @@ function Remove-NsxIpSet { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$IPSet, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$IPSet, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -25885,12 +26045,12 @@ function Remove-NsxIpSet { process { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ipset -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]") -and ( -not $force)) { - write-warning "Not removing $($Ipset.Name) as it is set as read-only. Use -Force to force deletion." + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ipset -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]") -and ( -not $force)) { + Write-Warning "Not removing $($Ipset.Name) as it is set as read-only. Use -Force to force deletion." } else { if ( $confirm ) { - $message = "IPSet removal is permanent." + $message = "IPSet removal is permanent." $question = "Proceed with removal of IP Set $($IPSet.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -25909,9 +26069,9 @@ function Remove-NsxIpSet { $URI = "/api/2.0/services/ipset/$($IPSet.objectId)?force=false" } - Write-Progress -activity "Remove IP Set $($IPSet.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove IP Set $($IPSet.Name)" -completed + Write-Progress -Activity "Remove IP Set $($IPSet.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove IP Set $($IPSet.Name)" -Completed } } } @@ -25919,7 +26079,7 @@ function Remove-NsxIpSet { end {} } -function Add-NsxIpSetMember { +function Add-NsxIpSetMember { <# .SYNOPSIS Adds a new member to an existing IP Set. @@ -25960,25 +26120,25 @@ function Add-NsxIpSetMember { [CmdletBinding()] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #Existing IPSet PowerNSX object to be modified. - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$IPSet, - [Parameter (Mandatory=$true)] - #Collection of ip addresses/ranges and/or CIDR's to be added to the ipset. - [ValidateNotNullOrEmpty()] - [string[]]$IPAddress, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #Existing IPSet PowerNSX object to be modified. + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$IPSet, + [Parameter (Mandatory = $true)] + #Collection of ip addresses/ranges and/or CIDR's to be added to the ipset. + [ValidateNotNullOrEmpty()] + [string[]]$IPAddress, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { $_ipset = $ipset.clonenode($true) - if ( -not (invoke-xpathquery -QueryMethod SelectSingleNode -Node $_ipset -query "child::value")) { + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ipset -query "child::value")) { Add-XmlElement -xmlRoot $_ipset -xmlElementName "value" -xmlElementText "" } @@ -25991,7 +26151,7 @@ function Add-NsxIpSetMember { } else { if ( $_ipset.value -split "," -contains $value ) { - write-warning "Value $value is already a member of the IPSet $($ipset.name)" + Write-Warning "Value $value is already a member of the IPSet $($ipset.name)" } else { $modified = $true @@ -26004,7 +26164,7 @@ function Add-NsxIpSetMember { #Do the post $body = $_ipset.OuterXml $URI = "/api/2.0/services/ipset/$($_ipset.objectId)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection try { [system.xml.xmldocument]$ipsetdoc = $response.content $ipsetdoc.ipset @@ -26017,7 +26177,7 @@ function Add-NsxIpSetMember { end {} } -function Remove-NsxIpSetMember { +function Remove-NsxIpSetMember { <# .SYNOPSIS Removes a member from an existing IP Set. @@ -26069,18 +26229,18 @@ function Remove-NsxIpSetMember { [CmdletBinding()] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #Existing IPSet PowerNSX object to be modified. - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$IPSet, - [Parameter (Mandatory=$true)] - #Collection of ip addresses/ranges and/or CIDR's to be removed from the ipset. - [ValidateNotNullOrEmpty()] - [string[]]$IPAddress, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #Existing IPSet PowerNSX object to be modified. + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$IPSet, + [Parameter (Mandatory = $true)] + #Collection of ip addresses/ranges and/or CIDR's to be removed from the ipset. + [ValidateNotNullOrEmpty()] + [string[]]$IPAddress, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -26088,9 +26248,10 @@ function Remove-NsxIpSetMember { $_ipset = $ipset.clonenode($true) $modified = $false - if ( ( $_ipset.value -eq "" ) -or ( -not (invoke-xpathquery -QueryMethod SelectSingleNode -Node $_ipset -query "child::value")) ) { - write-warning "IPSet $($ipset.name) ($($ipset.objectid)): No members found." - } else { + if ( ( $_ipset.value -eq "" ) -or ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ipset -query "child::value")) ) { + Write-Warning "IPSet $($ipset.name) ($($ipset.objectid)): No members found." + } + else { [system.collections.arraylist]$ValCollection = $_ipset.value -split "," foreach ( $value in $IPAddress ) { # An IPSET allows the users to enter a host as either 1.1.1.1 or @@ -26099,7 +26260,7 @@ function Remove-NsxIpSetMember { if ( ValidateIPHost $value ) { if ( $value -as [ipaddress] ) { if ( ( -not ( $valcollection -contains $value ) ) -and ( -not ( $valcollection -contains "$($value)/32" ) ) ) { - write-warning "IPSet $($ipset.name) ($($ipset.objectid)): $Value is not a member of IPSet" + Write-Warning "IPSet $($ipset.name) ($($ipset.objectid)): $Value is not a member of IPSet" } else { $modified = $true @@ -26109,7 +26270,7 @@ function Remove-NsxIpSetMember { } else { if ( ( -not ( $valcollection -contains $value ) ) -and ( -not ( $valcollection -contains "$(($value -split "/")[0])" ) ) ) { - write-warning "IPSet $($ipset.name) ($($ipset.objectid)): $Value is not a member of IPSet" + Write-Warning "IPSet $($ipset.name) ($($ipset.objectid)): $Value is not a member of IPSet" } else { $modified = $true @@ -26120,7 +26281,7 @@ function Remove-NsxIpSetMember { } else { if ( ( -not ( $valcollection -contains $value ) ) ) { - write-warning "IPSet $($ipset.name) ($($ipset.objectid)): $Value is not a member of IPSet" + Write-Warning "IPSet $($ipset.name) ($($ipset.objectid)): $Value is not a member of IPSet" } else { $modified = $true @@ -26142,7 +26303,7 @@ function Remove-NsxIpSetMember { #Do the post $body = $_ipset.OuterXml $URI = "/api/2.0/services/ipset/$($_ipset.objectId)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection try { [system.xml.xmldocument]$ipsetdoc = $response.content $ipsetdoc.ipset @@ -26173,33 +26334,33 @@ function Remove-NsxIpPool { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #IPPool object to be removed. - [ValidateScript({ ValidateIpPool $_ })] - [System.Xml.XmlElement]$IPPool, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #Force removal of the ippool, even if it has current allocations. - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #IPPool object to be removed. + [ValidateScript( { ValidateIpPool $_ })] + [System.Xml.XmlElement]$IPPool, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #Force removal of the ippool, even if it has current allocations. + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $IPPool -Query "descendant::usedAddressCount[. != 0]") -and ( -not $force)) { - write-warning "Not removing $($IPPool.Name) because it currently has allocated addresses. Use -force to override." + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $IPPool -query "descendant::usedAddressCount[. != 0]") -and ( -not $force)) { + Write-Warning "Not removing $($IPPool.Name) because it currently has allocated addresses. Use -force to override." } else { if ( $confirm ) { - $message = "IP Pool removal is permanent." + $message = "IP Pool removal is permanent." $question = "Proceed with removal of IP Pool $($IPPool.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -26209,9 +26370,9 @@ function Remove-NsxIpPool { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/2.0/services/ipam/pools/$($IPPool.objectId)?force=$($force.tostring().tolower())" - Write-Progress -activity "Remove IP Pool $($IPPool.Name)" - invoke-nsxrestmethod -method "delete" -uri $URI -connection $connection | out-null - write-progress -activity "Remove IP Pool $($IPPool.Name)" -completed + Write-Progress -Activity "Remove IP Pool $($IPPool.Name)" + Invoke-NsxRestMethod -method "delete" -URI $URI -connection $connection | Out-Null + Write-Progress -Activity "Remove IP Pool $($IPPool.Name)" -Completed } } } @@ -26245,34 +26406,34 @@ function Get-NsxMacSet { #> - [CmdLetBinding(DefaultParameterSetName="Default")] + [CmdLetBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$false,ParameterSetName="objectId")] - #Get Mac sets by objectid - [string]$objectId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] - #Get mac sets by name - [string]$Name, - [Parameter (Mandatory=$false)] - #ScopeId of MacSet. Can define multiple scopeIds in a list to iterate accross scopes. - [string[]]$scopeId, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] - #Return only Universal objects - [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] - #Return only Locally scoped objects - [switch]$LocalOnly, - [Parameter (Mandatory=$false)] - #Include mac sets with readonly attribute - [switch]$IncludeReadOnly=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, ParameterSetName = "objectId")] + #Get Mac sets by objectid + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] + #Get mac sets by name + [string]$Name, + [Parameter (Mandatory = $false)] + #ScopeId of MacSet. Can define multiple scopeIds in a list to iterate accross scopes. + [string[]]$scopeId, + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] + #Return only Universal objects + [switch]$UniversalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] + #Return only Locally scoped objects + [switch]$LocalOnly, + [Parameter (Mandatory = $false)] + #Include mac sets with readonly attribute + [switch]$IncludeReadOnly = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -26302,11 +26463,12 @@ function Get-NsxMacSet { foreach ($scope in $scopeid ) { #All IPSets $URI = "/api/2.0/services/macset/scope/$scope" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::list/macset')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::list/macset')) { if ( $name ) { - $macsets += $response.list.macset | where-object { $_.name -eq $name } - } else { + $macsets += $response.list.macset | Where-Object { $_.name -eq $name } + } + else { $macsets += $response.list.macset } } @@ -26314,7 +26476,7 @@ function Get-NsxMacSet { #Filter readonly if switch not set if ( $macsets -and (-not $IncludeReadOnly )) { - $macsets| where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $macsets | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } else { $macsets @@ -26324,14 +26486,14 @@ function Get-NsxMacSet { #Just getting a single named MACset $URI = "/api/2.0/services/macset/$objectId" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::macset')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::macset')) { $macsets = $response.macset } #Filter readonly if switch not set if ( -not $IncludeReadOnly ) { - $macsets| where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $macsets | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } else { $macsets @@ -26342,7 +26504,7 @@ function Get-NsxMacSet { end {} } -function New-NsxMacSet { +function New-NsxMacSet { <# .SYNOPSIS Creates a new NSX MACSet. @@ -26374,40 +26536,41 @@ function New-NsxMacSet { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - #Name of the MacSet - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - #Description of the MacSet - [ValidateNotNull()] - [string]$Description = "", - [Parameter (Mandatory=$false)] - #Single string accepting comma separated Mac Addresses - [string]$MacAddresses, - [Parameter (Mandatory=$false)] - #Scope of object. For universal object creation, use the -Universal switch. - [ValidateScript({ + [Parameter (Mandatory = $true)] + #Name of the MacSet + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + #Description of the MacSet + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $false)] + #Single string accepting comma separated Mac Addresses + [string]$MacAddresses, + [Parameter (Mandatory = $false)] + #Scope of object. For universal object creation, use the -Universal switch. + [ValidateScript( { if ($_ -match "^globalroot-0$|universalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | universalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - #Create the MacSet as Universal object. - [switch]$Universal=$false, - [Parameter (Mandatory=$false)] - #Create the MacSet with the inheritance set. Allows the MacSet to be used at a lower scope. - [switch]$EnableInheritance=$false, - [Parameter (Mandatory=$false)] - #Return the objectid as a string rather than the whole XML object. - [switch]$ReturnObjectIdOnly=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + #Create the MacSet as Universal object. + [switch]$Universal = $false, + [Parameter (Mandatory = $false)] + #Create the MacSet with the inheritance set. Allows the MacSet to be used at a lower scope. + [switch]$EnableInheritance = $false, + [Parameter (Mandatory = $false)] + #Return the objectid as a string rather than the whole XML object. + [switch]$ReturnObjectIdOnly = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -26416,7 +26579,7 @@ function New-NsxMacSet { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("macset") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description @@ -26429,15 +26592,15 @@ function New-NsxMacSet { #Do the post $body = $xmlroot.OuterXml - if ( $universal ) { $scopeId = "universalroot-0"} + if ( $universal ) { $scopeId = "universalroot-0" } $URI = "/api/2.0/services/macset/$($scopeId.tolower())" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection if ( $ReturnObjectIdOnly) { $response.content } else { - Get-NsxMacSet -objectid $response.content -connection $connection + Get-NsxMacSet -objectId $response.content -Connection $connection } } end {} @@ -26469,23 +26632,23 @@ function Remove-NsxMacSet { -confirm:$false can be used to avoid being prompted. #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - #Macset as retrieved by get-nsxmacset to remove - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$MacSet, - [Parameter (Mandatory=$False)] - #Set to false to disable prompt on deletion - [switch]$confirm=$true, - [Parameter (Mandatory=$False)] - #Enable force to remove objects in use, or set to readonly (system) - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + #Macset as retrieved by get-nsxmacset to remove + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$MacSet, + [Parameter (Mandatory = $False)] + #Set to false to disable prompt on deletion + [switch]$confirm = $true, + [Parameter (Mandatory = $False)] + #Enable force to remove objects in use, or set to readonly (system) + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -26494,12 +26657,12 @@ function Remove-NsxMacSet { process { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $macset -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]") -and ( -not $force)) { - write-warning "Not removing $($MacSet.Name) as it is set as read-only. Use -Force to force deletion." + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $macset -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]") -and ( -not $force)) { + Write-Warning "Not removing $($MacSet.Name) as it is set as read-only. Use -Force to force deletion." } else { if ( $confirm ) { - $message = "MACSet removal is permanent." + $message = "MACSet removal is permanent." $question = "Proceed with removal of MAC Set $($MACSet.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -26517,9 +26680,9 @@ function Remove-NsxMacSet { $URI = "/api/2.0/services/macset/$($MACSet.objectId)?force=false" } - Write-Progress -activity "Remove MAC Set $($MACSet.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove MAC Set $($MACSet.Name)" -completed + Write-Progress -Activity "Remove MAC Set $($MACSet.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove MAC Set $($MACSet.Name)" -Completed } } @@ -26554,42 +26717,42 @@ function Get-NsxService { PS C:\> Get-NsxService -port 1234 #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$false,ParameterSetName="objectId")] - #Return service by objectId - [string]$objectId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] - #Return service by name - [string]$Name, - [Parameter (Mandatory=$false,ParameterSetName="Port",Position=1)] - #Return services that have a either a matching port, or are defiuned by a range into which the specified port falls - [int]$Port, - [Parameter (Mandatory=$false)] - #ScopeId of Service Group. Can define multiple scopeIds in a list to iterate accross scopes. + [Parameter (Mandatory = $false, ParameterSetName = "objectId")] + #Return service by objectId + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] + #Return service by name + [string]$Name, + [Parameter (Mandatory = $false, ParameterSetName = "Port", Position = 1)] + #Return services that have a either a matching port, or are defiuned by a range into which the specified port falls + [int]$Port, + [Parameter (Mandatory = $false)] + #ScopeId of Service Group. Can define multiple scopeIds in a list to iterate accross scopes. [string[]]$scopeId, - [Parameter (Mandatory=$false)] - #Include services with readonly attribute - [switch]$IncludeReadOnly=$false, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] - #Return only Universal objects - [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] - #Return only Locally scoped objects - [switch]$LocalOnly, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + #Include services with readonly attribute + [switch]$IncludeReadOnly = $false, + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] + #Return only Universal objects + [switch]$UniversalOnly, + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] + #Return only Locally scoped objects + [switch]$LocalOnly, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - if (-not $PsBoundParameters.ContainsKey("scopeId") ){ + if (-not $PsBoundParameters.ContainsKey("scopeId") ) { switch ( $PSCmdlet.ParameterSetName ) { "UniversalOnly" { @@ -26616,12 +26779,12 @@ function Get-NsxService { #Just getting a single named service group $URI = "/api/2.0/services/application/$objectId" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::application')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::application')) { $svcs = $response.application #Filter readonly if switch not set if ( -not $IncludeReadOnly ) { - $svcs| where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $svcs | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } else { $svcs @@ -26635,12 +26798,12 @@ function Get-NsxService { foreach ($scope in $scopeid ) { $application = $null $URI = "/api/2.0/services/application/scope/$scope" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::list/application')) { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::list/application')) { foreach ( $application in $response.list.application ) { - if ( $application | get-member -memberType Properties -name element ) { - write-debug "$($MyInvocation.MyCommand.Name) : Testing service $($application.name) with ports: $($application.element.value)" + if ( $application | Get-Member -MemberType Properties -Name element ) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Testing service $($application.name) with ports: $($application.element.value)" #The port configured on a service is stored in element.value and can be #either an int, range (expressed as inta-intb, or a comma separated list of ints and/or ranges @@ -26652,16 +26815,16 @@ function Get-NsxService { "^[\d,-]+$" { [string[]]$valarray = $application.element.value.split(",") - foreach ($val in $valarray) { + foreach ($val in $valarray) { - write-debug "$($MyInvocation.MyCommand.Name) : Converting range expression and expanding: $val" - [int[]]$ports = invoke-expression ( $val -replace '^(\d+)-(\d+)$','($1..$2)' ) + Write-Debug "$($MyInvocation.MyCommand.Name) : Converting range expression and expanding: $val" + [int[]]$ports = Invoke-Expression ( $val -replace '^(\d+)-(\d+)$', '($1..$2)' ) #Then test if the port int array contains what we are looking for... if ( $ports.contains($port) ) { - write-debug "$($MyInvocation.MyCommand.Name) : Matched Service $($Application.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Matched Service $($Application.name)" #Filter readonly if switch not set if ( -not $IncludeReadOnly ) { - $application| where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $application | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } else { $application @@ -26671,13 +26834,14 @@ function Get-NsxService { } } - default { #do nothing, port number is not numeric.... - write-debug "$($MyInvocation.MyCommand.Name) : Ignoring $($application.name) - non numeric element: $($application.element | format-xml)" + default { + #do nothing, port number is not numeric.... + Write-Debug "$($MyInvocation.MyCommand.Name) : Ignoring $($application.name) - non numeric element: $($application.element | Format-XML)" } } } else { - write-debug "$($MyInvocation.MyCommand.Name) : Ignoring $($application.name) - element not defined" + Write-Debug "$($MyInvocation.MyCommand.Name) : Ignoring $($application.name) - element not defined" } } } @@ -26689,11 +26853,12 @@ function Get-NsxService { foreach ($scope in $scopeid ) { #All Services $URI = "/api/2.0/services/application/scope/$scope" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query 'descendant::list/application')) { - if ( $name ) { - $svcs += $response.list.application | where-object { $_.name -eq $name } - } else { + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query 'descendant::list/application')) { + if ( $name ) { + $svcs += $response.list.application | Where-Object { $_.name -eq $name } + } + else { $svcs += $response.list.application } } @@ -26701,7 +26866,7 @@ function Get-NsxService { #Filter readonly if switch not set if ( -not $IncludeReadOnly ) { - $svcs| where-object { -not ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_ -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } + $svcs | Where-Object { -not ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_ -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]")) } } else { $svcs @@ -26713,7 +26878,7 @@ function Get-NsxService { end {} } -function New-NsxService { +function New-NsxService { <# .SYNOPSIS @@ -26734,49 +26899,50 @@ function New-NsxService { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNull()] - [string]$Description = "", - [Parameter (Mandatory=$true)] - [ValidateSet ( "AARP", "AH", "ARPATALK", "ATMFATE", "ATMMPOA", - "BPQ", "CUST", "DEC", "DIAG", "DNA_DL", "DNA_RC", "DNA_RT", "ESP", - "FR_ARP", "FTP", "GRE", "ICMP", "IEEE_802_1Q", "IGMP", "IPCOMP", - "IPV4", "IPV6", "IPV6FRAG", "IPV6ICMP", "IPV6NONXT", "IPV6OPTS", - "IPV6ROUTE", "IPX", "L2_OTHERS", "L2TP", "L3_OTHERS", "LAT", "LLC", - "LOOP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", - "NBNS_BROADCAST", "NETBEUI", "ORACLE_TNS", "PPP", "PPP_DISC", - "PPP_SES", "RARP", "RAW_FR", "RSVP", "SCA", "SCTP", "SUN_RPC_TCP", - "SUN_RPC_UDP", "TCP", "UDP", "X25" )] - [string]$Protocol, - [Parameter (Mandatory=$false)] - [string]$port, - [Parameter (Mandatory=$false)] - [string]$SourcePort, - [Parameter (Mandatory=$false)] - #Scope of object. For universal object creation, use the -Universal switch. - [ValidateScript({ + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $true)] + [ValidateSet ( "AARP", "AH", "ARPATALK", "ATMFATE", "ATMMPOA", + "BPQ", "CUST", "DEC", "DIAG", "DNA_DL", "DNA_RC", "DNA_RT", "ESP", + "FR_ARP", "FTP", "GRE", "ICMP", "IEEE_802_1Q", "IGMP", "IPCOMP", + "IPV4", "IPV6", "IPV6FRAG", "IPV6ICMP", "IPV6NONXT", "IPV6OPTS", + "IPV6ROUTE", "IPX", "L2_OTHERS", "L2TP", "L3_OTHERS", "LAT", "LLC", + "LOOP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", + "NBNS_BROADCAST", "NETBEUI", "ORACLE_TNS", "PPP", "PPP_DISC", + "PPP_SES", "RARP", "RAW_FR", "RSVP", "SCA", "SCTP", "SUN_RPC_TCP", + "SUN_RPC_UDP", "TCP", "UDP", "X25" )] + [string]$Protocol, + [Parameter (Mandatory = $false)] + [string]$port, + [Parameter (Mandatory = $false)] + [string]$SourcePort, + [Parameter (Mandatory = $false)] + #Scope of object. For universal object creation, use the -Universal switch. + [ValidateScript( { if ($_ -match "^globalroot-0$|universalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | universalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - #Create the Service as Universal object. - [switch]$Universal=$false, - [Parameter (Mandatory=$false)] - #Create the Service with the inheritance set. Allows the Service to be used at a lower scope. - [switch]$EnableInheritance=$false, - [Parameter (Mandatory=$false)] - [switch]$ReturnObjectIdOnly=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + #Create the Service as Universal object. + [switch]$Universal = $false, + [Parameter (Mandatory = $false)] + #Create the Service with the inheritance set. Allows the Service to be used at a lower scope. + [switch]$EnableInheritance = $false, + [Parameter (Mandatory = $false)] + [switch]$ReturnObjectIdOnly = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -26791,7 +26957,7 @@ function New-NsxService { throw "TCP or UDP port numbers must be either an integer, range (nn-nn) or commma separated integers or ranges." } - if ( ( @("FTP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", "SUN_RPC_TCP", "SUN_RPC_UDP") -contains $Protocol ) -and (-not ( ($port -as [int]) -and ( (1..65535) -contains $port )))) { + if ( ( @("FTP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", "SUN_RPC_TCP", "SUN_RPC_UDP") -contains $Protocol ) -and (-not ( ($port -as [int]) -and ( (1..65535) -contains $port )))) { throw "Valid port numbers must be an integer between 1-65535." } @@ -26807,7 +26973,7 @@ function New-NsxService { throw "L3_OTHER protocoltype `'port`' must specify a valid IP protocol number in the range 1-255" } - if ($PSBoundParameters.ContainsKey("Port") -and (($protocol -notmatch "ICMP|TCP|UDP") -and ( $AllServicesNotRequiringPort -contains $Protocol ))) { + if ($PSBoundParameters.ContainsKey("Port") -and (($protocol -notmatch "ICMP|TCP|UDP") -and ( $AllServicesNotRequiringPort -contains $Protocol ))) { #Validation is only executed if user specified a value for port... ICMP, UDP and TCP are special in that you can, but dont have to specify a 'port'. throw "Specified protocol does not allow a port value to be specified." } @@ -26818,7 +26984,7 @@ function New-NsxService { throw "TCP or UDP source port numbers must be either an integer, range (nn-nn) or commma separated integers or ranges." } - if ( ( @("FTP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", "SUN_RPC_TCP", "SUN_RPC_UDP") -contains $Protocol ) -and (-not ( ($SourcePort -as [int]) -and ( (1..65535) -contains $SourcePort )))) { + if ( ( @("FTP", "MS_RPC_TCP", "MS_RPC_UDP", "NBDG_BROADCAST", "NBNS_BROADCAST", "ORACLE_TNS", "SUN_RPC_TCP", "SUN_RPC_UDP") -contains $Protocol ) -and (-not ( ($SourcePort -as [int]) -and ( (1..65535) -contains $SourcePort )))) { throw "Valid source port numbers must be an integer between 1-65535." } @@ -26832,14 +26998,14 @@ function New-NsxService { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("application") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description #Create the 'element' element ??? :) [System.XML.XMLElement]$xmlElement = $XMLDoc.CreateElement("element") - $xmlRoot.appendChild($xmlElement) | out-null + $xmlRoot.appendChild($xmlElement) | Out-Null Add-XmlElement -xmlRoot $xmlElement -xmlElementName "applicationProtocol" -xmlElementText $Protocol.ToUpper() if ( $PSBoundParameters.ContainsKey("Port")) { @@ -26854,15 +27020,15 @@ function New-NsxService { #Do the post $body = $xmlroot.OuterXml - if ( $universal ) { $scopeId = "universalroot-0"} + if ( $universal ) { $scopeId = "universalroot-0" } $URI = "/api/2.0/services/application/$($scopeId.tolower())" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection if ( $ReturnObjectIdOnly) { $response.content } else { - Get-NsxService -objectId $response.content -connection $connection + Get-NsxService -objectId $response.content -Connection $connection } } end {} @@ -26886,21 +27052,21 @@ function Remove-NsxService { Removes the service TestService #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$Service, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$Service, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -26909,12 +27075,12 @@ function Remove-NsxService { process { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Service -Query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]") -and ( -not $force)) { - write-warning "Not removing $($Service.Name) as it is set as read-only. Use -Force to force deletion." + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Service -query "descendant::extendedAttributes/extendedAttribute[name=`"isReadOnly`" and value=`"true`"]") -and ( -not $force)) { + Write-Warning "Not removing $($Service.Name) as it is set as read-only. Use -Force to force deletion." } else { if ( $confirm ) { - $message = "Service removal is permanent." + $message = "Service removal is permanent." $question = "Proceed with removal of Service $($Service.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -26932,9 +27098,9 @@ function Remove-NsxService { $URI = "/api/2.0/services/application/$($Service.objectId)?force=false" } - Write-Progress -activity "Remove Service $($Service.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Service $($Service.Name)" -completed + Write-Progress -Activity "Remove Service $($Service.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Service $($Service.Name)" -Completed } } @@ -26985,37 +27151,37 @@ Function Get-NsxServiceGroup { MS Exchange 2010 Unified Messaging Server #> - [CmdLetBinding(DefaultParameterSetName="Default")] + [CmdLetBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,ParameterSetName="objectId")] + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] #Objectid of Service Group [string]$objectId, - [Parameter (Mandatory=$true,Position=1,ParameterSetName="Name")] - [Parameter (Mandatory=$false, ParameterSetName="UniversalOnly", Position=1)] - [Parameter (Mandatory=$false, ParameterSetName="LocalOnly", Position=1)] + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "Name")] + [Parameter (Mandatory = $false, ParameterSetName = "UniversalOnly", Position = 1)] + [Parameter (Mandatory = $false, ParameterSetName = "LocalOnly", Position = 1)] # Name of the Service Group [ValidateNotNullorEmpty()] [string]$Name, - [Parameter (Mandatory=$false)] + [Parameter (Mandatory = $false)] #ScopeId of Service Group. Can define multiple scopeIds in a list to iterate accross scopes. [string[]]$scopeId, - [Parameter (Mandatory=$true, ParameterSetName="UniversalOnly")] + [Parameter (Mandatory = $true, ParameterSetName = "UniversalOnly")] #Return only Universal objects [switch]$UniversalOnly, - [Parameter (Mandatory=$true, ParameterSetName="LocalOnly")] + [Parameter (Mandatory = $true, ParameterSetName = "LocalOnly")] #Return only Locally scoped objects [switch]$LocalOnly, - [Parameter (Mandatory=$False)] + [Parameter (Mandatory = $False)] #PowerNSX Connection object [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - if ( -not $PsBoundParameters.ContainsKey("scopeId") ){ + if ( -not $PsBoundParameters.ContainsKey("scopeId") ) { switch ( $PSCmdlet.ParameterSetName ) { "UniversalOnly" { @@ -27042,15 +27208,15 @@ Function Get-NsxServiceGroup { foreach ($scope in $scopeid ) { $URI = "/api/2.0/services/applicationgroup/scope/$scope" - [system.xml.xmlDocument]$response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [system.xml.xmlDocument]$response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query "child::list/applicationGroup")){ + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::list/applicationGroup")) { $servicegroup += $response.list.applicationGroup } } - if ($PsBoundParameters.ContainsKey("Name")){ - $servicegroup | where-object {$_.name -eq $name} + if ($PsBoundParameters.ContainsKey("Name")) { + $servicegroup | Where-Object { $_.name -eq $name } } else { $servicegroup @@ -27059,7 +27225,7 @@ Function Get-NsxServiceGroup { else { $URI = "/api/2.0/services/applicationgroup/$objectid" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $response.applicationGroup } @@ -27123,31 +27289,31 @@ function Get-NsxServiceGroupMember { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateServiceOrServiceGroup $_ })] - [System.Xml.XmlElement]$ServiceGroup, - [Parameter (Mandatory=$false)] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - [string]$objectId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateServiceOrServiceGroup $_ })] + [System.Xml.XmlElement]$ServiceGroup, + [Parameter (Mandatory = $false)] + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + [string]$objectId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - begin{ + begin { } - process{ + process { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ServiceGroup -Query "child::member")){ + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ServiceGroup -query "child::member")) { $ServiceGroup.member } } - end{} + end {} } function Remove-NsxServiceGroup { @@ -27178,29 +27344,29 @@ function Remove-NsxServiceGroup { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateServiceGroup $_ })] - [System.Xml.XmlElement]$ServiceGroup, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateServiceGroup $_ })] + [System.Xml.XmlElement]$ServiceGroup, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) - begin{ + begin { } - process{ + process { if ( $confirm ) { - $message = "Service Group removal is permanent." + $message = "Service Group removal is permanent." $question = "Proceed with removal of Service group $($ServiceGroup.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -27218,9 +27384,9 @@ function Remove-NsxServiceGroup { $URI = "/api/2.0/services/applicationgroup/$($ServiceGroup.objectid)?force=false" } - Write-Progress -activity "Remove Service Group $($ServiceGroup.Name)" - $null = Invoke-NsxWebRequest -method "delete" -uri $URI -connection $connection - Write-progress -activity "Remove Service Group $($ServiceGroup.Name)" -completed + Write-Progress -Activity "Remove Service Group $($ServiceGroup.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Service Group $($ServiceGroup.Name)" -Completed } } @@ -27264,34 +27430,35 @@ function New-NsxServiceGroup { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNull()] - [string]$Description = "", - [Parameter (Mandatory=$false)] - #Scope of object. For universal object creation, use the -Universal switch. - [ValidateScript({ + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $false)] + #Scope of object. For universal object creation, use the -Universal switch. + [ValidateScript( { if ($_ -match "^globalroot-0$|universalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | universalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - #Create the Service Group as Universal object. - [switch]$Universal=$false, - [Parameter (Mandatory=$false)] - #Create the Service Group with the inheritance set. Allows the Service Group to be used at a lower scope. - [switch]$EnableInheritance=$false, - [Parameter (Mandatory=$false)] - [switch]$ReturnObjectIdOnly=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + #Create the Service Group as Universal object. + [switch]$Universal = $false, + [Parameter (Mandatory = $false)] + #Create the Service Group with the inheritance set. Allows the Service Group to be used at a lower scope. + [switch]$EnableInheritance = $false, + [Parameter (Mandatory = $false)] + [switch]$ReturnObjectIdOnly = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -27303,7 +27470,7 @@ function New-NsxServiceGroup { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("applicationGroup") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description @@ -27312,17 +27479,17 @@ function New-NsxServiceGroup { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "inheritanceAllowed" -xmlElementText "True" } - if ( $universal ) { $scopeId = "universalroot-0"} + if ( $universal ) { $scopeId = "universalroot-0" } $body = $xmlroot.OuterXml $uri = "/api/2.0/services/applicationgroup/$($scopeId.ToLower())" - $response = invoke-nsxwebrequest -uri $uri -method "post" -body $body -connection $connection + $response = Invoke-NsxWebRequest -URI $uri -method "post" -body $body -connection $connection if ( $ReturnObjectIdOnly) { $response.content } else { - Get-NsxServiceGroup -objectId $response.content -connection $connection + Get-NsxServiceGroup -objectId $response.content -Connection $connection } } @@ -27361,26 +27528,26 @@ function Add-NsxServiceGroupMember { param ( #Mastergroup added from Get-NsxServiceGroup - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateServiceGroup $_ })] - [System.Xml.XmlElement]$ServiceGroup, - [Parameter (Mandatory=$true,Position=1)] - [ValidateScript({ ValidateServiceOrServiceGroup $_ })] - #The [] in XmlElement means it can expect more than one object! - [System.Xml.XmlElement[]]$Member, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateServiceGroup $_ })] + [System.Xml.XmlElement]$ServiceGroup, + [Parameter (Mandatory = $true, Position = 1)] + [ValidateScript( { ValidateServiceOrServiceGroup $_ })] + #The [] in XmlElement means it can expect more than one object! + [System.Xml.XmlElement[]]$Member, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { - foreach ($Mem in $Member){ + foreach ($Mem in $Member) { $URI = "/api/2.0/services/applicationgroup/$($ServiceGroup.objectId)/members/$($Mem.objectId)" - $null = invoke-nsxwebrequest -method "PUT" -uri $URI -connection $connection - Write-Progress -activity "Adding Service or Service Group $($Mem) to Service Group $($ServiceGroup)" + $null = Invoke-NsxWebRequest -method "PUT" -URI $URI -connection $connection + Write-Progress -Activity "Adding Service or Service Group $($Mem) to Service Group $($ServiceGroup)" } } @@ -27431,39 +27598,40 @@ function Get-NsxApplicableMember { Get the applicable member list for Universal ServiceGroup membership. #> - [CmdLetBinding(DefaultParameterSetName="securitygroup")] + [CmdLetBinding(DefaultParameterSetName = "securitygroup")] param ( - [Parameter (Mandatory=$false)] - [ValidateScript({ + [Parameter (Mandatory = $false)] + [ValidateScript( { if ($_ -match "^globalroot-0$|universalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | universalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$true, ParameterSetName="securitygroup" )] - [switch]$SecurityGroupApplicableMembers, - [Parameter (Mandatory=$true, ParameterSetName="applicationgroup" )] - [switch]$ServiceGroupApplicableMembers, - [Parameter (Mandatory=$true, ParameterSetName="securitygroup" )] - [ValidateSet("IPSet", "ClusterComputeResource", "VirtualWire", "VirtualMachine", "DirectoryGroup", "SecurityGroup", "VirtualApp", "ResourcePool", "DistributedVirtualPortgroup", "Datacenter", "Network", "Vnic", "SecurityTag", "MACSet", IgnoreCase=$false)] - [string]$MemberType, - [Parameter (Mandatory=$false)] - [switch]$Universal=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $true, ParameterSetName = "securitygroup" )] + [switch]$SecurityGroupApplicableMembers, + [Parameter (Mandatory = $true, ParameterSetName = "applicationgroup" )] + [switch]$ServiceGroupApplicableMembers, + [Parameter (Mandatory = $true, ParameterSetName = "securitygroup" )] + [ValidateSet("IPSet", "ClusterComputeResource", "VirtualWire", "VirtualMachine", "DirectoryGroup", "SecurityGroup", "VirtualApp", "ResourcePool", "DistributedVirtualPortgroup", "Datacenter", "Network", "Vnic", "SecurityTag", "MACSet", IgnoreCase = $false)] + [string]$MemberType, + [Parameter (Mandatory = $false)] + [switch]$Universal = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - begin{ + begin { } - process{ + process { - if ( $universal ) { $scopeId = "universalroot-0"} + if ( $universal ) { $scopeId = "universalroot-0" } if ( $PSCmdlet.ParameterSetName -eq "securitygroup") { $URI = "/api/2.0/services/securitygroup/scope/$($scopeId.ToLower())/members/$MemberType" @@ -27472,12 +27640,12 @@ function Get-NsxApplicableMember { $URI = "/api/2.0/services/applicationgroup/scope/$($scopeId.ToLower())/members/" } try { - $response = Invoke-NsxWebRequest -Uri $Uri -method Get -connection $connection + $response = Invoke-NsxWebRequest -URI $Uri -method Get -connection $connection } catch { throw "Failed retrieving applicable members. $_" } - if ( $response | get-member -membertype Property -Name Content ) { + if ( $response | Get-Member -MemberType Property -Name Content ) { try { [xml]$content = $response.Content if ( Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $content -query "child::list/basicinfo") { @@ -27493,7 +27661,7 @@ function Get-NsxApplicableMember { } } - end{} + end {} } @@ -27507,7 +27675,7 @@ function Add-NsxSourceDestNode { param ( [system.xml.xmlelement]$Rule, - [ValidateSet ("sources","destinations",IgnoreCase=$false)] + [ValidateSet ("sources", "destinations", IgnoreCase = $false)] [string]$NodeType, [switch]$negated ) @@ -27515,11 +27683,11 @@ function Add-NsxSourceDestNode { #Create the parent sources element $XmlDoc = $Rule.OwnerDocument [System.XML.XMLElement]$xmlNode = $XMLDoc.CreateElement($NodeType) - $Rule.AppendChild($xmlNode) | out-null + $Rule.AppendChild($xmlNode) | Out-Null #The excluded attribute indicates negation $xmlNegated = $xmlDoc.createAttribute("excluded") - $xmlNode.Attributes.Append($xmlNegated) | out-null + $xmlNode.Attributes.Append($xmlNegated) | Out-Null $xmlNegated.value = $Negated.ToString().ToLower() } @@ -27533,8 +27701,8 @@ function Add-NsxSourceDestMember { # - Removed negation logic (moved back to new-rule due to logic not being applicable to individual member instances, function to be duplicated in set-rule cmdlet to allow flipping of negation (and other functions)) param ( - [Parameter (Mandatory=$true)] - [ValidateSet ("source","destination",IgnoreCase=$false)] + [Parameter (Mandatory = $true)] + [ValidateSet ("source", "destination", IgnoreCase = $false)] [string]$membertype, [object[]]$memberlist, [System.Xml.XmlElement]$rule @@ -27545,52 +27713,53 @@ function Add-NsxSourceDestMember { # Get SrcDestNode parent element. Have to use xpath here as the elem may be empty and powershell unhelpfully turns that into a string for us :| if ( $membertype -eq "Source" ) { - [System.Xml.XmlElement]$xmlSrcDestNode = invoke-xpathquery -query "child::sources" -QueryMethod SelectSingleNode -node $rule + [System.Xml.XmlElement]$xmlSrcDestNode = Invoke-XpathQuery -query "child::sources" -QueryMethod SelectSingleNode -Node $rule } else { - [System.Xml.XmlElement]$xmlSrcDestNode = invoke-xpathquery -query "child::destinations" -QueryMethod SelectSingleNode -node $rule + [System.Xml.XmlElement]$xmlSrcDestNode = Invoke-XpathQuery -query "child::destinations" -QueryMethod SelectSingleNode -Node $rule } #Loop the memberlist and create appropriate element in the srcdest node. foreach ($member in $memberlist) { if ( ( $member -as [ipaddress]) -or ( ValidateIPRange -argument $member ) -or ( ValidateIPPrefix -argument $member ) ) { - write-debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $member" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $member" } else { - write-debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $($member.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building source/dest node for $($member.name)" } #Build the return XML element and append to our srcdestnode [System.XML.XMLElement]$xmlMember = $XMLDoc.CreateElement($memberType) - $xmlSrcDestNode.appendChild($xmlMember) | out-null + $xmlSrcDestNode.appendChild($xmlMember) | Out-Null if ( ( $member -as [ipaddress]) -or ( ValidateIPRange -argument $member ) -or ( ValidateIPPrefix -argument $member ) ) { #Item is v4 or 6 address - write-debug "$($MyInvocation.MyCommand.Name) : Object $member is an ipaddress" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $member is an ipaddress" Add-XmlElement -xmlRoot $xmlMember -xmlElementName "value" -xmlElementText $member Add-XmlElement -xmlRoot $xmlMember -xmlElementName "type" -xmlElementText "Ipv4Address" } elseif ( $member -is [system.xml.xmlelement] ) { - write-debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as xml element" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as xml element" #XML representation of NSX object passed - ipset, sec group or logical switch #get appropritate name, value. Add-XmlElement -xmlRoot $xmlMember -xmlElementName "value" -xmlElementText $member.objectId Add-XmlElement -xmlRoot $xmlMember -xmlElementName "name" -xmlElementText $member.name Add-XmlElement -xmlRoot $xmlMember -xmlElementName "type" -xmlElementText $member.objectTypeName - } else { + } + else { - write-debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as supported powercli object" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is specified as supported powercli object" #Proper PowerCLI Object passed #If passed object is a NIC, we have to do some more digging if ( $member -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { - write-debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is vNic" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($member.name) is vNic" #Naming based on DFW UI standard Add-XmlElement -xmlRoot $xmlMember -xmlElementName "name" -xmlElementText "$($member.parent.name) - $($member.name)" Add-XmlElement -xmlRoot $xmlMember -xmlElementName "type" -xmlElementText "Vnic" - $vmUuid = ($member.parent | get-view).config.instanceuuid + $vmUuid = ($member.parent | Get-View).config.instanceuuid $MemberMoref = "$vmUuid.$($member.id.substring($member.id.length-3))" Add-XmlElement -xmlRoot $xmlMember -xmlElementName "value" -xmlElementText $MemberMoref } @@ -27624,25 +27793,25 @@ function New-NsxServiceNode { [System.XML.XMLElement]$xmlItem = $XMLDoc.CreateElement("service") Add-XmlElement -xmlRoot $xmlItem -xmlElementName "protocolName" -xmlElementText $itemSplit[0].ToUpper() Add-XmlElement -xmlRoot $xmlItem -xmlElementName "destinationPort" -xmlElementText $itemSplit[1] - write-debug "$($MyInvocation.MyCommand.Name) : Building service node for $($item)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building service node for $($item)" } # Otherwise we assume its just a Protocol with no port specified - elseif ($item -is [string]) { + elseif ($item -is [string]) { [System.XML.XMLElement]$xmlItem = $XMLDoc.CreateElement("service") Add-XmlElement -xmlRoot $xmlItem -xmlElementName "protocolName" -xmlElementText $item.ToUpper() - write-debug "$($MyInvocation.MyCommand.Name) : Building service node for $($item)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building service node for $($item)" } # or its either an XML object, or a collection of objects (already verified as XML objects through validation script) elseif ( ( $item -is [System.Xml.XmlElement] ) -or ( $item -is [System.Object] ) ) { foreach ( $serviceitem in $item ) { [System.XML.XMLElement]$xmlItem = $XMLDoc.CreateElement("service") Add-XmlElement -xmlRoot $xmlItem -xmlElementName "value" -xmlElementText $serviceItem.objectId - $xmlReturn.appendChild($xmlItem) | out-null - write-debug "$($MyInvocation.MyCommand.Name) : Building service node for $($item.name)" + $xmlReturn.appendChild($xmlItem) | Out-Null + Write-Debug "$($MyInvocation.MyCommand.Name) : Building service node for $($item.name)" } } - $xmlReturn.appendChild($xmlItem) | out-null + $xmlReturn.appendChild($xmlItem) | Out-Null } $xmlReturn @@ -27655,9 +27824,9 @@ function New-NsxEdgeServiceNode { param ( [Parameter (Mandatory = $true)] - [object[]]$itemlist, + [object[]]$itemlist, [Parameter (Mandatory = $true)] - [System.XML.XMLElement]$xmlRule + [System.XML.XMLElement]$xmlRule ) $xmlDoc = $xmlRule.OwnerDocument @@ -27672,20 +27841,20 @@ function New-NsxEdgeServiceNode { $null = $Application.AppendChild($svc) Add-XmlElement -xmlRoot $svc -xmlElementName "protocol" -xmlElementText $itemSplit[0].ToUpper() Add-XmlElement -xmlRoot $svc -xmlElementName "port" -xmlElementText $itemSplit[1] - write-debug "$($MyInvocation.MyCommand.Name) : Building protocol/port service node for $($item)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building protocol/port service node for $($item)" } # Otherwise we assume its just a Protocol with no port specified - elseif ($item -is [string]) { + elseif ($item -is [string]) { $svc = $XMLDoc.CreateElement("service") $null = $Application.AppendChild($svc) Add-XmlElement -xmlRoot $svc -xmlElementName "protocol" -xmlElementText $item.ToUpper() - write-debug "$($MyInvocation.MyCommand.Name) : Building protocol service node for $($item)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building protocol service node for $($item)" } # or its either an XML object, or a collection of objects (already verified as XML objects through validation script) else { Add-XmlElement -xmlRoot $Application -xmlElementName "applicationId" -xmlElementText $item.objectId - write-debug "$($MyInvocation.MyCommand.Name) : Building application service node for $($item.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building application service node for $($item.name)" } } } @@ -27708,17 +27877,17 @@ function New-NsxAppliedToListNode { #$xmlRoot.appendChild($xmlReturn) | out-null foreach ($item in $itemlist) { - write-debug "$($MyInvocation.MyCommand.Name) : Building appliedTo node for $($item.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Building appliedTo node for $($item.name)" #Build the return XML element [System.XML.XMLElement]$xmlItem = $XMLDoc.CreateElement("appliedTo") if ( $item -is [system.xml.xmlelement] ) { - write-debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is specified as xml element" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is specified as xml element" - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $item -Query 'descendant::edgeSummary')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $item -query 'descendant::edgeSummary')) { - write-debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is an edge object" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is an edge object" if ( $ApplyToAllEdges ) { #Apply to all edges is default off, so this means the user asked for something stupid @@ -27748,17 +27917,17 @@ function New-NsxAppliedToListNode { #Something specific passed in applied to list, turn off Apply to DFW. $ApplyToDFW = $false - write-debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is specified as supported powercli object" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is specified as supported powercli object" #Proper PowerCLI Object passed #If passed object is a NIC, we have to do some more digging if ( $item -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { - write-debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is vNic" + Write-Debug "$($MyInvocation.MyCommand.Name) : Object $($item.name) is vNic" #Naming based on DFW UI standard Add-XmlElement -xmlRoot $xmlItem -xmlElementName "name" -xmlElementText "$($item.parent.name) - $($item.name)" Add-XmlElement -xmlRoot $xmlItem -xmlElementName "type" -xmlElementText "Vnic" - $vmUuid = ($item.parent | get-view).config.instanceuuid + $vmUuid = ($item.parent | Get-View).config.instanceuuid $MemberMoref = "$vmUuid.$($item.id.substring($item.id.length-3))" Add-XmlElement -xmlRoot $xmlItem -xmlElementName "value" -xmlElementText $MemberMoref } @@ -27770,13 +27939,13 @@ function New-NsxAppliedToListNode { } } - $xmlReturn.appendChild($xmlItem) | out-null + $xmlReturn.appendChild($xmlItem) | Out-Null } if ( $ApplyToDFW ) { [System.XML.XMLElement]$xmlAppliedTo = $XMLDoc.CreateElement("appliedTo") - $xmlReturn.appendChild($xmlAppliedTo) | out-null + $xmlReturn.appendChild($xmlAppliedTo) | Out-Null Add-XmlElement -xmlRoot $xmlAppliedTo -xmlElementName "name" -xmlElementText "DISTRIBUTED_FIREWALL" Add-XmlElement -xmlRoot $xmlAppliedTo -xmlElementName "type" -xmlElementText "DISTRIBUTED_FIREWALL" Add-XmlElement -xmlRoot $xmlAppliedTo -xmlElementName "value" -xmlElementText "DISTRIBUTED_FIREWALL" @@ -27785,7 +27954,7 @@ function New-NsxAppliedToListNode { if ( $ApplyToAllEdges ) { [System.XML.XMLElement]$xmlAppliedTo = $XMLDoc.CreateElement("appliedTo") - $xmlReturn.appendChild($xmlAppliedTo) | out-null + $xmlReturn.appendChild($xmlAppliedTo) | Out-Null Add-XmlElement -xmlRoot $xmlAppliedTo -xmlElementName "name" -xmlElementText "ALL_EDGES" Add-XmlElement -xmlRoot $xmlAppliedTo -xmlElementName "type" -xmlElementText "ALL_EDGES" Add-XmlElement -xmlRoot $xmlAppliedTo -xmlElementName "value" -xmlElementText "ALL_EDGES" @@ -27813,23 +27982,23 @@ function Get-NsxFirewallSection { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$false,ParameterSetName="ObjectId")] - [string]$objectId, - [Parameter (Mandatory=$false)] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false,Position=1,ParameterSetName="Name")] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateSet("layer3sections","layer2sections","layer3redirectsections",ignorecase=$false)] - [string]$sectionType="layer3sections", - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + [string]$objectId, + [Parameter (Mandatory = $false)] + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Name")] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateSet("layer3sections", "layer2sections", "layer3redirectsections", ignorecase = $false)] + [string]$sectionType = "layer3sections", + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -27843,13 +28012,14 @@ function Get-NsxFirewallSection { #All Sections $URI = "/api/4.0/firewall/$scopeID/config" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $return = $response.firewallConfiguration.$sectiontype.section if ($name) { - $return | where-object {$_.name -eq $name} - }else { + $return | Where-Object { $_.name -eq $name } + } + else { $return } @@ -27858,7 +28028,7 @@ function Get-NsxFirewallSection { else { $URI = "/api/4.0/firewall/$scopeID/config/$sectionType/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $response.section } @@ -27932,40 +28102,41 @@ function New-NsxFirewallSection { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateSet("layer3sections","layer2sections","layer3redirectsections",ignorecase=$false)] - [string]$sectionType="layer3sections", - [Parameter (Mandatory=$false)] - [ValidateScript({ + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateSet("layer3sections", "layer2sections", "layer3redirectsections", ignorecase = $false)] + [string]$sectionType = "layer3sections", + [Parameter (Mandatory = $false)] + [ValidateScript( { if ($_ -match "^globalroot-0$|^edge-\d+$") { $True - } else { + } + else { Throw "$_ is not a valid scope. Valid options are: globalroot-0 | edge-id" } })] - [string]$scopeId="globalroot-0", - [Parameter (Mandatory=$false)] - #Marks the firewall section to be universal or not - [switch]$Universal, - [Parameter (Mandatory=$false)] - #Identifies where to insert the newly created section. after & before must specify an existing section id as the anchor. - [ValidateSet("top","bottom","after","before",ignorecase=$false)] - [string]$position="top", - [Parameter (Mandatory=$False)] - #ID of an existing section to use as an anchor for the new section. - [ValidateNotNullOrEmpty()] - [string]$anchorId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [string]$scopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + #Marks the firewall section to be universal or not + [switch]$Universal, + [Parameter (Mandatory = $false)] + #Identifies where to insert the newly created section. after & before must specify an existing section id as the anchor. + [ValidateSet("top", "bottom", "after", "before", ignorecase = $false)] + [string]$position = "top", + [Parameter (Mandatory = $False)] + #ID of an existing section to use as an anchor for the new section. + [ValidateNotNullOrEmpty()] + [string]$anchorId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - $requiresAnchor = @("before","after") + $requiresAnchor = @("before", "after") if (( $requiresAnchor -contains $position ) -AND (-not ($PSBoundParameters.ContainsKey("anchorID")) ) ) { throw "An anchor ID must be supplied when specifying insert_before or insert_after as the operation" @@ -27980,22 +28151,22 @@ function New-NsxFirewallSection { #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("section") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null #Mandatory Fields Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name #Optional Fields if ($Universal) { - #Create XML for universal object - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "managedBy" -xmlElementText "universalroot-0" + #Create XML for universal object + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "managedBy" -xmlElementText "universalroot-0" } #Do the post $body = $xmlroot.OuterXml switch ($position) { - {$requiresAnchor -contains $position} { + { $requiresAnchor -contains $position } { $URI = "/api/4.0/firewall/$($scopeId.ToLower())/config/$sectionType`?operation=$(ConvertTo-NsxApiSectionOperation $position)`&anchorId=$anchorId" } "bottom" { @@ -28006,7 +28177,7 @@ function New-NsxFirewallSection { } } - $response = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection $response.section @@ -28034,21 +28205,21 @@ function Remove-NsxFirewallSection { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNull()] - [System.Xml.XmlElement]$Section, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNull()] + [System.Xml.XmlElement]$Section, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -28058,7 +28229,7 @@ function Remove-NsxFirewallSection { process { if ( $confirm ) { - $message = "Firewall Section removal is permanent and cannot be reversed." + $message = "Firewall Section removal is permanent and cannot be reversed." $question = "Proceed with removal of Section $($Section.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -28070,13 +28241,13 @@ function Remove-NsxFirewallSection { else { $decision = 0 } if ($decision -eq 0) { if ( $Section.Name -match 'Default Section' ) { - write-warning "Will not delete $($Section.Name)." + Write-Warning "Will not delete $($Section.Name)." } else { #Changed to avoid need for traversal to parent XML node to determine section type which fails in some scenarios. switch ( $Section.Type) { - "LAYER3" { $sectiontype = "layer3sections" } + "LAYER3" { $sectiontype = "layer3sections" } "LAYER2" { $Sectiontype = "layer2sections" } "L3REDIRECT" { $sectiontype = "layer3redirectsections" } } @@ -28086,7 +28257,7 @@ function Remove-NsxFirewallSection { } else { - if ( $section | get-member -MemberType Properties -Name rule ) { + if ( $section | Get-Member -MemberType Properties -Name rule ) { throw "Section $($section.name) contains rules. Specify -force to delete this section" } else { @@ -28094,9 +28265,9 @@ function Remove-NsxFirewallSection { } } - Write-Progress -activity "Remove Section $($Section.Name)" - $null = invoke-NsxWebRequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Section $($Section.Name)" -completed + Write-Progress -Activity "Remove Section $($Section.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Section $($Section.Name)" -Completed } } } @@ -28128,42 +28299,42 @@ function Get-NsxFirewallRule { #> - [CmdletBinding(DefaultParameterSetName="Filter")] + [CmdletBinding(DefaultParameterSetName = "Filter")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Section")] - [ValidateNotNull()] - [System.Xml.XmlElement]$Section, - [Parameter (Mandatory=$false, Position=1, ParameterSetName="Filter")] - [Parameter (Mandatory=$false, Position=1, ParameterSetName="Section")] - [ValidateNotNullorEmpty()] - [string]$Name, - [Parameter (Mandatory=$true,ParameterSetName="RuleId")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Section")] + [ValidateNotNull()] + [System.Xml.XmlElement]$Section, + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Filter")] + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Section")] + [ValidateNotNullorEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "RuleId")] + [ValidateNotNullOrEmpty()] + [string]$RuleId, + [Parameter (Mandatory = $false)] + [string]$ScopeId = "globalroot-0", + [Parameter (Mandatory = $false, ParameterSetName = "Section")] + [Parameter (Mandatory = $false, ParameterSetName = "RuleId")] + [ValidateSet("layer3sections", "layer2sections", "layer3redirectsections", ignorecase = $false)] + [string]$RuleType = "layer3sections", + [Parameter (Mandatory = $False, ParameterSetName = "Filter")] + [ValidateScript( { ValidateFwSourceDestFilter $_ })] + [object]$Source, + [Parameter (Mandatory = $False, ParameterSetName = "Filter")] + [ValidateScript( { ValidateFwSourceDestFilter $_ })] + [object]$Destination, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object [ValidateNotNullOrEmpty()] - [string]$RuleId, - [Parameter (Mandatory=$false)] - [string]$ScopeId="globalroot-0", - [Parameter (Mandatory=$false,ParameterSetName="Section")] - [Parameter (Mandatory=$false,ParameterSetName="RuleId")] - [ValidateSet("layer3sections","layer2sections","layer3redirectsections",ignorecase=$false)] - [string]$RuleType="layer3sections", - [Parameter (Mandatory=$False,ParameterSetName="Filter")] - [ValidateScript({ ValidateFwSourceDestFilter $_ })] - [object]$Source, - [Parameter (Mandatory=$False,ParameterSetName="Filter")] - [ValidateScript({ ValidateFwSourceDestFilter $_ })] - [object]$Destination, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - if ( ( $PSCmdlet.ParameterSetName -eq "Section" ) -and $PSBoundParameters.ContainsKey('RuleType') ){ - write-warning "The -RuleType parameter is no longer required (and will be ignored) when passing a section along the pipeline. This will be deprecated and removed in a future release." + if ( ( $PSCmdlet.ParameterSetName -eq "Section" ) -and $PSBoundParameters.ContainsKey('RuleType') ) { + Write-Warning "The -RuleType parameter is no longer required (and will be ignored) when passing a section along the pipeline. This will be deprecated and removed in a future release." } } @@ -28173,11 +28344,11 @@ function Get-NsxFirewallRule { $URI = "/api/4.0/firewall/$scopeID/config/$(ConvertTo-NsxApiSectionType $section.type)/$($Section.Id)" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( $response | get-member -name Section -Membertype Properties){ - if ( $response.Section | get-member -name Rule -Membertype Properties ){ + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( $response | Get-Member -Name Section -MemberType Properties) { + if ( $response.Section | Get-Member -Name Rule -MemberType Properties ) { if ( $PsBoundParameters.ContainsKey("Name") ) { - $response.section.rule | where-object { $_.name -eq $Name } + $response.section.rule | Where-Object { $_.name -eq $Name } } else { $response.section.rule @@ -28185,10 +28356,10 @@ function Get-NsxFirewallRule { } } } - elseif ( $PSCmdlet.ParameterSetName -eq "Filter" ) { + elseif ( $PSCmdlet.ParameterSetName -eq "Filter" ) { Switch ( $Source ) { - { $_ -as [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]} { + { $_ -as [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop] } { $SourceString = $_.id -replace "virtualmachine-" } default { @@ -28197,7 +28368,7 @@ function Get-NsxFirewallRule { } } Switch ( $Destination ) { - { $_ -as [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]} { + { $_ -as [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop] } { $DestinationString = $_.id -replace "virtualmachine-" } default { @@ -28207,8 +28378,8 @@ function Get-NsxFirewallRule { } $URI = "/api/4.0/firewall/$ScopeId/config?ruleType=LAYER3&source=$SourceString&destination=$DestinationString&name=$Name" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( Invoke-XpathQuery -QueryMethod SelectSingleNode -query "descendant::filteredfirewallConfiguration/layer3Sections/section/rule" -Node $response ){ + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( Invoke-XpathQuery -QueryMethod SelectSingleNode -query "descendant::filteredfirewallConfiguration/layer3Sections/section/rule" -Node $response ) { $response.filteredfirewallConfiguration.layer3Sections.Section.rule } } @@ -28230,34 +28401,34 @@ function Get-NsxFirewallRule { #for a query such as we are doing here is now called #'filteredfirewallConfiguration'. Why? :| - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ( $response | get-member -name firewallConfiguration -MemberType Properties ){ + if ( $response | Get-Member -Name firewallConfiguration -MemberType Properties ) { if ( $PsBoundParameters.ContainsKey("Name") ) { - $response.firewallConfiguration.layer3Sections.Section.rule | where-object { $_.name -eq $Name } + $response.firewallConfiguration.layer3Sections.Section.rule | Where-Object { $_.name -eq $Name } } else { $response.firewallConfiguration.layer3Sections.Section.rule } } - elseif ( $response | get-member -name filteredfirewallConfiguration -MemberType Properties ){ + elseif ( $response | Get-Member -Name filteredfirewallConfiguration -MemberType Properties ) { if ( $PsBoundParameters.ContainsKey("Name") ) { - $response.filteredfirewallConfiguration.layer3Sections.Section.rule | where-object { $_.name -eq $Name } + $response.filteredfirewallConfiguration.layer3Sections.Section.rule | Where-Object { $_.name -eq $Name } } else { $response.filteredfirewallConfiguration.layer3Sections.Section.rule } } - else { throw "Invalid response from NSX API. $response"} + else { throw "Invalid response from NSX API. $response" } } } end {} } -function New-NsxFirewallRule { +function New-NsxFirewallRule { <# .SYNOPSIS @@ -28339,95 +28510,95 @@ function New-NsxFirewallRule { #> [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Section")] - # Section in which the new rule should be created - [ValidateNotNull()] - [System.Xml.XmlElement]$Section, - [Parameter (Mandatory=$true)] - # Name of the new rule - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true)] - # Action of the rule - allow, deny or reject. - [ValidateSet("allow","deny","reject")] - [string]$Action, - [Parameter (Mandatory=$false)] - # Direction of traffic to hit the rule - in, out or inout (Default inout) - [ValidateSet("inout","in","out")] - [string]$Direction="inout", - [Parameter (Mandatory=$false)] - # Source(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. - [ValidateScript({ ValidateFirewallRuleSourceDest $_ })] - [object[]]$Source, - [Parameter (Mandatory=$false)] - # Negate the list of sources hit by the rule - [ValidateNotNullOrEmpty()] - [switch]$NegateSource, - [Parameter (Mandatory=$false)] - # Destination(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. - [ValidateScript({ ValidateFirewallRuleSourceDest $_ })] - [object[]]$Destination, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [switch]$NegateDestination, - [Parameter (Mandatory=$false)] - # Negate the list of destinations hit by the rule - [ValidateScript ({ ValidateFirewallRuleService $_ })] - [object[]]$Service, - [Parameter (Mandatory=$false)] - # Comment string for the new rule - [string]$Comment="", - [Parameter (Mandatory=$false)] - # Rule is created as disabled - [switch]$Disabled, - [Parameter (Mandatory=$false)] - # Rule logging is enabled - [switch]$EnableLogging, - [Parameter (Mandatory=$false)] - # Specific Object(s) to which the rule will be applied. - [ValidateScript({ ValidateFirewallAppliedTo $_ })] - [object[]]$AppliedTo, - [Parameter (Mandatory=$false)] - # Enable application of the rule to 'DISTRIBUTED_FIREWALL' (ie, to all VNICs present on NSX prepared hypervisors. This does NOT include NSX Edges) - [switch]$ApplyToDfw=$true, - [Parameter (Mandatory=$false)] - # Enable application of the rule to all NSX edges - [switch]$ApplyToAllEdges=$false, - [Parameter (Mandatory=$false)] - # Rule type - [ValidateSet("layer3sections","layer2sections","layer3redirectsections",ignorecase=$false)] - [string]$RuleType="layer3sections", - [Parameter (Mandatory=$false)] - # Create the new rule at the specified position of the section (Top or Bottom, Default - Top) - [ValidateSet("Top","Bottom","before","after")] - [string]$Position="Top", - [Parameter (Mandatory=$False)] - #ID of an existing rule to use as an anchor for the new rule. - [ValidateNotNullOrEmpty()] - [string]$anchorId, - [Parameter (Mandatory=$false)] - # Tag to be configured on the new rule. Tag is an arbitrary string attached to the rule that does not affect application of the rule, but is included in logged output of rule hits if logging is enabled for the rule. - [ValidateNotNullorEmpty()] - [string]$Tag, - [Parameter (Mandatory=$false)] - # Scope of the created rule. - [string]$ScopeId="globalroot-0", - [Parameter (Mandatory=$false)] - # Specifies that New-NsxFirewall rule will return the actual rule that was created rather than the deprecated behaviour of returning the complete containing section - # This option exists to allow existing scripts that use this function to be easily updated to set it to $false and continue working (For now!). - # This option is deprecated and will be removed in a future version. - [switch]$ReturnRule=$true, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Section")] + # Section in which the new rule should be created + [ValidateNotNull()] + [System.Xml.XmlElement]$Section, + [Parameter (Mandatory = $true)] + # Name of the new rule + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true)] + # Action of the rule - allow, deny or reject. + [ValidateSet("allow", "deny", "reject")] + [string]$Action, + [Parameter (Mandatory = $false)] + # Direction of traffic to hit the rule - in, out or inout (Default inout) + [ValidateSet("inout", "in", "out")] + [string]$Direction = "inout", + [Parameter (Mandatory = $false)] + # Source(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. + [ValidateScript( { ValidateFirewallRuleSourceDest $_ })] + [object[]]$Source, + [Parameter (Mandatory = $false)] + # Negate the list of sources hit by the rule + [ValidateNotNullOrEmpty()] + [switch]$NegateSource, + [Parameter (Mandatory = $false)] + # Destination(s) of traffic to hit the rule. IP4/6 members are specified as string, any other member as the appropriate VI or PowerNSX object. + [ValidateScript( { ValidateFirewallRuleSourceDest $_ })] + [object[]]$Destination, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [switch]$NegateDestination, + [Parameter (Mandatory = $false)] + # Negate the list of destinations hit by the rule + [ValidateScript ( { ValidateFirewallRuleService $_ })] + [object[]]$Service, + [Parameter (Mandatory = $false)] + # Comment string for the new rule + [string]$Comment = "", + [Parameter (Mandatory = $false)] + # Rule is created as disabled + [switch]$Disabled, + [Parameter (Mandatory = $false)] + # Rule logging is enabled + [switch]$EnableLogging, + [Parameter (Mandatory = $false)] + # Specific Object(s) to which the rule will be applied. + [ValidateScript( { ValidateFirewallAppliedTo $_ })] + [object[]]$AppliedTo, + [Parameter (Mandatory = $false)] + # Enable application of the rule to 'DISTRIBUTED_FIREWALL' (ie, to all VNICs present on NSX prepared hypervisors. This does NOT include NSX Edges) + [switch]$ApplyToDfw = $true, + [Parameter (Mandatory = $false)] + # Enable application of the rule to all NSX edges + [switch]$ApplyToAllEdges = $false, + [Parameter (Mandatory = $false)] + # Rule type + [ValidateSet("layer3sections", "layer2sections", "layer3redirectsections", ignorecase = $false)] + [string]$RuleType = "layer3sections", + [Parameter (Mandatory = $false)] + # Create the new rule at the specified position of the section (Top or Bottom, Default - Top) + [ValidateSet("Top", "Bottom", "before", "after")] + [string]$Position = "Top", + [Parameter (Mandatory = $False)] + #ID of an existing rule to use as an anchor for the new rule. + [ValidateNotNullOrEmpty()] + [string]$anchorId, + [Parameter (Mandatory = $false)] + # Tag to be configured on the new rule. Tag is an arbitrary string attached to the rule that does not affect application of the rule, but is included in logged output of rule hits if logging is enabled for the rule. + [ValidateNotNullorEmpty()] + [string]$Tag, + [Parameter (Mandatory = $false)] + # Scope of the created rule. + [string]$ScopeId = "globalroot-0", + [Parameter (Mandatory = $false)] + # Specifies that New-NsxFirewall rule will return the actual rule that was created rather than the deprecated behaviour of returning the complete containing section + # This option exists to allow existing scripts that use this function to be easily updated to set it to $false and continue working (For now!). + # This option is deprecated and will be removed in a future version. + [switch]$ReturnRule = $true, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { - $requiresAnchor = @("before","after") + $requiresAnchor = @("before", "after") if (( $requiresAnchor -contains $position ) -AND (-not ($PSBoundParameters.ContainsKey("anchorID")) ) ) { throw "An anchor ID must be supplied when specifying before or after as the operation" @@ -28440,17 +28611,17 @@ function New-NsxFirewallRule { # the section and has a node/element of default # and if you try to add a rule below this default rule, the API responds with # a criptic errror msg which can only be decrypted if your a part of the Goa'uld - if ( ($position -eq "bottom") -AND (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Section -Query "child::rule[precedence=`"default`"][last()]") ){ + if ( ($position -eq "bottom") -AND (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Section -query "child::rule[precedence=`"default`"][last()]") ) { throw "Cannot insert rule at the bottom of the section $($section.id) ($($section.name)) as the last rule is a system defined default rule" } $generationNumber = $section.generationNumber - write-debug "$($MyInvocation.MyCommand.Name) : Preparing rule for section $($section.Name) with generationId $generationNumber" + Write-Debug "$($MyInvocation.MyCommand.Name) : Preparing rule for section $($section.Name) with generationId $generationNumber" #Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRule = $XMLDoc.CreateElement("rule") - $xmlDoc.appendChild($xmlRule) | out-null + $xmlDoc.appendChild($xmlRule) | Out-Null Add-XmlElement -xmlRoot $xmlRule -xmlElementName "name" -xmlElementText $Name #Add-XmlElement -xmlRoot $xmlRule -xmlElementName "sectionId" -xmlElementText $($section.Id) @@ -28461,14 +28632,14 @@ function New-NsxFirewallRule { #Enable Logging attribute $xmlAttrLog = $xmlDoc.createAttribute("logged") $xmlAttrLog.value = "true" - $xmlRule.Attributes.Append($xmlAttrLog) | out-null + $xmlRule.Attributes.Append($xmlAttrLog) | Out-Null } if ( $Disabled ) { #Disable (rule) attribute $xmlAttrDisabled = $xmlDoc.createAttribute("disabled") $xmlAttrDisabled.value = "true" - $xmlRule.Attributes.Append($xmlAttrDisabled) | out-null + $xmlRule.Attributes.Append($xmlAttrDisabled) | Out-Null } #Build Sources Node @@ -28492,7 +28663,7 @@ function New-NsxFirewallRule { #Services if ( $service ) { $xmlservices = New-NsxServiceNode -itemType "service" -itemlist $service -xmlDoc $xmlDoc - $xmlRule.appendChild($xmlservices) | out-null + $xmlRule.appendChild($xmlservices) | Out-Null } #Applied To @@ -28502,7 +28673,7 @@ function New-NsxFirewallRule { else { $xmlAppliedToList = New-NsxAppliedToListNode -itemlist $AppliedTo -xmlDoc $xmlDoc -ApplyToDFW:$ApplyToDfw -ApplyToAllEdges:$ApplyToAllEdges } - $xmlRule.appendChild($xmlAppliedToList) | out-null + $xmlRule.appendChild($xmlAppliedToList) | Out-Null #Tag if ( $tag ) { @@ -28510,7 +28681,7 @@ function New-NsxFirewallRule { } #GetThe existing rule Ids and store them - we check for a rule that isnt contained here in the response so we can presnet back to user with rule id - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Section -Query "child::rule") ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Section -query "child::rule") ) { $ExistingIds = @($Section.rule.id) } else { @@ -28522,15 +28693,16 @@ function New-NsxFirewallRule { switch ($Position) { "Top" { $Section.prependchild($xmlRule) | Out-Null } "Bottom" { $Section.appendchild($xmlRule) | Out-Null } - {($_ -eq "before") -or ($_ -eq "after")} { - $anchorRule = Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Section -Query "child::rule[@id=`"$anchorId`"]" + { ($_ -eq "before") -or ($_ -eq "after") } { + $anchorRule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Section -query "child::rule[@id=`"$anchorId`"]" if (-not ($anchorRule)) { throw "Anchor rule id $anchorId does not exist in section $($section.id) ($($section.name))" - } else { + } + else { switch ($Position) { - "before" { $section.insertBefore($xmlrule,$anchorRule) | Out-Null } - "after" { $section.insertAfter($xmlrule,$anchorRule) | Out-Null } - } + "before" { $section.insertBefore($xmlrule, $anchorRule) | Out-Null } + "after" { $section.insertAfter($xmlrule, $anchorRule) | Out-Null } + } } } } @@ -28539,8 +28711,8 @@ function New-NsxFirewallRule { $URI = "/api/4.0/firewall/$scopeId/config/$(ConvertTo-NsxApiSectionType $section.type)/$($section.Id)" #Need the IfMatch header to specify the current section generation id - $IfMatchHeader = @{"If-Match"=$generationNumber} - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -extraheader $IfMatchHeader -connection $connection + $IfMatchHeader = @{"If-Match" = $generationNumber } + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -extraheader $IfMatchHeader -connection $connection try { [system.xml.xmldocument]$content = $response.content @@ -28549,11 +28721,11 @@ function New-NsxFirewallRule { throw "API call to NSX was successful, but was unable to interpret NSX API response as xml." } if ( $ReturnRule ) { - $content.section.rule | where-object { ( -not ($ExistingIds.Contains($_.id))) } + $content.section.rule | Where-Object { ( -not ($ExistingIds.Contains($_.id))) } } else { $content.section - write-warning 'The -ReturnRule:$false option is deprecated and will be removed in a future version. Please update your scripts so that they accept the return object of New-NsxFirewallRule to be the newly created rule rather than the full section.' + Write-Warning 'The -ReturnRule:$false option is deprecated and will be removed in a future version. Please update your scripts so that they accept the return object of New-NsxFirewallRule to be the newly created rule rather than the full section.' } } end {} @@ -28601,27 +28773,27 @@ function Set-NsxFirewallRule { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - # DFW rule as returned by Get-NsxFirewallRule / New-NsxFirewallRule - [ValidateScript({ ValidateFirewallRule $_ })] - [System.Xml.XmlElement]$FirewallRule, - [Parameter (Mandatory=$false)] - [boolean]$disabled, - [Parameter (Mandatory=$false)] - [boolean]$logged, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$name, - [Parameter (Mandatory=$false)] - [ValidateSet("Allow","Deny", "Reject")] - [string]$action, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$comment, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + # DFW rule as returned by Get-NsxFirewallRule / New-NsxFirewallRule + [ValidateScript( { ValidateFirewallRule $_ })] + [System.Xml.XmlElement]$FirewallRule, + [Parameter (Mandatory = $false)] + [boolean]$disabled, + [Parameter (Mandatory = $false)] + [boolean]$logged, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$name, + [Parameter (Mandatory = $false)] + [ValidateSet("Allow", "Deny", "Reject")] + [string]$action, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$comment, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -28653,18 +28825,19 @@ function Set-NsxFirewallRule { if ( $PsBoundParameters.ContainsKey('comment') ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_FirewallRule -Query 'descendant::notes')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_FirewallRule -query 'descendant::notes')) { $_FirewallRule.notes = $comment.ToString() - } else{ - Add-XmlElement -xmlRoot $_FirewallRule -xmlElementName "notes" -xmlElementText $comment.ToString() + } + else { + Add-XmlElement -xmlRoot $_FirewallRule -xmlElementName "notes" -xmlElementText $comment.ToString() } } $uri = "/api/4.0/firewall/globalroot-0/config/layer3sections/$sectionId/rules/$Ruleid" #Need the IfMatch header to specify the current section generation id - $IfMatchHeader = @{"If-Match"=$generationNumber} + $IfMatchHeader = @{"If-Match" = $generationNumber } try { - $response = Invoke-NsxWebRequest -method put -Uri $uri -body $_FirewallRule.OuterXml -extraheader $IfMatchHeader -connection $connection + $response = Invoke-NsxWebRequest -method put -URI $uri -body $_FirewallRule.OuterXml -extraheader $IfMatchHeader -connection $connection [xml]$ruleElem = $response.Content Get-NsxFirewallRule -RuleId $ruleElem.rule.id } @@ -28695,21 +28868,21 @@ function Remove-NsxFirewallRule { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNull()] - [System.Xml.XmlElement]$Rule, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - [switch]$force=$false, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNull()] + [System.Xml.XmlElement]$Rule, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + [switch]$force = $false, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -28719,7 +28892,7 @@ function Remove-NsxFirewallRule { process { if ( $confirm ) { - $message = "Firewall Rule removal is permanent and cannot be reversed." + $message = "Firewall Rule removal is permanent and cannot be reversed." $question = "Proceed with removal of Rule $($Rule.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -28731,14 +28904,14 @@ function Remove-NsxFirewallRule { else { $decision = 0 } if ($decision -eq 0) { - $section = get-nsxFirewallSection $Rule.parentnode.name -connection $connection + $section = Get-NsxFirewallSection $Rule.parentnode.name -Connection $connection $generationNumber = $section.generationNumber - $IfMatchHeader = @{"If-Match"=$generationNumber} + $IfMatchHeader = @{"If-Match" = $generationNumber } $URI = "/api/4.0/firewall/globalroot-0/config/$($Section.ParentNode.name.tolower())/$($Section.Id)/rules/$($Rule.id)" - Write-Progress -activity "Remove Rule $($Rule.Name)" - $null = invoke-NsxWebRequest -method "delete" -uri $URI -extraheader $IfMatchHeader -connection $connection - write-progress -activity "Remove Rule $($Rule.Name)" -completed + Write-Progress -Activity "Remove Rule $($Rule.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -extraheader $IfMatchHeader -connection $connection + Write-Progress -Activity "Remove Rule $($Rule.Name)" -Completed } } @@ -28781,17 +28954,17 @@ function Get-NsxFirewallExclusionListMember { #> param ( - [Parameter (Mandatory=$False)] + [Parameter (Mandatory = $False)] #PowerNSX Connection object [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} - process{ + process { # Build URL and catch response into XML format $URI = "/api/2.1/app/excludelist" - [System.Xml.XmlDocument]$response = invoke-nsxrestmethod -method "GET" -uri $URI -connection $Connection + [System.Xml.XmlDocument]$response = Invoke-NsxRestMethod -method "GET" -URI $URI -connection $Connection # If there are any VMs found, iterate and return them #Martijn - I removed the array build here, as: @@ -28800,11 +28973,11 @@ function Get-NsxFirewallExclusionListMember { #### as opposed to building the array internally where the whole pipeline has to be processed before the user gets any output. #### c) Its also less lines :) - $nodes = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $response -Query 'descendant::VshieldAppConfiguration/excludeListConfiguration/excludeMember') - if ($nodes){ - foreach ($node in $nodes){ + $nodes = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $response -query 'descendant::VshieldAppConfiguration/excludeListConfiguration/excludeMember') + if ($nodes) { + foreach ($node in $nodes) { # output the VI VM object... - Get-VM -Server $Connection.VIConnection -id "VirtualMachine-$($node.member.objectId)" + Get-VM -Server $Connection.VIConnection -Id "VirtualMachine-$($node.member.objectId)" } } } @@ -28845,13 +29018,13 @@ function Add-NsxFirewallExclusionListMember { #> param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullorEmpty()] [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$False)] + [Parameter (Mandatory = $False)] #PowerNSX Connection object [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -28862,14 +29035,14 @@ function Add-NsxFirewallExclusionListMember { $URI = "/api/2.1/app/excludelist/$vmMoid" try { - $null = invoke-nsxrestmethod -method "PUT" -uri $URI -connection $connection + $null = Invoke-NsxRestMethod -method "PUT" -URI $URI -connection $connection } catch { Throw "Unable to add VM $VirtualMachine to Exclusion list. $_" } } - end {} + end {} } function Remove-NsxFirewallExclusionListMember { @@ -28906,13 +29079,13 @@ function Remove-NsxFirewallExclusionListMember { #> param ( - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullorEmpty()] [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VirtualMachine, - [Parameter (Mandatory=$False)] + [Parameter (Mandatory = $False)] #PowerNSX Connection object [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -28923,7 +29096,7 @@ function Remove-NsxFirewallExclusionListMember { $URI = "/api/2.1/app/excludelist/$vmMoid" try { - $null = invoke-NsxWebRequest -method "DELETE" -uri $URI -connection $connection + $null = Invoke-NsxWebRequest -method "DELETE" -URI $URI -connection $connection } catch { Throw "Unable to remove VM $VirtualMachine from Exclusion list. $_" @@ -28935,7 +29108,7 @@ function Remove-NsxFirewallExclusionListMember { function Get-NsxFirewallSavedConfiguration { - <# + <# .SYNOPSIS Retrieves saved Distributed Firewall configuration. @@ -28970,22 +29143,22 @@ function Get-NsxFirewallSavedConfiguration { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$false,ParameterSetName="ObjectId")] - # ID of a saved Distributed Firewall Configuration - [ValidateNotNullOrEmpty()] - [string]$ObjectId, - [Parameter (Mandatory=$false,Position=1,ParameterSetName="Name")] - # Name of a saved Distributed Firewall Configuration - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + # ID of a saved Distributed Firewall Configuration + [ValidateNotNullOrEmpty()] + [string]$ObjectId, + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Name")] + # Name of a saved Distributed Firewall Configuration + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -28999,16 +29172,16 @@ function Get-NsxFirewallSavedConfiguration { # All Sections $URI = "/api/4.0/firewall/globalroot-0/drafts" - [system.xml.xmldocument]$Response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query "child::firewallDrafts/*")){ + [system.xml.xmldocument]$Response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::firewallDrafts/*")) { $Return = $Response - if ($PsBoundParameters.ContainsKey("Name")){ - $namedResults = $Return.firewallDrafts.firewallDraft | where-object {$_.name -eq $Name} + if ($PsBoundParameters.ContainsKey("Name")) { + $namedResults = $Return.firewallDrafts.firewallDraft | Where-Object { $_.name -eq $Name } foreach ($config in $namedResults) { - Get-NsxFirewallSavedConfiguration -ObjectId $config.id -connection $connection + Get-NsxFirewallSavedConfiguration -ObjectId $config.id -Connection $connection } } else { @@ -29019,9 +29192,9 @@ function Get-NsxFirewallSavedConfiguration { else { $URI = "/api/4.0/firewall/globalroot-0/drafts/$ObjectId" - [system.xml.xmldocument]$Response = Invoke-NsxRestMethod -method "get" -uri $URI -connection $connection + [system.xml.xmldocument]$Response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Response -Query "child::firewallDraft")){ + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Response -query "child::firewallDraft")) { $Response.firewallDraft } } @@ -29031,7 +29204,7 @@ function Get-NsxFirewallSavedConfiguration { function New-NsxFirewallSavedConfiguration { - <# + <# .SYNOPSIS Creates a manually saved Distributed Firewall configuration. @@ -29056,77 +29229,78 @@ function New-NsxFirewallSavedConfiguration { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,Position=1)] - # Name to call the saved configuration - [string]$Name, - [Parameter (Mandatory=$false)] - # A meaningful description for the saved configuration - [string]$Description, - [Parameter (Mandatory=$false)] - # Specifies whether to preserve the saved configuration to prevent it being deleted automatically. Default = $True - [switch]$Preserve=$true, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, Position = 1)] + # Name to call the saved configuration + [string]$Name, + [Parameter (Mandatory = $false)] + # A meaningful description for the saved configuration + [string]$Description, + [Parameter (Mandatory = $false)] + # Specifies whether to preserve the saved configuration to prevent it being deleted automatically. Default = $True + [switch]$Preserve = $true, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} - process{ + process { # Create the XMLRoot [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlRoot = $XMLDoc.CreateElement("firewallDraft") # Set the name attribute - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null $xmlAttrName = $xmlDoc.createAttribute("name") $xmlAttrName.value = $Name - $xmlRoot.Attributes.Append($xmlAttrName) | out-null + $xmlRoot.Attributes.Append($xmlAttrName) | Out-Null Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "preserve" -xmlElementText $Preserve Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "mode" -xmlElementText "userdefined" if ( $PsBoundParameters.ContainsKey("Description") ) { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description - } else { + } + else { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" } #Go and grab the complete firewall configuration to backup $URI = "/api/4.0/firewall/globalroot-0/config" - [system.xml.xmlDocument]$config = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + [system.xml.xmlDocument]$config = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection - if (-not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $config -Query "child::firewallConfiguration")) { + if (-not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $config -query "child::firewallConfiguration")) { throw "Cannot retrieve complete Distributed Firewall configuration." } [System.XML.XMLElement]$xmlConfigNode = $xmlRoot.OwnerDocument.CreateElement("config") - $xmlRoot.AppendChild($xmlConfigNode) | out-null + $xmlRoot.AppendChild($xmlConfigNode) | Out-Null foreach ($node in $config.firewallConfiguration.ChildNodes) { $xmlConfigBackup = $xmlroot.OwnerDocument.ImportNode($node, $true) - $xmlConfigNode.AppendChild($xmlConfigBackup) | out-null + $xmlConfigNode.AppendChild($xmlConfigBackup) | Out-Null } $body = $xmlroot.OuterXml $URI = "/api/4.0/firewall/globalroot-0/drafts" - Write-Progress -activity "Creating firewall saved configuration." - $response = invoke-nsxrestmethod -method "post" -uri $URI -body $body -connection $connection - Write-Progress -activity "Creating firewall saved configuration." -completed + Write-Progress -Activity "Creating firewall saved configuration." + $response = Invoke-NsxRestMethod -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating firewall saved configuration." -Completed - Get-NsxFirewallSavedConfiguration -ObjectId $response.firewalldraft.id -connection $connection + Get-NsxFirewallSavedConfiguration -ObjectId $response.firewalldraft.id -Connection $connection } - end{} + end {} } function Remove-NsxFirewallSavedConfiguration { - <# + <# .SYNOPSIS Removes a saved Distributed Firewall configuration. @@ -29156,28 +29330,28 @@ function Remove-NsxFirewallSavedConfiguration { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - # A valid saved configuration from Get-NsxFirewallSavedConfiguration - [ValidateScript({ ValidateFirewallDraft $_ })] - [System.Xml.XmlElement]$SavedConfig, - [Parameter (Mandatory=$False)] - # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + # A valid saved configuration from Get-NsxFirewallSavedConfiguration + [ValidateScript( { ValidateFirewallDraft $_ })] + [System.Xml.XmlElement]$SavedConfig, + [Parameter (Mandatory = $False)] + # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} - process{ + process { if ( $confirm ) { - $message = "Removal of a saved Distributed Firewall Configuration is permanent." + $message = "Removal of a saved Distributed Firewall Configuration is permanent." $question = "Proceed with removal of Saved Distributed Firewall Configuration ($($SavedConfig.id) - $($SavedConfig.Name))?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -29191,18 +29365,18 @@ function Remove-NsxFirewallSavedConfiguration { if ($decision -eq 0) { $URI = "/api/4.0/firewall/globalroot-0/drafts/$($SavedConfig.id)" - Write-Progress -activity "Remove Saved Distributed Firewall Configuration $($SavedConfig.id) - $($SavedConfig.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Saved Distributed Firewall Configuration $($SavedConfig.id) - $($SavedConfig.Name)" -completed + Write-Progress -Activity "Remove Saved Distributed Firewall Configuration $($SavedConfig.id) - $($SavedConfig.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Saved Distributed Firewall Configuration $($SavedConfig.id) - $($SavedConfig.Name)" -Completed } } - end{} + end {} } function Set-NsxFirewallSavedConfiguration { - <# + <# .SYNOPSIS Update a saved Distributed Firewall configuration. @@ -29234,27 +29408,27 @@ function Set-NsxFirewallSavedConfiguration { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - # A valid saved configuration from Get-NsxFirewallSavedConfiguration - [ValidateScript({ ValidateFirewallSavedConfiguration $_ })] - [System.Xml.XmlElement]$SavedConfig, - [Parameter (Mandatory=$False)] - # Specifies whether to preserve the saved configuration to prevent it being deleted automatically. Default = $True - [switch]$Preserve, - [Parameter (Mandatory=$False)] - # Name to call the saved configuration - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$False)] - # A meaningful description for the saved configuration - [string]$Description, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + # A valid saved configuration from Get-NsxFirewallSavedConfiguration + [ValidateScript( { ValidateFirewallSavedConfiguration $_ })] + [System.Xml.XmlElement]$SavedConfig, + [Parameter (Mandatory = $False)] + # Specifies whether to preserve the saved configuration to prevent it being deleted automatically. Default = $True + [switch]$Preserve, + [Parameter (Mandatory = $False)] + # Name to call the saved configuration + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $False)] + # A meaningful description for the saved configuration + [string]$Description, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -29279,9 +29453,9 @@ function Set-NsxFirewallSavedConfiguration { $URI = "/api/4.0/firewall/globalroot-0/drafts/$($SavedConfig.id)" $body = $_SavedConfig.OuterXml - $null = Invoke-NsxRestMethod -method "put" -uri $URI -body $body -connection $connection + $null = Invoke-NsxRestMethod -method "put" -URI $URI -body $body -connection $connection - Get-NsxFirewallSavedConfiguration -ObjectId $SavedConfig.id -connection $connection + Get-NsxFirewallSavedConfiguration -ObjectId $SavedConfig.id -Connection $connection } @@ -29313,10 +29487,10 @@ function Get-NsxFirewallThreshold { #> param ( - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -29327,19 +29501,19 @@ function Get-NsxFirewallThreshold { $URI = "/api/4.0/firewall/stats/eventthresholds" try { - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection [system.xml.xmldocument]$Content = $response.content } catch { Throw "Unexpected API response $_" } - if ( Invoke-XPathQuery -Node $content -QueryMethod SelectSingleNode -query "child::eventThresholds" ){ + if ( Invoke-XpathQuery -Node $content -QueryMethod SelectSingleNode -query "child::eventThresholds" ) { $Content.eventThresholds } } - end{} + end {} } function Set-NsxFirewallThreshold { @@ -29368,19 +29542,19 @@ function Set-NsxFirewallThreshold { param ( - [Parameter (Mandatory=$false)] - [ValidateRange(1,100)] - [int]$Memory, - [Parameter (Mandatory=$false)] - [ValidateRange(1,100)] - [int]$Cpu, - [Parameter (Mandatory=$false)] - [ValidateRange(1,500000)] - [int]$ConnectionsPerSecond, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + [ValidateRange(1, 100)] + [int]$Memory, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 100)] + [int]$Cpu, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 500000)] + [int]$ConnectionsPerSecond, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -29388,14 +29562,14 @@ function Set-NsxFirewallThreshold { process { #Capture existing thresholds - $currentthreshold = Get-NsxFirewallThreshold + $currentthreshold = Get-NsxFirewallThreshold #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. # Must convert all ToString due to Windows issues. macOS and Linux are fine without. if ( $PsBoundParameters.ContainsKey('Cpu') ) { - $currentthreshold.cpu.percentValue = $Cpu.ToString() + $currentthreshold.cpu.percentValue = $Cpu.ToString() } if ( $PsBoundParameters.ContainsKey('Memory') ) { $currentthreshold.memory.percentValue = $Memory.ToString() @@ -29406,7 +29580,7 @@ function Set-NsxFirewallThreshold { $uri = "/api/4.0/firewall/stats/eventthresholds" $body = $currentthreshold.outerXml - Invoke-NsxWebRequest -method "PUT" -URI $uri -body $body | out-null + Invoke-NsxWebRequest -method "PUT" -URI $uri -body $body | Out-Null Get-NsxFirewallThreshold } @@ -29515,29 +29689,29 @@ function Get-NsxFirewallRuleMember { #> - [CmdletBinding(DefaultParameterSetName="Default")] + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - # DFW rule as returned by Get-NsxFirewallRule / New-NsxFirewallRule - [ValidateScript({ ValidateFirewallRule $_ })] - [System.Xml.XmlElement]$FirewallRule, - [Parameter (Mandatory=$false, Position=1)] - # Member(s) to return. Can specify as a string or VI / NSX Object (VM, Logical Switch etc)). String match is processed as regex (eg: web\d{2} is supported) - [ValidateScript({ ValidateFirewallRuleMember $_ })] - [object[]]$Member=".*", - [Parameter (Mandatory=$false)] - # MemberType to return. Source, Destination or All (Default) - [ValidateSet("Source","Destination", "All")] - [string]$MemberType="All" + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + # DFW rule as returned by Get-NsxFirewallRule / New-NsxFirewallRule + [ValidateScript( { ValidateFirewallRule $_ })] + [System.Xml.XmlElement]$FirewallRule, + [Parameter (Mandatory = $false, Position = 1)] + # Member(s) to return. Can specify as a string or VI / NSX Object (VM, Logical Switch etc)). String match is processed as regex (eg: web\d{2} is supported) + [ValidateScript( { ValidateFirewallRuleMember $_ })] + [object[]]$Member = ".*", + [Parameter (Mandatory = $false)] + # MemberType to return. Source, Destination or All (Default) + [ValidateSet("Source", "Destination", "All")] + [string]$MemberType = "All" ) begin {} process { - write-debug "$($MyInvocation.MyCommand.Name) : Rule $($FirewallRule.id)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule $($FirewallRule.id)" foreach ( $_Member in $Member ) { if ( $_Member -is [string] ) { if ( $Membertype -match "Source|All" ) { @@ -29623,7 +29797,7 @@ function Get-NsxFirewallRuleMember { if ( $Membertype -match "Source|All" ) { if ( Invoke-XpathQuery -Node $FirewallRule -query "child::sources/source" -QueryMethod SelectSingleNode ) { foreach ($source in $FirewallRule.Sources.Source ) { - if (( $source.type -notmatch "ipv4Address|ipv6Address" ) -and ( $source.value -match $_Member.extensiondata.moref.value )) { + if (( $source.type -notmatch "ipv4Address|ipv6Address" ) -and ( $source.value -match $_Member.extensiondata.moref.value )) { [pscustomobject]@{"RuleId" = $FirewallRule.id; "SectionId" = $FirewallRule.SectionId; "MemberType" = "Source"; "Name" = $source.Name; "Value" = $source.Value; "Type" = $source.Type; "isValid" = $source.isValid } } } @@ -29632,7 +29806,7 @@ function Get-NsxFirewallRuleMember { if ( $Membertype -match "Destination|All" ) { if ( Invoke-XpathQuery -Node $FirewallRule -query "child::destinations/destination" -QueryMethod SelectSingleNode ) { foreach ($destination in $FirewallRule.Destinations.Destination ) { - if (( $destination.type -notmatch "ipv4Address|ipv6Address" ) -and ( $destination.value -match $_Member.extensiondata.moref.value )) { + if (( $destination.type -notmatch "ipv4Address|ipv6Address" ) -and ( $destination.value -match $_Member.extensiondata.moref.value )) { [pscustomobject]@{"RuleId" = $FirewallRule.id; "SectionId" = $FirewallRule.SectionId; "MemberType" = "Destination"; "Name" = $Destination.Name; "Value" = $Destination.Value; "Type" = $Destination.Type; "isValid" = $Destination.isValid } } } @@ -29701,26 +29875,26 @@ function Add-NsxFirewallRuleMember { #> - [CmdletBinding(DefaultParameterSetName="Default")] + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - # DFW rule as returned by Get-NsxFirewallRule / New-NsxFirewallRule - [ValidateScript({ ValidateFirewallRule $_ })] - [System.Xml.XmlElement]$FirewallRule, - [Parameter (Mandatory=$True, Position=1)] - # Member(s) to add. specify ipv4/6 addresses as a string or other member types as VI / NSX Object (VM, Logical Switch etc)). - [ValidateScript({ ValidateFirewallRuleSourceDest $_ })] - [object[]]$Member, - [Parameter (Mandatory=$true)] - # MemberType to add. Source, Destination or Both - [ValidateSet("Source","Destination", "Both")] - [string]$MemberType, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + # DFW rule as returned by Get-NsxFirewallRule / New-NsxFirewallRule + [ValidateScript( { ValidateFirewallRule $_ })] + [System.Xml.XmlElement]$FirewallRule, + [Parameter (Mandatory = $True, Position = 1)] + # Member(s) to add. specify ipv4/6 addresses as a string or other member types as VI / NSX Object (VM, Logical Switch etc)). + [ValidateScript( { ValidateFirewallRuleSourceDest $_ })] + [object[]]$Member, + [Parameter (Mandatory = $true)] + # MemberType to add. Source, Destination or Both + [ValidateSet("Source", "Destination", "Both")] + [string]$MemberType, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -29736,11 +29910,11 @@ function Add-NsxFirewallRuleMember { if ( $MemberType -eq "Both" ) { # We are defaulting negation to false here as negation applied to ALL members. If we allow user to specify in this cmdlet, then we have to catch the scenario where the rule has existing sources (and we shouldnt override the existing negation setting). Prefer to require user to explicitly use separate set-nsxfirewallrule -negatesource / -negatedestination? - if ( -not ( invoke-xpathquery -QueryMethod SelectSingleNode -query "child::sources" -node $_FirewallRule)) { + if ( -not ( Invoke-XpathQuery -QueryMethod SelectSingleNode -query "child::sources" -Node $_FirewallRule)) { Add-NsxSourceDestNode -Rule $_FirewallRule -Nodetype "sources" -negated:$false } - if ( -not ( invoke-xpathquery -QueryMethod SelectSingleNode -query "child::destinations" -node $_FirewallRule)) { + if ( -not ( Invoke-XpathQuery -QueryMethod SelectSingleNode -query "child::destinations" -Node $_FirewallRule)) { Add-NsxSourceDestNode -Rule $_FirewallRule -Nodetype "destinations" -negated:$false } @@ -29748,7 +29922,7 @@ function Add-NsxFirewallRuleMember { Add-NsxSourceDestMember -membertype "destination" -memberlist $member -rule $_FirewallRule } else { - if ( -not ( invoke-xpathquery -QueryMethod SelectSingleNode -query "child::$($Membertype.ToLower())s" -node $_FirewallRule)) { + if ( -not ( Invoke-XpathQuery -QueryMethod SelectSingleNode -query "child::$($Membertype.ToLower())s" -Node $_FirewallRule)) { Add-NsxSourceDestNode -Rule $_FirewallRule -Nodetype "$($Membertype.ToLower())s" -negated:$false } Add-NsxSourceDestMember -membertype $MemberType.ToLower() -memberlist $member -rule $_FirewallRule @@ -29756,9 +29930,9 @@ function Add-NsxFirewallRuleMember { $uri = "/api/4.0/firewall/globalroot-0/config/layer3sections/$sectionId/rules/$Ruleid" #Need the IfMatch header to specify the current section generation id - $IfMatchHeader = @{"If-Match"=$generationNumber} + $IfMatchHeader = @{"If-Match" = $generationNumber } try { - $response = Invoke-NsxWebRequest -method put -Uri $uri -body $_FirewallRule.OuterXml -extraheader $IfMatchHeader -connection $connection + $response = Invoke-NsxWebRequest -method put -URI $uri -body $_FirewallRule.OuterXml -extraheader $IfMatchHeader -connection $connection [xml]$ruleElem = $response.Content Get-NsxFirewallRule -RuleId $ruleElem.rule.id | Get-NsxFirewallRuleMember } @@ -29837,35 +30011,35 @@ function Remove-NsxFirewallRuleMember { #> - [CmdletBinding(DefaultParameterSetName="Default")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [CmdletBinding(DefaultParameterSetName = "Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - # DFW rule member as returned by Get-NsxFirewallRuleMember - [ValidateScript({ ValidateFirewallRuleMemberObject $_ })] - [Object]$FirewallRuleMember, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #Override confirmation of removal of last source or destination member - effectively converting rule to match ANY in the appropriate field (source or destination). Specify as -SayHello2Heaven to disable confirmation prompt. RIP Chris Cornell, 17 May 2017 - [switch]$SayHello2Heaven=$false, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + # DFW rule member as returned by Get-NsxFirewallRuleMember + [ValidateScript( { ValidateFirewallRuleMemberObject $_ })] + [Object]$FirewallRuleMember, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #Override confirmation of removal of last source or destination member - effectively converting rule to match ANY in the appropriate field (source or destination). Specify as -SayHello2Heaven to disable confirmation prompt. RIP Chris Cornell, 17 May 2017 + [switch]$SayHello2Heaven = $false, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { # We process all member modifications offline as part of pipeline processing, then we put the updated sections to the api in the end{} section to optimise multiple edits to the same rule. # Save modified rules in a hash table keyed by ruleid $ModifiedSections = @{} - } + } process { if ( $confirm ) { - $message = "Removal of a firewall rule member is permanent and will modify your security posture." + $message = "Removal of a firewall rule member is permanent and will modify your security posture." $question = "Proceed with removal of member $($FirewallRuleMember.Value) from the $($FirewallRuleMember.MemberType) list of firewallrule $($FirewallRuleMember.RuleId) in section $($FirewallRuleMember.SectionId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -29886,8 +30060,8 @@ function Remove-NsxFirewallRuleMember { } $Query = "descendant::rule[@id=`"$($FirewallRuleMember.RuleId.ToString())`"]/*/$($FirewallRuleMember.MemberType.ToString().ToLower())[value=`"$($FirewallRuleMember.Value.ToString())`"]" - write-debug "$($MyInvocation.MyCommand.Name) : Executing xpath query to locate member in section: $query" - $XmlMember = Invoke-XpathQuery -QueryMethod SelectNodes -Query $Query -node $SectionXml + Write-Debug "$($MyInvocation.MyCommand.Name) : Executing xpath query to locate member in section: $query" + $XmlMember = Invoke-XpathQuery -QueryMethod SelectNodes -query $Query -Node $SectionXml if ( @($XmlMember).Count -ne 1) { throw "Xpath query for member $($FirewallRuleMember.Name) did not result in exactly one member being returned. $(@($XmlMember).count) members were matched. Please report this issue at https://github.com/vmware/powernsx/issues/ and include steps to reproduce." @@ -29900,13 +30074,13 @@ function Remove-NsxFirewallRuleMember { $ParentNode = $XmlMember.ParentNode $AllChildNodes = Invoke-XpathQuery -Node $ParentNode -QueryMethod SelectNodes -query "child::$($FirewallRuleMember.MemberType.ToString().ToLower())" - if ( @($AllChildNodes).count -eq 1 ) { + if ( @($AllChildNodes).count -eq 1 ) { # We have about to remove the last member from the sources or destinations element. API will reject and empty sources elem, so we need to remove it. # We also should warn the user that this just became an any rule! # Also - when Im doing this 'get my parent and call its removechild method to remove myself' kinda circular operation, it always reminds me of the Lorax lifting himself by the seat of his pants and disappearing... if ( -not $SayHello2Heaven ) { - $message = "The $($FirewallRuleMember.MemberType.ToLower()) member $($FirewallRuleMember.Value) of rule $($FirewallRuleMember.RuleId) in section $($FirewallRuleMember.SectionId) is the last $($FirewallRuleMember.MemberType.ToLower()) member in this rule. Its removal will cause this rule to match ANY $($FirewallRuleMember.MemberType)" + $message = "The $($FirewallRuleMember.MemberType.ToLower()) member $($FirewallRuleMember.Value) of rule $($FirewallRuleMember.RuleId) in section $($FirewallRuleMember.SectionId) is the last $($FirewallRuleMember.MemberType.ToLower()) member in this rule. Its removal will cause this rule to match ANY $($FirewallRuleMember.MemberType)" $question = "Confirm rule $($FirewallRuleMember.RuleId) to match $($FirewallRuleMember.MemberType) ANY?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -29916,13 +30090,13 @@ function Remove-NsxFirewallRuleMember { else { $decision = 0 } if ( $decision -eq 0 ) { - write-warning "The $($FirewallRuleMember.MemberType.ToLower()) member $($FirewallRuleMember.Value) of rule $($FirewallRuleMember.RuleId) in section $($FirewallRuleMember.SectionId) was the last member in this rule. Its removal has caused this rule to now match ANY $($FirewallRuleMember.MemberType)." - $ParentNode.RemoveChild($XmlMember) | out-null - $ParentNode.ParentNode.RemoveChild($ParentNode) | out-null + Write-Warning "The $($FirewallRuleMember.MemberType.ToLower()) member $($FirewallRuleMember.Value) of rule $($FirewallRuleMember.RuleId) in section $($FirewallRuleMember.SectionId) was the last member in this rule. Its removal has caused this rule to now match ANY $($FirewallRuleMember.MemberType)." + $ParentNode.RemoveChild($XmlMember) | Out-Null + $ParentNode.ParentNode.RemoveChild($ParentNode) | Out-Null } } else { - $ParentNode.RemoveChild($XmlMember) | out-null + $ParentNode.RemoveChild($XmlMember) | Out-Null } } } @@ -29933,17 +30107,17 @@ function Remove-NsxFirewallRuleMember { foreach ( $Section in $ModifiedSections.Values ) { switch ( $Section.Type ) { - "LAYER3" { $SectionType = "layer3sections"} - "LAYER2" { $SectionType = "layer2sections"} - "L3REDIRECT" { $SectionType = "layer3redirectsections"} + "LAYER3" { $SectionType = "layer3sections" } + "LAYER2" { $SectionType = "layer2sections" } + "L3REDIRECT" { $SectionType = "layer3redirectsections" } } $uri = "/api/4.0/firewall/globalroot-0/config/$SectionType/$($section.Id)" # Need the IfMatch header to specify the current section generation id - $IfMatchHeader = @{"If-Match"=$Section.generationNumber} + $IfMatchHeader = @{"If-Match" = $Section.generationNumber } try { - $response = Invoke-NsxWebRequest -method put -Uri $uri -body $Section.outerxml -extraheader $IfMatchHeader -connection $connection + $response = Invoke-NsxWebRequest -method put -URI $uri -body $Section.outerxml -extraheader $IfMatchHeader -connection $connection [xml]$Section = $response.Content } catch { @@ -29977,10 +30151,10 @@ function Get-NsxFirewallGlobalConfiguration { #> param ( - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -29989,19 +30163,19 @@ function Get-NsxFirewallGlobalConfiguration { process { $URI = "/api/4.0/firewall/config/globalconfiguration" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection try { [system.xml.xmldocument]$globalConfigurationDoc = $response.content $globalConfigurationDoc.globalConfiguration - } + } catch { Throw "Unexpected API response $_" } } - end{} + end {} } function Set-NsxFirewallGlobalConfiguration { @@ -30025,22 +30199,22 @@ function Set-NsxFirewallGlobalConfiguration { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateNotNullOrEmpty()] - [System.Xml.XmlElement]$GlobalConfiguration, - [Parameter (Mandatory=$False)] - [switch]$EnableTcpStrict, - [Parameter (Mandatory=$False)] - [switch]$DisableAutoDraft, - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateNotNullOrEmpty()] + [System.Xml.XmlElement]$GlobalConfiguration, + [Parameter (Mandatory = $False)] + [switch]$EnableTcpStrict, + [Parameter (Mandatory = $False)] + [switch]$DisableAutoDraft, + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} - process{ + process { #Capture existing options $_GlobalConfiguration = $GlobalConfiguration.CloneNode($True) @@ -30048,12 +30222,12 @@ function Set-NsxFirewallGlobalConfiguration { #If the user did not specify a given parameter, we dont want to modify from the existing value. if ( $PsBoundParameters.ContainsKey('EnableTcpStrict') ) { - $_GlobalConfiguration.tcpStrictOption = [string]$EnableTcpStrict + $_GlobalConfiguration.tcpStrictOption = [string]$EnableTcpStrict } if ( $PsBoundParameters.ContainsKey('DisableAutoDraft') ) { # Check to see if the element already exists - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_GlobalConfiguration -Query 'descendant::autoDraftDisabled')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_GlobalConfiguration -query 'descendant::autoDraftDisabled')) { $_GlobalConfiguration.autoDraftDisabled = [string]$DisableAutoDraft } else { @@ -30063,7 +30237,7 @@ function Set-NsxFirewallGlobalConfiguration { $uri = "/api/4.0/firewall/config/globalconfiguration" $body = $_GlobalConfiguration.outerXml - Invoke-NsxWebRequest -method "PUT" -URI $uri -body $body | out-null + Invoke-NsxWebRequest -method "PUT" -URI $uri -body $body | Out-Null Get-NsxFirewallGlobalConfiguration @@ -30093,10 +30267,10 @@ function Get-NsxFirewallPublishStatus { #> param ( - [Parameter (Mandatory=$false)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $false)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -30106,15 +30280,15 @@ function Get-NsxFirewallPublishStatus { $URI = "/api/4.0/firewall/globalroot-0/status" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection [system.xml.xmldocument]$Content = $response.content - if ( Invoke-XPathQuery -Node $content -QueryMethod SelectSingleNode -query "child::firewallStatus" ){ + if ( Invoke-XpathQuery -Node $content -QueryMethod SelectSingleNode -query "child::firewallStatus" ) { $Content.firewallStatus } } - end{} + end {} } @@ -30146,12 +30320,12 @@ function Get-NsxLoadBalancer { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin {} @@ -30222,22 +30396,22 @@ function Set-NsxLoadBalancer { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$False)] - [switch]$Enabled, - [Parameter (Mandatory=$False)] - [switch]$EnableAcceleration, - [Parameter (Mandatory=$False)] - [switch]$EnableLogging, - [Parameter (Mandatory=$False)] - [ValidateSet("emergency","alert","critical","error","warning","notice","info","debug")] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $False)] + [switch]$Enabled, + [Parameter (Mandatory = $False)] + [switch]$EnableAcceleration, + [Parameter (Mandatory = $False)] + [switch]$EnableLogging, + [Parameter (Mandatory = $False)] + [ValidateSet("emergency", "alert", "critical", "error", "warning", "notice", "info", "debug")] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -30251,7 +30425,7 @@ function Set-NsxLoadBalancer { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_LoadBalancer.edgeId - $_LoadBalancer.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -Query 'descendant::edgeId')) ) | out-null + $_LoadBalancer.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -30259,7 +30433,8 @@ function Set-NsxLoadBalancer { if ( $PsBoundParameters.ContainsKey('Enabled') ) { if ( $Enabled ) { $_LoadBalancer.enabled = "true" - } else { + } + else { $_LoadBalancer.enabled = "false" } } @@ -30267,7 +30442,8 @@ function Set-NsxLoadBalancer { if ( $PsBoundParameters.ContainsKey('EnableAcceleration') ) { if ( $EnableAcceleration ) { $_LoadBalancer.accelerationEnabled = "true" - } else { + } + else { $_LoadBalancer.accelerationEnabled = "false" } } @@ -30275,7 +30451,8 @@ function Set-NsxLoadBalancer { if ( $PsBoundParameters.ContainsKey('EnableLogging') ) { if ( $EnableLogging ) { $_LoadBalancer.logging.enable = "true" - } else { + } + else { $_LoadBalancer.logging.enable = "false" } } @@ -30287,13 +30464,13 @@ function Set-NsxLoadBalancer { $URI = "/api/4.0/edges/$($edgeId)/loadbalancer/config" $body = $_LoadBalancer.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($edgeId)" -completed - Get-NsxEdge -objectId $($edgeId) -connection $connection | Get-NsxLoadBalancer + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Completed + Get-NsxEdge -objectId $($edgeId) -Connection $connection | Get-NsxLoadBalancer } - end{ + end { } } @@ -30326,16 +30503,16 @@ function Get-NsxLoadBalancerMonitor { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [PSCustomObject]$LoadBalancer, - [Parameter (Mandatory=$true,ParameterSetName="monitorId")] - [string]$monitorId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [PSCustomObject]$LoadBalancer, + [Parameter (Mandatory = $true, ParameterSetName = "monitorId")] + [string]$monitorId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name ) begin {} @@ -30343,10 +30520,10 @@ function Get-NsxLoadBalancerMonitor { process { if ( $Name) { - $Monitors = $loadbalancer.monitor | where-object { $_.name -eq $Name } + $Monitors = $loadbalancer.monitor | Where-Object { $_.name -eq $Name } } elseif ( $monitorId ) { - $Monitors = $loadbalancer.monitor | where-object { $_.monitorId -eq $monitorId } + $Monitors = $loadbalancer.monitor | Where-Object { $_.monitorId -eq $monitorId } } else { $Monitors = $loadbalancer.monitor @@ -30358,7 +30535,7 @@ function Get-NsxLoadBalancerMonitor { $_Monitor } } - end{ } + end { } } function New-NsxLoadBalancerMonitor { @@ -30393,96 +30570,96 @@ function New-NsxLoadBalancerMonitor { HTTPS -Method GET -Url "/WAPI/api/status" -Expected "200 OK" #> - [CmdLetBinding(DefaultParameterSetName="HTTP")] - - param ( - - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="TCP")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ICMP")] - [Parameter (Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="UDP")] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [switch]$TypeHttp, - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [switch]$TypeHttps, - [Parameter (Mandatory=$true, ParameterSetName="TCP")] - [switch]$TypeTcp, - [Parameter (Mandatory=$true, ParameterSetName="ICMP")] - [switch]$TypeIcmp, - [Parameter (Mandatory=$true, ParameterSetName="UDP")] - [switch]$TypeUdp, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$true, ParameterSetName="TCP")] - [Parameter (Mandatory=$true, ParameterSetName="ICMP")] - [Parameter (Mandatory=$true, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$true, ParameterSetName="TCP")] - [Parameter (Mandatory=$true, ParameterSetName="ICMP")] - [Parameter (Mandatory=$true, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$Interval, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$true, ParameterSetName="TCP")] - [Parameter (Mandatory=$true, ParameterSetName="ICMP")] - [Parameter (Mandatory=$true, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$Timeout, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$true, ParameterSetName="TCP")] - [Parameter (Mandatory=$true, ParameterSetName="ICMP")] - [Parameter (Mandatory=$true, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$MaxRetries, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [ValidateSet("GET","POST","OPTIONS", IgnoreCase=$False)] - [string]$Method, - [Parameter (Mandatory=$true, ParameterSetName="HTTP")] - [Parameter (Mandatory=$true, ParameterSetName="HTTPS")] - [ValidateNotNullOrEmpty()] - [string]$Url, - [Parameter (Mandatory=$false, ParameterSetName="HTTP")] - [Parameter (Mandatory=$false, ParameterSetName="HTTPS")] - [ValidateNotNullOrEmpty()] - [string]$Expected, - [Parameter (Mandatory=$false, ParameterSetName="HTTP")] - [Parameter (Mandatory=$false, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$false, ParameterSetName="TCP")] - [Parameter (Mandatory=$false, ParameterSetName="ICMP")] - [Parameter (Mandatory=$false, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$Send, - [Parameter (Mandatory=$false, ParameterSetName="HTTP")] - [Parameter (Mandatory=$false, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$false, ParameterSetName="TCP")] - [Parameter (Mandatory=$false, ParameterSetName="ICMP")] - [Parameter (Mandatory=$false, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$Receive, - [Parameter (Mandatory=$false, ParameterSetName="HTTP")] - [Parameter (Mandatory=$false, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$false, ParameterSetName="TCP")] - [Parameter (Mandatory=$false, ParameterSetName="ICMP")] - [Parameter (Mandatory=$false, ParameterSetName="UDP")] - [ValidateNotNullOrEmpty()] - [string]$Extension, - [Parameter (Mandatory=$false, ParameterSetName="HTTP")] - [Parameter (Mandatory=$false, ParameterSetName="HTTPS")] - [Parameter (Mandatory=$false, ParameterSetName="TCP")] - [Parameter (Mandatory=$false, ParameterSetName="ICMP")] - [Parameter (Mandatory=$false, ParameterSetName="UDP")] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdLetBinding(DefaultParameterSetName = "HTTP")] + + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "TCP")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "UDP")] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [switch]$TypeHttp, + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [switch]$TypeHttps, + [Parameter (Mandatory = $true, ParameterSetName = "TCP")] + [switch]$TypeTcp, + [Parameter (Mandatory = $true, ParameterSetName = "ICMP")] + [switch]$TypeIcmp, + [Parameter (Mandatory = $true, ParameterSetName = "UDP")] + [switch]$TypeUdp, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $true, ParameterSetName = "TCP")] + [Parameter (Mandatory = $true, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $true, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $true, ParameterSetName = "TCP")] + [Parameter (Mandatory = $true, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $true, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$Interval, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $true, ParameterSetName = "TCP")] + [Parameter (Mandatory = $true, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $true, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$Timeout, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $true, ParameterSetName = "TCP")] + [Parameter (Mandatory = $true, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $true, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$MaxRetries, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [ValidateSet("GET", "POST", "OPTIONS", IgnoreCase = $False)] + [string]$Method, + [Parameter (Mandatory = $true, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $true, ParameterSetName = "HTTPS")] + [ValidateNotNullOrEmpty()] + [string]$Url, + [Parameter (Mandatory = $false, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $false, ParameterSetName = "HTTPS")] + [ValidateNotNullOrEmpty()] + [string]$Expected, + [Parameter (Mandatory = $false, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $false, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $false, ParameterSetName = "TCP")] + [Parameter (Mandatory = $false, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $false, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$Send, + [Parameter (Mandatory = $false, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $false, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $false, ParameterSetName = "TCP")] + [Parameter (Mandatory = $false, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $false, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$Receive, + [Parameter (Mandatory = $false, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $false, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $false, ParameterSetName = "TCP")] + [Parameter (Mandatory = $false, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $false, ParameterSetName = "UDP")] + [ValidateNotNullOrEmpty()] + [string]$Extension, + [Parameter (Mandatory = $false, ParameterSetName = "HTTP")] + [Parameter (Mandatory = $false, ParameterSetName = "HTTPS")] + [Parameter (Mandatory = $false, ParameterSetName = "TCP")] + [Parameter (Mandatory = $false, ParameterSetName = "ICMP")] + [Parameter (Mandatory = $false, ParameterSetName = "UDP")] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -30494,7 +30671,7 @@ function New-NsxLoadBalancerMonitor { $edgeId = $LoadBalancer.edgeId if ( -not $LoadBalancer.enabled -eq 'true' ) { - write-warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." + Write-Warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." } [System.XML.XMLElement]$xmlmonitor = $LoadBalancer.OwnerDocument.CreateElement("monitor") @@ -30525,7 +30702,8 @@ function New-NsxLoadBalancerMonitor { #will match both HTTP and HTTPS due to regex switch handling... if ( $TypeHttp ) { Add-XmlElement -xmlRoot $xmlmonitor -xmlElementName "type" -xmlElementText "http" - } else { + } + else { Add-XmlElement -xmlRoot $xmlmonitor -xmlElementName "type" -xmlElementText "https" } @@ -30558,11 +30736,11 @@ function New-NsxLoadBalancerMonitor { $URI = "/api/4.0/edges/$edgeId/loadbalancer/config/monitors" $body = $xmlmonitor.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" -status "Load Balancer Monitor Config" - $null = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($edgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Status "Load Balancer Monitor Config" + $null = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Completed - get-nsxedge -objectId $edgeId -connection $connection | Get-NsxLoadBalancer | Get-NsxLoadBalancerMonitor -name $Name + Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxLoadBalancer | Get-NsxLoadBalancerMonitor -Name $Name } end {} @@ -30593,19 +30771,19 @@ function Remove-NsxLoadBalancerMonitor { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLoadBalancerMonitor $_ })] - [System.Xml.XmlElement]$Monitor, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLoadBalancerMonitor $_ })] + [System.Xml.XmlElement]$Monitor, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -30618,7 +30796,7 @@ function Remove-NsxLoadBalancerMonitor { $URI = "/api/4.0/edges/$edgeId/loadbalancer/config/monitors/$MonitorId" if ( $confirm ) { - $message = "Monitor removal is permanent." + $message = "Monitor removal is permanent." $question = "Proceed with removal of Load Balancer Monitor $($MonitorId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -30629,9 +30807,9 @@ function Remove-NsxLoadBalancerMonitor { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $EdgeId" -status "Removing Monitor $MonitorId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Status "Removing Monitor $MonitorId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed } } @@ -30673,17 +30851,17 @@ function Get-NsxLoadBalancerApplicationProfile { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$true,ParameterSetName="applicationProfileId")] - [alias("applicationProfileId")] - [string]$objectId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $true, ParameterSetName = "applicationProfileId")] + [alias("applicationProfileId")] + [string]$objectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name ) @@ -30691,12 +30869,12 @@ function Get-NsxLoadBalancerApplicationProfile { process { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -Query 'descendant::applicationProfile')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -query 'descendant::applicationProfile')) { if ( $PsBoundParameters.ContainsKey('Name')) { - $AppProfiles = $loadbalancer.applicationProfile | where-object { $_.name -eq $Name } + $AppProfiles = $loadbalancer.applicationProfile | Where-Object { $_.name -eq $Name } } elseif ( $PsBoundParameters.ContainsKey('objectId') ) { - $AppProfiles = $loadbalancer.applicationProfile | where-object { $_.applicationProfileId -eq $objectId } + $AppProfiles = $loadbalancer.applicationProfile | Where-Object { $_.applicationProfileId -eq $objectId } } else { $AppProfiles = $loadbalancer.applicationProfile @@ -30710,7 +30888,7 @@ function Get-NsxLoadBalancerApplicationProfile { } } - end{ } + end { } } function New-NsxLoadBalancerApplicationProfile { @@ -30745,36 +30923,36 @@ function New-NsxLoadBalancerApplicationProfile { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$True)] - [ValidateSet("TCP","UDP","HTTP","HTTPS")] - [string]$Type, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [switch]$InsertXForwardedFor=$false, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [switch]$SslPassthrough=$false, - [Parameter (Mandatory=$False)] - [ValidateSet("ssl_sessionid", "cookie", "sourceip", "msrdp", IgnoreCase=$false)] - [string]$PersistenceMethod, - [Parameter (Mandatory=$False)] - [int]$PersistenceExpiry, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$CookieName, - [Parameter (Mandatory=$False)] - [ValidateSet("insert", "prefix", "app")] - [string]$CookieMode, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $True)] + [ValidateSet("TCP", "UDP", "HTTP", "HTTPS")] + [string]$Type, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [switch]$InsertXForwardedFor = $false, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [switch]$SslPassthrough = $false, + [Parameter (Mandatory = $False)] + [ValidateSet("ssl_sessionid", "cookie", "sourceip", "msrdp", IgnoreCase = $false)] + [string]$PersistenceMethod, + [Parameter (Mandatory = $False)] + [int]$PersistenceExpiry, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$CookieName, + [Parameter (Mandatory = $False)] + [ValidateSet("insert", "prefix", "app")] + [string]$CookieMode, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) # Still a bit to do here - need cert selection... @@ -30794,14 +30972,14 @@ function New-NsxLoadBalancerApplicationProfile { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_LoadBalancer.edgeId - $_LoadBalancer.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -Query 'descendant::edgeId')) ) | out-null + $_LoadBalancer.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -query 'descendant::edgeId')) ) | Out-Null if ( -not $_LoadBalancer.enabled -eq 'true' ) { - write-warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." + Write-Warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." } [System.XML.XMLElement]$xmlapplicationProfile = $_LoadBalancer.OwnerDocument.CreateElement("applicationProfile") - $_LoadBalancer.appendChild($xmlapplicationProfile) | out-null + $_LoadBalancer.appendChild($xmlapplicationProfile) | Out-Null #Mandatory Params and those with Default values Add-XmlElement -xmlRoot $xmlapplicationProfile -xmlElementName "name" -xmlElementText $Name @@ -30812,7 +30990,7 @@ function New-NsxLoadBalancerApplicationProfile { #Optionals. If ( $PsBoundParameters.ContainsKey('PersistenceMethod')) { [System.XML.XMLElement]$xmlPersistence = $_LoadBalancer.OwnerDocument.CreateElement("persistence") - $xmlapplicationProfile.appendChild($xmlPersistence) | out-null + $xmlapplicationProfile.appendChild($xmlPersistence) | Out-Null Add-XmlElement -xmlRoot $xmlPersistence -xmlElementName "method" -xmlElementText $PersistenceMethod If ( $PsBoundParameters.ContainsKey('CookieName')) { Add-XmlElement -xmlRoot $xmlPersistence -xmlElementName "cookieName" -xmlElementText $CookieName @@ -30828,30 +31006,30 @@ function New-NsxLoadBalancerApplicationProfile { $URI = "/api/4.0/edges/$edgeId/loadbalancer/config" $body = $_LoadBalancer.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" -status "Load Balancer Config" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($edgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Status "Load Balancer Config" + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Completed - $updatedEdge = Get-NsxEdge -objectId $($edgeId) -connection $connection + $updatedEdge = Get-NsxEdge -objectId $($edgeId) -Connection $connection $applicationProfiles = $updatedEdge.features.loadbalancer.applicationProfile foreach ($applicationProfile in $applicationProfiles) { #6.1 Bug? NSX API creates an object ID format that it does not accept back when put. We have to change on the fly to the 'correct format'. - write-debug "$($MyInvocation.MyCommand.Name) : Checking for stupidness in $($applicationProfile.applicationProfileId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Checking for stupidness in $($applicationProfile.applicationProfileId)" $applicationProfile.applicationProfileId = - $applicationProfile.applicationProfileId.replace("edge_load_balancer_application_profiles","applicationProfile-") + $applicationProfile.applicationProfileId.replace("edge_load_balancer_application_profiles", "applicationProfile-") } $body = $updatedEdge.features.loadbalancer.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" -status "Load Balancer Config" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($edgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Status "Load Balancer Config" + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Completed #filter output for our newly created app profile - name is safe as it has to be unique. - $return = $updatedEdge.features.loadbalancer.applicationProfile | where-object { $_.name -eq $name } - Add-XmlElement -xmlroot $return -xmlElementName "edgeId" -xmlElementText $edgeId + $return = $updatedEdge.features.loadbalancer.applicationProfile | Where-Object { $_.name -eq $name } + Add-XmlElement -xmlRoot $return -xmlElementName "edgeId" -xmlElementText $edgeId $return } @@ -30886,19 +31064,19 @@ function Remove-NsxLoadBalancerApplicationProfile { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLoadBalancerApplicationProfile $_ })] - [System.Xml.XmlElement]$ApplicationProfile, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLoadBalancerApplicationProfile $_ })] + [System.Xml.XmlElement]$ApplicationProfile, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -30911,7 +31089,7 @@ function Remove-NsxLoadBalancerApplicationProfile { $URI = "/api/4.0/edges/$edgeId/loadbalancer/config/applicationprofiles/$AppProfileId" if ( $confirm ) { - $message = "Application Profile removal is permanent." + $message = "Application Profile removal is permanent." $question = "Proceed with removal of Application Profile $($AppProfileId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -30922,9 +31100,9 @@ function Remove-NsxLoadBalancerApplicationProfile { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $EdgeId" -status "Removing Application Profile $AppProfileId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Status "Removing Application Profile $AppProfileId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed } } @@ -30984,34 +31162,34 @@ function New-NsxLoadBalancerMemberSpec { #> - [CmdLetBinding(DefaultParameterSetName="IpAddress")] + [CmdLetBinding(DefaultParameterSetName = "IpAddress")] param ( - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true, ParameterSetName="IpAddress")] - [ValidateNotNullOrEmpty()] - [IpAddress]$IpAddress, - [Parameter (Mandatory=$true, ParameterSetName="GroupingObject")] - [ValidateScript( { ValidateSecurityGroupMember $_ })] - [object]$Member, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$Weight=1, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$Port, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$MonitorPort=$Port, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$MinimumConnections=0, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$MaximumConnections=0 + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "IpAddress")] + [ValidateNotNullOrEmpty()] + [IpAddress]$IpAddress, + [Parameter (Mandatory = $true, ParameterSetName = "GroupingObject")] + [ValidateScript( { ValidateSecurityGroupMember $_ })] + [object]$Member, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$Weight = 1, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$Port, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$MonitorPort = $Port, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$MinimumConnections = 0, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$MaximumConnections = 0 ) begin {} @@ -31019,7 +31197,7 @@ function New-NsxLoadBalancerMemberSpec { [System.XML.XMLDocument]$xmlDoc = New-Object System.XML.XMLDocument [System.XML.XMLElement]$xmlMember = $XMLDoc.CreateElement("member") - $xmlDoc.appendChild($xmlMember) | out-null + $xmlDoc.appendChild($xmlMember) | Out-Null Add-XmlElement -xmlRoot $xmlMember -xmlElementName "name" -xmlElementText $Name if ( $PSCmdlet.ParameterSetName -eq "ipaddress" ) { @@ -31035,7 +31213,7 @@ function New-NsxLoadBalancerMemberSpec { $MemberMoref = $Member $MemberName = $Member } - elseif ( ($Member -is [string] ) -and ( [guid]::tryparse(($Member -replace ".\d{3}$",""), [ref][guid]::Empty)) ) { + elseif ( ($Member -is [string] ) -and ( [guid]::tryparse(($Member -replace ".\d{3}$", ""), [ref][guid]::Empty)) ) { $MemberMoref = $Member $MemberName = $Member } @@ -31046,7 +31224,7 @@ function New-NsxLoadBalancerMemberSpec { elseif ( $Member -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($Member.parent | get-view).config.instanceuuid + $vmUuid = ($Member.parent | Get-View).config.instanceuuid $MemberMoref = "$vmUuid.$($Member.id.substring($Member.id.length-3))" $MemberName = $Member.Name @@ -31119,31 +31297,31 @@ function New-NsxLoadBalancerPool { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$False)] - [ValidateNotNull()] - [string]$Description="", - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [switch]$Transparent=$false, - [Parameter (Mandatory=$True)] - [ValidateSet("round-robin", "ip-hash", "uri", "leastconn")] - [string]$Algorithm, - [Parameter (Mandatory=$false)] - [ValidateScript({ ValidateLoadBalancerMonitor $_ })] - [System.Xml.XmlElement]$Monitor, - [Parameter (Mandatory=$false)] - [ValidateScript({ ValidateLoadBalancerMemberSpec $_ })] - [System.Xml.XmlElement[]]$MemberSpec, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $False)] + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [switch]$Transparent = $false, + [Parameter (Mandatory = $True)] + [ValidateSet("round-robin", "ip-hash", "uri", "leastconn")] + [string]$Algorithm, + [Parameter (Mandatory = $false)] + [ValidateScript( { ValidateLoadBalancerMonitor $_ })] + [System.Xml.XmlElement]$Monitor, + [Parameter (Mandatory = $false)] + [ValidateScript( { ValidateLoadBalancerMemberSpec $_ })] + [System.Xml.XmlElement[]]$MemberSpec, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -31156,14 +31334,14 @@ function New-NsxLoadBalancerPool { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_LoadBalancer.edgeId - $_LoadBalancer.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -Query 'descendant::edgeId')) ) | out-null + $_LoadBalancer.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -query 'descendant::edgeId')) ) | Out-Null if ( -not $_LoadBalancer.enabled -eq 'true' ) { - write-warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." + Write-Warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." } [System.XML.XMLElement]$xmlPool = $_LoadBalancer.OwnerDocument.CreateElement("pool") - $_LoadBalancer.appendChild($xmlPool) | out-null + $_LoadBalancer.appendChild($xmlPool) | Out-Null Add-XmlElement -xmlRoot $xmlPool -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlPool -xmlElementName "description" -xmlElementText $Description @@ -31177,20 +31355,20 @@ function New-NsxLoadBalancerPool { if ( $PSBoundParameters.ContainsKey('MemberSpec')) { foreach ( $Member in $MemberSpec ) { $xmlmember = $xmlPool.OwnerDocument.ImportNode($Member, $true) - $xmlPool.AppendChild($xmlmember) | out-null + $xmlPool.AppendChild($xmlmember) | Out-Null } } $URI = "/api/4.0/edges/$EdgeId/loadbalancer/config" $body = $_LoadBalancer.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" -status "Load Balancer Config" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Status "Load Balancer Config" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed - $UpdatedEdge = Get-NsxEdge -objectId $($EdgeId) -connection $connection - $return = $UpdatedEdge.features.loadBalancer.pool | where-object { $_.name -eq $Name } - Add-XmlElement -xmlroot $return -xmlElementName "edgeId" -xmlElementText $edgeId + $UpdatedEdge = Get-NsxEdge -objectId $($EdgeId) -Connection $connection + $return = $UpdatedEdge.features.loadBalancer.pool | Where-Object { $_.name -eq $Name } + Add-XmlElement -xmlRoot $return -xmlElementName "edgeId" -xmlElementText $edgeId $return } @@ -31228,16 +31406,16 @@ function Get-NsxLoadBalancerPool { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$true,ParameterSetName="poolId")] - [string]$PoolId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $true, ParameterSetName = "poolId")] + [string]$PoolId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name ) @@ -31245,12 +31423,12 @@ function Get-NsxLoadBalancerPool { process { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $loadbalancer -Query 'child::pool')) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $loadbalancer -query 'child::pool')) { if ( $PsBoundParameters.ContainsKey('Name')) { - $pools = $loadbalancer.pool | where-object { $_.name -eq $Name } + $pools = $loadbalancer.pool | Where-Object { $_.name -eq $Name } } elseif ( $PsBoundParameters.ContainsKey('PoolId')) { - $pools = $loadbalancer.pool | where-object { $_.poolId -eq $PoolId } + $pools = $loadbalancer.pool | Where-Object { $_.poolId -eq $PoolId } } else { $pools = $loadbalancer.pool @@ -31264,7 +31442,7 @@ function Get-NsxLoadBalancerPool { } } - end{ } + end { } } function Remove-NsxLoadBalancerPool { @@ -31293,19 +31471,19 @@ function Remove-NsxLoadBalancerPool { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLoadBalancerPool $_ })] - [System.Xml.XmlElement]$LoadBalancerPool, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLoadBalancerPool $_ })] + [System.Xml.XmlElement]$LoadBalancerPool, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -31316,21 +31494,21 @@ function Remove-NsxLoadBalancerPool { $poolId = $LoadBalancerPool.poolId #Get and remove the edgeId element - $LoadBalancer = Get-nsxEdge -objectId $edgeId -connection $connection | Get-NsxLoadBalancer - $LoadBalancer.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -Query 'child::edgeId')) ) | out-null + $LoadBalancer = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxLoadBalancer + $LoadBalancer.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -query 'child::edgeId')) ) | Out-Null - $PoolToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -Query "child::pool[poolId=`"$poolId`"]") + $PoolToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -query "child::pool[poolId=`"$poolId`"]") if ( -not $PoolToRemove ) { throw "Pool $poolId is not defined on Load Balancer $edgeid." } - $LoadBalancer.RemoveChild( $PoolToRemove ) | out-null + $LoadBalancer.RemoveChild( $PoolToRemove ) | Out-Null $URI = "/api/4.0/edges/$edgeId/loadbalancer/config" $body = $LoadBalancer.OuterXml if ( $confirm ) { - $message = "Pool removal is permanent." + $message = "Pool removal is permanent." $question = "Proceed with removal of Pool $($poolId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -31341,11 +31519,11 @@ function Remove-NsxLoadBalancerPool { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $EdgeId" -status "Removing pool $poolId" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Status "Removing pool $poolId" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed - Get-NSxEdge -objectID $edgeId -connection $connection | Get-NsxLoadBalancer + Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxLoadBalancer } } @@ -31378,16 +31556,16 @@ function Get-NsxLoadBalancerPoolMember { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancerPool $_ })] - [System.Xml.XmlElement]$LoadBalancerPool, - [Parameter (Mandatory=$true,ParameterSetName="MemberId")] - [string]$MemberId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancerPool $_ })] + [System.Xml.XmlElement]$LoadBalancerPool, + [Parameter (Mandatory = $true, ParameterSetName = "MemberId")] + [string]$MemberId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name ) @@ -31396,13 +31574,13 @@ function Get-NsxLoadBalancerPoolMember { process { if ( $PsBoundParameters.ContainsKey('Name')) { - $Members = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $LoadBalancerPool -Query 'descendant::member') | where-object { $_.name -eq $Name } + $Members = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $LoadBalancerPool -query 'descendant::member') | Where-Object { $_.name -eq $Name } } elseif ( $PsBoundParameters.ContainsKey('MemberId')) { - $Members = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $LoadBalancerPool -Query 'descendant::member') | where-object { $_.memberId -eq $MemberId } + $Members = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $LoadBalancerPool -query 'descendant::member') | Where-Object { $_.memberId -eq $MemberId } } else { - $Members = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $LoadBalancerPool -Query 'descendant::member') + $Members = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $LoadBalancerPool -query 'descendant::member') } foreach ( $Member in $Members ) { @@ -31414,7 +31592,7 @@ function Get-NsxLoadBalancerPoolMember { } } - end{ } + end { } } function Set-NsxLoadBalancerPoolMember { @@ -31470,50 +31648,50 @@ function Set-NsxLoadBalancerPoolMember { Set all members of all pools on edge testedge for weight 10 #> - [CmdLetBinding(DefaultParameterSetName="Default")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - #Pool member to be configured - [ValidateScript({ ValidateLoadBalancerPoolMember $_ })] - [System.Xml.XmlElement]$LoadBalancerPoolMember, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$false)] - [ValidateSet("enabled","disabled","drain")] - [string]$state, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$Weight, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$Port, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$MonitorPort, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$MinimumConnections, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$MaximumConnections, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdLetBinding(DefaultParameterSetName = "Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + #Pool member to be configured + [ValidateScript( { ValidateLoadBalancerPoolMember $_ })] + [System.Xml.XmlElement]$LoadBalancerPoolMember, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $false)] + [ValidateSet("enabled", "disabled", "drain")] + [string]$state, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$Weight, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$Port, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$MonitorPort, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$MinimumConnections, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$MaximumConnections, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } - if ($PSBoundParameters.ContainsKey("state") -and ($state -eq "drain") -and ([version]$Connection.version -lt [version]"6.3.0")){ + if ($PSBoundParameters.ContainsKey("state") -and ($state -eq "drain") -and ([version]$Connection.version -lt [version]"6.3.0")) { throw "Setting a member state to drain requires NSX 6.3.0 or above." } } @@ -31523,10 +31701,10 @@ function Set-NsxLoadBalancerPoolMember { $edgeid = $LoadBalancerPoolMember.edgeId $poolid = $loadBalancerPoolMember.poolId $memberId = $LoadBalancerPoolMember.memberId - $response = Invoke-NsxWebRequest -Method "get" -Uri "/api/4.0/edges/$edgeid/loadbalancer/config/pools/$poolid" + $response = Invoke-NsxWebRequest -method "get" -URI "/api/4.0/edges/$edgeid/loadbalancer/config/pools/$poolid" [xml]$pool = $response.Content - $member = Invoke-XpathQuery -QueryMethod SelectSingleNode -Query "child::member[memberId=`"$memberId`"]" -Node $pool.pool + $member = Invoke-XpathQuery -QueryMethod SelectSingleNode -query "child::member[memberId=`"$memberId`"]" -Node $pool.pool if ($PSBoundParameters.ContainsKey("state")) { $member.condition = $state.toLower() @@ -31549,15 +31727,15 @@ function Set-NsxLoadBalancerPoolMember { #ToDo: Missing Confirm!!! - $response = Invoke-NsxWebRequest -method "put" -uri "/api/4.0/edges/$edgeid/loadbalancer/config/pools/$poolid" -body $pool.outerxml - $response = Invoke-NsxWebRequest -Method "get" -Uri "/api/4.0/edges/$edgeid/loadbalancer/config/pools/$poolid" + $response = Invoke-NsxWebRequest -method "put" -URI "/api/4.0/edges/$edgeid/loadbalancer/config/pools/$poolid" -body $pool.outerxml + $response = Invoke-NsxWebRequest -method "get" -URI "/api/4.0/edges/$edgeid/loadbalancer/config/pools/$poolid" [xml]$pool = $response.Content - $member = Invoke-XpathQuery -QueryMethod SelectSingleNode -Query "child::member[memberId=`"$memberId`"]" -Node $pool.pool + $member = Invoke-XpathQuery -QueryMethod SelectSingleNode -query "child::member[memberId=`"$memberId`"]" -Node $pool.pool $member } - end{ } + end { } } function Add-NsxLoadBalancerPoolMember { @@ -31603,40 +31781,40 @@ function Add-NsxLoadBalancerPoolMember { Adds the NSX object WebLS LB pool1 on edge Edge01 #> - [CmdLetBinding(DefaultParameterSetName="IpAddress")] - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancerPool $_ })] - [System.Xml.XmlElement]$LoadBalancerPool, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true, ParameterSetName="IpAddress")] - [ValidateNotNullOrEmpty()] - [IpAddress]$IpAddress, - [Parameter (Mandatory=$true, ParameterSetName="Member")] - [ValidateScript( { ValidateSecurityGroupMember $_ })] - [object]$Member, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$Weight=1, - [Parameter (Mandatory=$true)] - [ValidateRange(1,65535)] - [int]$Port, - [Parameter (Mandatory=$false)] - [ValidateRange(1,65535)] - [int]$MonitorPort=$port, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$MinimumConnections=0, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [int]$MaximumConnections=0, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdLetBinding(DefaultParameterSetName = "IpAddress")] + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancerPool $_ })] + [System.Xml.XmlElement]$LoadBalancerPool, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "IpAddress")] + [ValidateNotNullOrEmpty()] + [IpAddress]$IpAddress, + [Parameter (Mandatory = $true, ParameterSetName = "Member")] + [ValidateScript( { ValidateSecurityGroupMember $_ })] + [object]$Member, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$Weight = 1, + [Parameter (Mandatory = $true)] + [ValidateRange(1, 65535)] + [int]$Port, + [Parameter (Mandatory = $false)] + [ValidateRange(1, 65535)] + [int]$MonitorPort = $port, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$MinimumConnections = 0, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$MaximumConnections = 0, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -31647,10 +31825,10 @@ function Add-NsxLoadBalancerPoolMember { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_LoadBalancerPool.edgeId - $_LoadBalancerPool.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancerPool -Query 'descendant::edgeId')) ) | out-null + $_LoadBalancerPool.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancerPool -query 'descendant::edgeId')) ) | Out-Null [System.XML.XMLElement]$xmlMember = $_LoadBalancerPool.OwnerDocument.CreateElement("member") - $_LoadBalancerPool.appendChild($xmlMember) | out-null + $_LoadBalancerPool.appendChild($xmlMember) | Out-Null Add-XmlElement -xmlRoot $xmlMember -xmlElementName "name" -xmlElementText $Name @@ -31667,7 +31845,7 @@ function Add-NsxLoadBalancerPoolMember { $MemberMoref = $Member $MemberName = $Member } - elseif ( ($Member -is [string] ) -and ( [guid]::tryparse(($Member -replace ".\d{3}$",""), [ref][guid]::Empty)) ) { + elseif ( ($Member -is [string] ) -and ( [guid]::tryparse(($Member -replace ".\d{3}$", ""), [ref][guid]::Empty)) ) { $MemberMoref = $Member $MemberName = $Member } @@ -31678,7 +31856,7 @@ function Add-NsxLoadBalancerPoolMember { elseif ( $Member -is [VMware.VimAutomation.ViCore.Interop.V1.VirtualDevice.NetworkAdapterInterop] ) { #See NSX API guide 'Attach or Detach a Virtual Machine from a Logical Switch' for #how to construct NIC id. - $vmUuid = ($Member.parent | get-view).config.instanceuuid + $vmUuid = ($Member.parent | Get-View).config.instanceuuid $MemberMoref = "$vmUuid.$($Member.id.substring($Member.id.length-3))" $MemberName = $Member } @@ -31704,16 +31882,16 @@ function Add-NsxLoadBalancerPoolMember { $URI = "/api/4.0/edges/$edgeId/loadbalancer/config/pools/$($_LoadBalancerPool.poolId)" $body = $_LoadBalancerPool.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" -status "Pool config for $($_LoadBalancerPool.poolId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Status "Pool config for $($_LoadBalancerPool.poolId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed #Get updated pool $URI = "/api/4.0/edges/$edgeId/loadbalancer/config/pools/$($_LoadBalancerPool.poolId)" - Write-Progress -activity "Retrieving Updated Pool for $($EdgeId)" -status "Pool $($_LoadBalancerPool.poolId)" - $return = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + Write-Progress -Activity "Retrieving Updated Pool for $($EdgeId)" -Status "Pool $($_LoadBalancerPool.poolId)" + $return = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $Pool = $return.pool - Add-XmlElement -xmlroot $Pool -xmlElementName "edgeId" -xmlElementText $edgeId + Add-XmlElement -xmlRoot $Pool -xmlElementName "edgeId" -xmlElementText $edgeId $Pool } @@ -31747,19 +31925,19 @@ function Remove-NsxLoadBalancerPoolMember { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLoadBalancerPoolMember $_ })] - [System.Xml.XmlElement]$LoadBalancerPoolMember, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLoadBalancerPoolMember $_ })] + [System.Xml.XmlElement]$LoadBalancerPoolMember, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -31771,23 +31949,23 @@ function Remove-NsxLoadBalancerPoolMember { $poolId = $LoadBalancerPoolMember.poolId #Get and remove the edgeId and poolId elements - $LoadBalancer = Get-nsxEdge -objectId $edgeId -connection $connection | Get-NsxLoadBalancer - $LoadBalancer.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -Query 'child::edgeId')) ) | out-null + $LoadBalancer = Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxLoadBalancer + $LoadBalancer.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -query 'child::edgeId')) ) | Out-Null - $LoadBalancerPool = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $loadbalancer -Query "child::pool[poolId=`"$poolId`"]") + $LoadBalancerPool = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $loadbalancer -query "child::pool[poolId=`"$poolId`"]") - $MemberToRemove = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancerPool -Query "child::member[memberId=`"$MemberId`"]") + $MemberToRemove = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancerPool -query "child::member[memberId=`"$MemberId`"]") if ( -not $MemberToRemove ) { throw "Member $MemberId is not a member of pool $PoolId." } - $LoadBalancerPool.RemoveChild( $MemberToRemove ) | out-null + $LoadBalancerPool.RemoveChild( $MemberToRemove ) | Out-Null $URI = "/api/4.0/edges/$edgeId/loadbalancer/config" $body = $LoadBalancer.OuterXml if ( $confirm ) { - $message = "Pool Member removal is permanent." + $message = "Pool Member removal is permanent." $question = "Proceed with removal of Pool Member $($memberId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -31798,11 +31976,11 @@ function Remove-NsxLoadBalancerPoolMember { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $EdgeId" -status "Pool config for $poolId" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Status "Pool config for $poolId" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed - Get-NSxEdge -objectID $edgeId -connection $connection | Get-NsxLoadBalancer | Get-NsxLoadBalancerPool -poolId $poolId + Get-NsxEdge -objectId $edgeId -Connection $connection | Get-NsxLoadBalancer | Get-NsxLoadBalancerPool -PoolId $poolId } } @@ -31835,16 +32013,16 @@ function Get-NsxLoadBalancerVip { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$true,ParameterSetName="VirtualServerId")] - [string]$VirtualServerId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $true, ParameterSetName = "VirtualServerId")] + [string]$VirtualServerId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + [string]$Name ) begin {} @@ -31852,13 +32030,13 @@ function Get-NsxLoadBalancerVip { process { if ( $PsBoundParameters.ContainsKey('Name')) { - $Vips = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $LoadBalancer -Query 'descendant::virtualServer') | where-object { $_.name -eq $Name } + $Vips = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $LoadBalancer -query 'descendant::virtualServer') | Where-Object { $_.name -eq $Name } } elseif ( $PsBoundParameters.ContainsKey('MemberId')) { - $Vips = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $LoadBalancer -Query 'descendant::virtualServer') | where-object { $_.virtualServerId -eq $VirtualServerId } + $Vips = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $LoadBalancer -query 'descendant::virtualServer') | Where-Object { $_.virtualServerId -eq $VirtualServerId } } else { - $Vips = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $LoadBalancer -Query 'descendant::virtualServer') + $Vips = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $LoadBalancer -query 'descendant::virtualServer') } foreach ( $Vip in $Vips ) { @@ -31868,7 +32046,7 @@ function Get-NsxLoadBalancerVip { } } - end{ } + end { } } function Add-NsxLoadBalancerVip { @@ -31905,49 +32083,49 @@ function Add-NsxLoadBalancerVip { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$False)] - [ValidateNotNull()] - [string]$Description="", - [Parameter (Mandatory=$True)] - [ValidateNotNullOrEmpty()] - [IpAddress]$IpAddress, - [Parameter (Mandatory=$True)] - [ValidateSet("http", "https", "tcp", "udp")] - [string]$Protocol, - [Parameter (Mandatory=$True)] - [ValidateRange(1,65535)] - [int]$Port, - [Parameter (Mandatory=$False)] - [ValidateNotNullorEmpty()] - [switch]$Enabled=$true, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLoadBalancerApplicationProfile $_ })] - [System.Xml.XmlElement]$ApplicationProfile, - [Parameter (Mandatory=$true)] - [ValidateScript({ ValidateLoadBalancerPool $_ })] - [System.Xml.XmlElement]$DefaultPool, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [switch]$AccelerationEnabled=$True, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [int]$ConnectionLimit=0, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [int]$ConnectionRateLimit=0, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $False)] + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [IpAddress]$IpAddress, + [Parameter (Mandatory = $True)] + [ValidateSet("http", "https", "tcp", "udp")] + [string]$Protocol, + [Parameter (Mandatory = $True)] + [ValidateRange(1, 65535)] + [int]$Port, + [Parameter (Mandatory = $False)] + [ValidateNotNullorEmpty()] + [switch]$Enabled = $true, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLoadBalancerApplicationProfile $_ })] + [System.Xml.XmlElement]$ApplicationProfile, + [Parameter (Mandatory = $true)] + [ValidateScript( { ValidateLoadBalancerPool $_ })] + [System.Xml.XmlElement]$DefaultPool, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [switch]$AccelerationEnabled = $True, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [int]$ConnectionLimit = 0, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [int]$ConnectionRateLimit = 0, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -31961,14 +32139,14 @@ function Add-NsxLoadBalancerVip { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_LoadBalancer.edgeId - $_LoadBalancer.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -Query 'descendant::edgeId')) ) | out-null + $_LoadBalancer.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancer -query 'descendant::edgeId')) ) | Out-Null if ( -not $_LoadBalancer.enabled -eq 'true' ) { - write-warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." + Write-Warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -Enabled to enable." } [System.XML.XMLElement]$xmlVIip = $_LoadBalancer.OwnerDocument.CreateElement("virtualServer") - $_LoadBalancer.appendChild($xmlVIip) | out-null + $_LoadBalancer.appendChild($xmlVIip) | Out-Null Add-XmlElement -xmlRoot $xmlVIip -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlVIip -xmlElementName "description" -xmlElementText $Description @@ -31985,11 +32163,11 @@ function Add-NsxLoadBalancerVip { $URI = "/api/4.0/edges/$($EdgeId)/loadbalancer/config" $body = $_LoadBalancer.OuterXml - Write-Progress -activity "Update Edge Services Gateway $EdgeId" -status "Load Balancer Config" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $EdgeId" -completed + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Status "Load Balancer Config" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $EdgeId" -Completed - $UpdatedLB = Get-NsxEdge -objectId $EdgeId -connection $connection | Get-NsxLoadBalancer + $UpdatedLB = Get-NsxEdge -objectId $EdgeId -Connection $connection | Get-NsxLoadBalancer $UpdatedLB } @@ -32022,18 +32200,18 @@ function Remove-NsxLoadBalancerVip { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateLoadBalancerVip $_ })] - [System.Xml.XmlElement]$LoadBalancerVip, - [Parameter (Mandatory=$False)] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLoadBalancerVip $_ })] + [System.Xml.XmlElement]$LoadBalancerVip, + [Parameter (Mandatory = $False)] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -32048,7 +32226,7 @@ function Remove-NsxLoadBalancerVip { $URI = "/api/4.0/edges/$edgeId/loadbalancer/config/virtualservers/$VipId" if ( $confirm ) { - $message = "VIP removal is permanent." + $message = "VIP removal is permanent." $question = "Proceed with removal of VIP $VipID on Edge $($edgeId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -32059,16 +32237,16 @@ function Remove-NsxLoadBalancerVip { } else { $decision = 0 } if ($decision -eq 0) { - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" -status "Removing VIP $VipId" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Status "Removing VIP $VipId" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed } } end {} } -function Get-NsxLoadBalancerStats{ +function Get-NsxLoadBalancerStats { <# .SYNOPSIS @@ -32097,16 +32275,16 @@ function Get-NsxLoadBalancerStats{ #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - #Load Balancer from which to retrieve stats. Must be enabled. - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + #Load Balancer from which to retrieve stats. Must be enabled. + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection - ) + ) begin {} process { @@ -32117,8 +32295,8 @@ function Get-NsxLoadBalancerStats{ } $URI = "/api/4.0/edges/$($LoadBalancer.EdgeId)/loadbalancer/statistics" - [system.xml.xmldocument]$response = invoke-nsxrestmethod -method "GET" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query "child::loadBalancerStatusAndStats")) { + [system.xml.xmldocument]$response = Invoke-NsxRestMethod -method "GET" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::loadBalancerStatusAndStats")) { $response.loadBalancerStatusAndStats } } @@ -32165,16 +32343,16 @@ function Get-NsxLoadBalancerApplicationRule { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$false,ParameterSetName="ObjectId")] - [string]$ObjectId, - [Parameter (Mandatory=$false,Position=1,ParameterSetName="Name")] - [string]$Name + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $false, ParameterSetName = "ObjectId")] + [string]$ObjectId, + [Parameter (Mandatory = $false, Position = 1, ParameterSetName = "Name")] + [string]$Name ) @@ -32185,9 +32363,9 @@ function Get-NsxLoadBalancerApplicationRule { process { if ( -not ($PsBoundParameters.ContainsKey("ObjectId"))) { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -Query "child::applicationRule")){ - if ($PsBoundParameters.ContainsKey("Name")){ - $LoadBalancer.applicationRule | where-object {$_.name -eq $Name} + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -query "child::applicationRule")) { + if ($PsBoundParameters.ContainsKey("Name")) { + $LoadBalancer.applicationRule | Where-Object { $_.name -eq $Name } } else { $LoadBalancer.applicationRule @@ -32195,8 +32373,8 @@ function Get-NsxLoadBalancerApplicationRule { } } else { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -Query "child::applicationRule/applicationRuleId")){ - $LoadBalancer.applicationRule | where-object {$_.applicationRuleId -eq $ObjectId} + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $LoadBalancer -query "child::applicationRule/applicationRuleId")) { + $LoadBalancer.applicationRule | Where-Object { $_.applicationRuleId -eq $ObjectId } } } } @@ -32230,20 +32408,20 @@ function New-NsxLoadBalancerApplicationRule { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancer $_ })] - [System.Xml.XmlElement]$LoadBalancer, - [Parameter (Mandatory=$True)] - [string]$Script, - [Parameter (Mandatory=$True,Position=1)] - [string]$Name, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancer $_ })] + [System.Xml.XmlElement]$LoadBalancer, + [Parameter (Mandatory = $True)] + [string]$Script, + [Parameter (Mandatory = $True, Position = 1)] + [string]$Name, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -32257,7 +32435,7 @@ function New-NsxLoadBalancerApplicationRule { $edgeId = $LoadBalancer.edgeId if ( -not $_LoadBalancer.enabled -eq 'true' ) { - write-warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -EnableLoadBalancing to enable." + Write-Warning "Load Balancer feature is not enabled on edge $($edgeId). Use Set-NsxLoadBalancer -EnableLoadBalancing to enable." } #Create a new XML document. Use applicationRule as root. [System.XML.XmlDocument]$xmldoc = New-Object System.XML.XmlDocument @@ -32272,11 +32450,11 @@ function New-NsxLoadBalancerApplicationRule { $URI = "/api/4.0/edges/$($EdgeId)/loadbalancer/config/applicationrules" $body = $xmlAr.OuterXml - $Response = Invoke-NsxWebRequest -method "POST" -uri $URI -body $body -connection $Connection + $Response = Invoke-NsxWebRequest -method "POST" -URI $URI -body $body -connection $Connection [System.XML.XmlDocument]$ApplicationRule = Invoke-NsxRestMethod -method "GET" -URI $Response.Headers.Location - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $ApplicationRule -Query "child::applicationRule")){ + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $ApplicationRule -query "child::applicationRule")) { $ApplicationRule.applicationRule } } @@ -32315,17 +32493,17 @@ function Get-NsxSecurityPolicyHighestUsedPrecedence { [CmdLetBinding()] param ( - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) $URI = "/api/2.0/services/policy/securitypolicy/maxprecedence" - $return = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $return = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection if ( -not ($return -match "\d*")) { throw "Unexpected result $return from call to get highest used precedence. Return value should be a number." } - [pscustomobject]@{"Precedence" = [int]$return} + [pscustomobject]@{"Precedence" = [int]$return } } function Get-NsxSecurityPolicy { @@ -32351,27 +32529,27 @@ function Get-NsxSecurityPolicy { Retrieves all security policies applied to the security Group WeApp1WebServers #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ParameterSetName="objectId")] - # Set Security Policies by objectId - [string]$ObjectId, - [Parameter (Mandatory=$false,ParameterSetName="Name",Position=1)] - # Get Security Policies by name - [string]$Name, - [Parameter (Mandatory=$true,ParameterSetName="SecurityGroup", ValueFromPipeline=$true)] - # Get Security Policies applied to the specified Security Group - [ValidateScript({ ValidateSecurityGroup $_ })] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$false)] - # Include the readonly (system) Security Policies in results. - [alias("ShowHidden")] - [switch]$IncludeHidden=$False, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ParameterSetName = "objectId")] + # Set Security Policies by objectId + [string]$ObjectId, + [Parameter (Mandatory = $false, ParameterSetName = "Name", Position = 1)] + # Get Security Policies by name + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "SecurityGroup", ValueFromPipeline = $true)] + # Get Security Policies applied to the specified Security Group + [ValidateScript( { ValidateSecurityGroup $_ })] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $false)] + # Include the readonly (system) Security Policies in results. + [alias("ShowHidden")] + [switch]$IncludeHidden = $False, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -32382,13 +32560,13 @@ function Get-NsxSecurityPolicy { "Name" { #Get all Security Policies and optionally filter on Name $URI = "/api/2.0/services/policy/securitypolicy/all" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $securityPolicies = @() - if ($response.securityPolicies | Get-Member -memberType Properties -Name pagingInfo) { + if ($response.securityPolicies | Get-Member -MemberType Properties -Name pagingInfo) { $defaultPageSize = 1024 - $itemIndex = 0 + $itemIndex = 0 $startingIndex = 0 $pagingInfo = $response.securityPolicies.pagingInfo @@ -32410,7 +32588,7 @@ function Get-NsxSecurityPolicy { $startingIndex += $defaultPageSize $URI = "/api/2.0/services/policy/securitypolicy/all?pageSize=$defaultPageSize&startIndex=$startingIndex" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $pagingInfo = $response.securityPolicies.pagingInfo } @@ -32423,9 +32601,10 @@ function Get-NsxSecurityPolicy { $securityPolicies = $response.securityPolicies.securitypolicy } - if ( $PSBoundParameters.ContainsKey("Name") ) { - $FinalSecPol = $securityPolicies | where-object { $_.name -eq $Name } - } else { + if ( $PSBoundParameters.ContainsKey("Name") ) { + $FinalSecPol = $securityPolicies | Where-Object { $_.name -eq $Name } + } + else { $FinalSecPol = $securityPolicies } } @@ -32433,14 +32612,14 @@ function Get-NsxSecurityPolicy { "objectId" { #Just getting a single Security policy $URI = "/api/2.0/services/policy/securitypolicy/$objectId" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $FinalSecPol = $response.securityPolicy } "SecurityGroup" { $URI = "/api/2.0/services/policy/securitygroup/$($SecurityGroup.objectId)/securitypolicies" - $response = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection - if ( invoke-xpathquery -node $response -querymethod selectSingleNode -query "child::securityPolicies/securityPolicy" ) { + $response = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection + if ( Invoke-XpathQuery -Node $response -QueryMethod selectSingleNode -query "child::securityPolicies/securityPolicy" ) { $FinalSecPol = $response.securityPolicies.SecurityPolicy } else { @@ -32452,9 +32631,9 @@ function Get-NsxSecurityPolicy { if ( -not $IncludeHidden ) { foreach ( $CurrSecPol in $FinalSecPol ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $CurrSecPol -Query 'child::extendedAttributes/extendedAttribute')) { - $hiddenattr = $CurrSecPol.extendedAttributes.extendedAttribute | where-object { $_.name -eq 'isHidden'} - if ( -not ($hiddenAttr.Value -eq 'true')){ + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $CurrSecPol -query 'child::extendedAttributes/extendedAttribute')) { + $hiddenattr = $CurrSecPol.extendedAttributes.extendedAttribute | Where-Object { $_.name -eq 'isHidden' } + if ( -not ($hiddenAttr.Value -eq 'true')) { $CurrSecPol } } @@ -32470,7 +32649,7 @@ function Get-NsxSecurityPolicy { end {} } -function New-NsxSecurityPolicy { +function New-NsxSecurityPolicy { <# .SYNOPSIS @@ -32649,38 +32828,38 @@ function New-NsxSecurityPolicy { [CmdletBinding()] param ( - [Parameter (Mandatory=$true)] - # The name of the newly created policy - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - # The description of the newly created policy - [ValidateNotNull()] - [string]$Description, - [Parameter (Mandatory=$false)] - # Security Policy Firewall Rule Spec as created by New-NsxSecurityPolicyFirewallRuleSpec - [ValidateScript({ ValidateSecPolFwSpec $_ })] - [System.Xml.XmlElement[]]$FirewallRuleSpec, - [Parameter (Mandatory=$false)] - # Guest Introspection Rule Spec as created by New-NsxSecurityPolicyGuestIntrospectionSpec - [ValidateScript({ ValidateSecPolGiSpec $_ })] - [System.Xml.XmlElement[]]$GuestIntrospectionSpec, - [Parameter (Mandatory=$false)] - # Network Introspection Rule Spec as created by New-NsxSecurityPolicyNetworkIntrospectionSpec - [ValidateScript({ ValidateSecPolNiSpec $_ })] - [System.Xml.XmlElement[]]$NetworkIntrospectionSpec, - [Parameter (Mandatory=$false)] - # Return only the objectId of the newly create policy (avoids an aditional get to the API to retrieve the newly created object) - [switch]$ReturnObjectIdOnly=$false, - [Parameter (Mandatory=$false)] - # Manually define the precedence number of the newly created policy. This defaults to the highest currently inuse precedence + 1000 (like the UI) - [int]$Precedence, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true)] + # The name of the newly created policy + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + # The description of the newly created policy + [ValidateNotNull()] + [string]$Description, + [Parameter (Mandatory = $false)] + # Security Policy Firewall Rule Spec as created by New-NsxSecurityPolicyFirewallRuleSpec + [ValidateScript( { ValidateSecPolFwSpec $_ })] + [System.Xml.XmlElement[]]$FirewallRuleSpec, + [Parameter (Mandatory = $false)] + # Guest Introspection Rule Spec as created by New-NsxSecurityPolicyGuestIntrospectionSpec + [ValidateScript( { ValidateSecPolGiSpec $_ })] + [System.Xml.XmlElement[]]$GuestIntrospectionSpec, + [Parameter (Mandatory = $false)] + # Network Introspection Rule Spec as created by New-NsxSecurityPolicyNetworkIntrospectionSpec + [ValidateScript( { ValidateSecPolNiSpec $_ })] + [System.Xml.XmlElement[]]$NetworkIntrospectionSpec, + [Parameter (Mandatory = $false)] + # Return only the objectId of the newly create policy (avoids an aditional get to the API to retrieve the newly created object) + [switch]$ReturnObjectIdOnly = $false, + [Parameter (Mandatory = $false)] + # Manually define the precedence number of the newly created policy. This defaults to the highest currently inuse precedence + 1000 (like the UI) + [int]$Precedence, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection - ) + ) begin { #Get current precedence and add 1000 @@ -32707,7 +32886,7 @@ function New-NsxSecurityPolicy { $xmlFwActionsByCategory = $xmlDoc.CreateElement("actionsByCategory") $null = $SecurityPolicy.appendChild($xmlFwActionsByCategory) Add-XmlElement -xmlRoot $xmlFwActionsByCategory -xmlElementName "category" -xmlElementText "firewall" - foreach ($rule in $FirewallRuleSpec){ + foreach ($rule in $FirewallRuleSpec) { #Import the new fw node $null = $xmlFwActionsByCategory.AppendChild($xmlFwActionsByCategory.OwnerDocument.ImportNode($rule, $true)) } @@ -32718,7 +32897,7 @@ function New-NsxSecurityPolicy { $xmlEndpointActionsByCategory = $xmlDoc.CreateElement("actionsByCategory") $null = $SecurityPolicy.appendChild($xmlEndpointActionsByCategory) Add-XmlElement -xmlRoot $xmlEndpointActionsByCategory -xmlElementName "category" -xmlElementText "endpoint" - foreach ($rule in $GuestIntrospectionSpec){ + foreach ($rule in $GuestIntrospectionSpec) { #Import the new GI node $null = $xmlEndpointActionsByCategory.AppendChild($xmlEndpointActionsByCategory.OwnerDocument.ImportNode($rule, $true)) } @@ -32729,7 +32908,7 @@ function New-NsxSecurityPolicy { $xmlNetworkIntrospectionActionsByCategory = $xmlDoc.CreateElement("actionsByCategory") $null = $SecurityPolicy.appendChild($xmlNetworkIntrospectionActionsByCategory) Add-XmlElement -xmlRoot $xmlNetworkIntrospectionActionsByCategory -xmlElementName "category" -xmlElementText "traffic_steering" - foreach ($rule in $NetworkIntrospectionSpec){ + foreach ($rule in $NetworkIntrospectionSpec) { #Import the new NI node $null = $xmlNetworkIntrospectionActionsByCategory.AppendChild($xmlNetworkIntrospectionActionsByCategory.OwnerDocument.ImportNode($rule, $true)) } @@ -32739,14 +32918,14 @@ function New-NsxSecurityPolicy { #Do the post $body = $SecurityPolicy.OuterXml $URI = "/api/2.0/services/policy/securitypolicy" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection - if ($response.StatusCode -eq "201"){ + if ($response.StatusCode -eq "201") { if ($ReturnObjectIdOnly) { $response.content } else { - Get-NsxSecurityPolicy -objectId $response.content -connection $connection + Get-NsxSecurityPolicy -ObjectId $response.content -Connection $connection } } } @@ -32795,38 +32974,38 @@ function Set-NsxSecurityPolicy { updated XML back. Any valid XML changes can be pushed this way. #> - [CmdletBinding(DefaultParameterSetName="XML")] + [CmdletBinding(DefaultParameterSetName = "XML")] param ( - [Parameter(Mandatory=$true, ValueFromPipeLine=$true)] - # Security Policy object to update - $Policy, + [Parameter(Mandatory = $true, ValueFromPipeLine = $true)] + # Security Policy object to update + $Policy, [Parameter()] - # Disable confirmation prompt - [switch]$NoConfirm, - [Parameter(ParameterSetName="Default")] - # Configure the policies name - [ValidateNotNullorEmpty()] - [string]$Name, - [Parameter(ParameterSetName="Default")] - # Configure the policies description - [ValidateNotNullorEmpty()] - [string]$Description, - [Parameter(ParameterSetName="Default")] - # Configure inheritance for the specified policy - [ValidateScript( { ValidateSecurityPolicy $_ })] - [object]$InheritPolicy, - [Parameter(ParameterSetName="Default")] - # Disable inheritance for the specified policy - [switch]$DisableInheritance, - [Parameter(ParameterSetName="Default")] - # Configure the policies weight (precedence) - [ValidateNotNullorEmpty()] - [Alias("Precedence")] - [string]$Weight, - [Parameter(Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + # Disable confirmation prompt + [switch]$NoConfirm, + [Parameter(ParameterSetName = "Default")] + # Configure the policies name + [ValidateNotNullorEmpty()] + [string]$Name, + [Parameter(ParameterSetName = "Default")] + # Configure the policies description + [ValidateNotNullorEmpty()] + [string]$Description, + [Parameter(ParameterSetName = "Default")] + # Configure inheritance for the specified policy + [ValidateScript( { ValidateSecurityPolicy $_ })] + [object]$InheritPolicy, + [Parameter(ParameterSetName = "Default")] + # Disable inheritance for the specified policy + [switch]$DisableInheritance, + [Parameter(ParameterSetName = "Default")] + # Configure the policies weight (precedence) + [ValidateNotNullorEmpty()] + [Alias("Precedence")] + [string]$Weight, + [Parameter(Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) Begin {} @@ -32837,58 +33016,58 @@ function Set-NsxSecurityPolicy { # Update Name if ( $PSBoundParameters.ContainsKey("Name")) { - if ( invoke-xpathquery -node $_Policy -querymethod SelectSingleNode -Query "child::name" ) { + if ( Invoke-XpathQuery -Node $_Policy -QueryMethod SelectSingleNode -query "child::name" ) { $_Policy.Name = $name } else { - Add-XmlElement -xmlroot $_Policy -xmlElementName "name" -xmlElementText $name + Add-XmlElement -xmlRoot $_Policy -xmlElementName "name" -xmlElementText $name } } # Update Description if ( $PSBoundParameters.ContainsKey("Description")) { - if ( invoke-xpathquery -node $_Policy -querymethod SelectSingleNode -Query "child::description" ) { + if ( Invoke-XpathQuery -Node $_Policy -QueryMethod SelectSingleNode -query "child::description" ) { $_Policy.description = $description } else { - Add-XmlElement -xmlroot $_Policy -xmlElementName "description" -xmlElementText $description + Add-XmlElement -xmlRoot $_Policy -xmlElementName "description" -xmlElementText $description } } # Update Weight (precedence) if ( $PSBoundParameters.ContainsKey("Weight")) { - if ( invoke-xpathquery -node $_Policy -querymethod SelectSingleNode -Query "child::precedence" ) { + if ( Invoke-XpathQuery -Node $_Policy -QueryMethod SelectSingleNode -query "child::precedence" ) { $_Policy.precedence = $weight } else { - Add-XmlElement -xmlroot $_Policy -xmlElementName "precedence" -xmlElementText $weight + Add-XmlElement -xmlRoot $_Policy -xmlElementName "precedence" -xmlElementText $weight } } # Disable inheritance if ( $DisableInheritance) { - $Parentnode = invoke-xpathquery -node $_Policy -querymethod SelectSingleNode -Query "child::parent" + $Parentnode = Invoke-XpathQuery -Node $_Policy -QueryMethod SelectSingleNode -query "child::parent" if ( $Parentnode ) { $null = $_Policy.RemoveChild($Parentnode) } else { - write-warning "Specified policy does not have inheritance enabled" + Write-Warning "Specified policy does not have inheritance enabled" } } # Update inheritance if ( $PSBoundParameters.ContainsKey("InheritPolicy")) { - $ParentNode = invoke-xpathquery -node $_Policy -querymethod SelectSingleNode -Query "child::parent" + $ParentNode = Invoke-XpathQuery -Node $_Policy -QueryMethod SelectSingleNode -query "child::parent" if ( $ParentNode ) { $null = $_Policy.RemoveChild($Parentnode) } $ParentNode = $_Policy.OwnerDocument.CreateElement("parent") $null = $_Policy.appendChild($ParentNode) - Add-XmlElement -xmlroot $ParentNode -xmlElementName "objectId" -xmlElementText $InheritPolicy.objectId + Add-XmlElement -xmlRoot $ParentNode -xmlElementName "objectId" -xmlElementText $InheritPolicy.objectId } if ( -Not $NoConfirm ) { - $message = "Modification of the specified policy will affect the security posture of all Security Groups that have it applied." + $message = "Modification of the specified policy will affect the security posture of all Security Groups that have it applied." $question = "Proceed with update of policy $($_Policy.objectId)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -32899,12 +33078,12 @@ function Set-NsxSecurityPolicy { } else { $decision = 0 } if ($decision -eq 0) { - write-debug "$($MyInvocation.MyCommand.Name) : Putting updated policy from the policy cache for $($_Policy.objectId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Putting updated policy from the policy cache for $($_Policy.objectId)" #Do the post $body = $_Policy.OuterXml $URI = "/api/2.0/services/policy/securitypolicy/$($_Policy.objectId)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - if ($response.StatusCode -eq "200"){ + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + if ($response.StatusCode -eq "200") { [System.Xml.XmlDocument]$Doc = $response.content $Doc.securityPolicy } @@ -32934,36 +33113,36 @@ function Remove-NsxSecurityPolicy { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - # Security Policy to Remove. - [ValidateScript( { ValidateSecurityPolicy $_ })] - [System.Xml.XmlElement]$SecurityPolicy, - [Parameter (Mandatory=$False)] - # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False)] - # Force removal, even if the policy is in use. - [switch]$force=$false, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + # Security Policy to Remove. + [ValidateScript( { ValidateSecurityPolicy $_ })] + [System.Xml.XmlElement]$SecurityPolicy, + [Parameter (Mandatory = $False)] + # Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False)] + # Force removal, even if the policy is in use. + [switch]$force = $false, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { - if ((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $SecurityPolicy -Query "descendant::extendedAttributes/extendedAttribute[name=`"isHidden`" and value=`"true`"]") -and ( -not $force)) { - write-warning "Not removing $($SecurityPolicy.Name) as it is set as hidden. Use -Force to force deletion." + if ((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $SecurityPolicy -query "descendant::extendedAttributes/extendedAttribute[name=`"isHidden`" and value=`"true`"]") -and ( -not $force)) { + Write-Warning "Not removing $($SecurityPolicy.Name) as it is set as hidden. Use -Force to force deletion." } else { if ( $confirm ) { - $message = "Security Policy removal is permanent." + $message = "Security Policy removal is permanent." $question = "Proceed with removal of Security Policy $($SecurityPolicy.Name)?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -32981,9 +33160,9 @@ function Remove-NsxSecurityPolicy { $URI = "/api/2.0/services/policy/securitypolicy/$($SecurityPolicy.ObjectId)?force=false" } - Write-Progress -activity "Remove Security Policy $($SecurityPolicy.Name)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - write-progress -activity "Remove Security Policy $($SecurityPolicy.Name)" -completed + Write-Progress -Activity "Remove Security Policy $($SecurityPolicy.Name)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove Security Policy $($SecurityPolicy.Name)" -Completed } } @@ -33082,44 +33261,44 @@ function New-NsxSecurityPolicyFirewallRuleSpec { [CmdletBinding(DefaultParameterSetName = "SrcDest")] param ( - [Parameter (Mandatory=$true)] - # Name of the newly created firewall rule - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - # Description of the newly created firewall rule - [ValidateNotNull()] - [string]$Description, - [Parameter (Mandatory=$false)] - # Specify -disabled to create a rule as disabled. Rules default to enabled. - [switch]$Disabled, - [Parameter (Mandatory=$false,ParameterSetName="Direction")] - # Security Group that defines the source or destination of the rule (depending on -Direction). Security Group is mandatory if direction is Inbound or Outbound. - [ValidateScript({ ValidateSecurityGroup $_ })] - [object[]]$SecurityGroup, - [Parameter (Mandatory=$true,ParameterSetName="Direction")] - # Direction that dictates if the specified security group is the source or destination of the rule. Inbound : Security Group defines the source. Outbound : Security Group defines the destination. - [ValidateSet("Inbound","Outbound", "Intra")] - [string]$Direction, - [Parameter (Mandatory=$false,ParameterSetName="SrcDest")] - # Source of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' - [ValidateScript({ ValidateSPFirewallSrcDest $_ })] - [object[]]$Source = "PoliciesSecurityGroup", - [Parameter (Mandatory=$false,ParameterSetName="SrcDest")] - # Destination of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' - [ValidateScript({ ValidateSPFirewallSrcDest $_ })] - [object[]]$Destination = "PoliciesSecurityGroup", - [Parameter (Mandatory=$false)] - # Service defined by the rule. Defaults to 'any'. Can be any valid PowerNSX Service object. - [ValidateScript({ ValidateServiceOrServiceGroup $_ })] - [object[]]$Service, - [Parameter (Mandatory=$false)] - # Enable logging. Defaults to disabled. - [switch]$EnableLogging, - [Parameter (Mandatory=$false)] - # Rule action. Defaults to Allow - [ValidateSet("Allow","Block", "Reject")] - [string]$Action = "Allow" + [Parameter (Mandatory = $true)] + # Name of the newly created firewall rule + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + # Description of the newly created firewall rule + [ValidateNotNull()] + [string]$Description, + [Parameter (Mandatory = $false)] + # Specify -disabled to create a rule as disabled. Rules default to enabled. + [switch]$Disabled, + [Parameter (Mandatory = $false, ParameterSetName = "Direction")] + # Security Group that defines the source or destination of the rule (depending on -Direction). Security Group is mandatory if direction is Inbound or Outbound. + [ValidateScript( { ValidateSecurityGroup $_ })] + [object[]]$SecurityGroup, + [Parameter (Mandatory = $true, ParameterSetName = "Direction")] + # Direction that dictates if the specified security group is the source or destination of the rule. Inbound : Security Group defines the source. Outbound : Security Group defines the destination. + [ValidateSet("Inbound", "Outbound", "Intra")] + [string]$Direction, + [Parameter (Mandatory = $false, ParameterSetName = "SrcDest")] + # Source of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' + [ValidateScript( { ValidateSPFirewallSrcDest $_ })] + [object[]]$Source = "PoliciesSecurityGroup", + [Parameter (Mandatory = $false, ParameterSetName = "SrcDest")] + # Destination of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' + [ValidateScript( { ValidateSPFirewallSrcDest $_ })] + [object[]]$Destination = "PoliciesSecurityGroup", + [Parameter (Mandatory = $false)] + # Service defined by the rule. Defaults to 'any'. Can be any valid PowerNSX Service object. + [ValidateScript( { ValidateServiceOrServiceGroup $_ })] + [object[]]$Service, + [Parameter (Mandatory = $false)] + # Enable logging. Defaults to disabled. + [switch]$EnableLogging, + [Parameter (Mandatory = $false)] + # Rule action. Defaults to Allow + [ValidateSet("Allow", "Block", "Reject")] + [string]$Action = "Allow" ) begin { @@ -33174,7 +33353,7 @@ function New-NsxSecurityPolicyFirewallRuleSpec { #Create the doc and root elem. We are only defining the action elem and down. $xmlDoc = New-Object System.XML.XMLDocument $xmlRoot = $xmlDoc.CreateElement("action") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null $xmlRoot.SetAttribute("class", "firewallSecurityAction") #Basic elements @@ -33183,16 +33362,16 @@ function New-NsxSecurityPolicyFirewallRuleSpec { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "logged" -xmlElementText $EnableLogging.ToString().ToLower() Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "action" -xmlElementText $Action.ToLower() Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "direction" -xmlElementText $Direction.ToLower() - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isEnabled" -xmlElementText ( -not $Disabled ) + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isEnabled" -xmlElementText ( -not $Disabled ) if ( $PSBoundParameters.ContainsKey("description")) { - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description } #Iterate securitygroups. 'PoliciesSecurityGroups' and 'Any' are taken care of in begin block. SecurityGroups is only popoulated if we really do have some to walk. foreach ( $Group in $SecurityGroup) { $xmlSecurityGroup = $xmlDoc.CreateElement("secondarySecurityGroup") - $xmlRoot.appendChild($xmlSecurityGroup) | out-null + $xmlRoot.appendChild($xmlSecurityGroup) | Out-Null Add-XmlElement -xmlRoot $xmlSecurityGroup -xmlElementName "objectId" -xmlElementText $group.objectId } @@ -33200,14 +33379,14 @@ function New-NsxSecurityPolicyFirewallRuleSpec { #Iterate over services. if ( $PsBoundParameters.ContainsKey('Service') ) { $xmlApplications = $xmlDoc.CreateElement("applications") - $xmlRoot.appendChild($xmlApplications) | out-null + $xmlRoot.appendChild($xmlApplications) | Out-Null foreach ( $svc in $service) { switch ($svc.objectTypeName) { - "application" { $xmlElementName = "application"} - "applicationgroup" { $xmlElementName = "applicationGroup"} + "application" { $xmlElementName = "application" } + "applicationgroup" { $xmlElementName = "applicationGroup" } } $xmlApplicationsObject = $xmlDoc.CreateElement($xmlElementName) - $xmlApplications.appendChild($xmlApplicationsObject) | out-null + $xmlApplications.appendChild($xmlApplicationsObject) | Out-Null Add-XmlElement -xmlRoot $xmlApplicationsObject -xmlElementName "objectId" -xmlElementText $svc.objectId } } @@ -33308,47 +33487,47 @@ function New-NsxSecurityPolicyNetworkIntrospectionSpec { [CmdletBinding(DefaultParameterSetName = "SrcDest")] param ( - [Parameter (Mandatory=$true)] - # Name of the newly created network introspection rule - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - # Description of the newly created network introspection rule - [ValidateNotNull()] - [string]$Description, - [Parameter (Mandatory=$false)] - # Specify -disabled to create a rule as disabled. Rules default to enabled. - [switch]$Disabled, - [Parameter (Mandatory=$false,ParameterSetName="Direction")] - # Security Group that defines the source or destination of the rule (depending on -Direction). Security Group is mandatory if direction is Inbound or Outbound. - [ValidateScript({ ValidateSecurityGroup $_ })] - [object[]]$SecurityGroup, - [Parameter (Mandatory=$true,ParameterSetName="Direction")] - # Direction that dictates if the specified security group is the source or destination of the rule. Inbound : Security Group defines the source. Outbound : Security Group defines the destination. - [ValidateSet("Inbound","Outbound", "Intra")] - [string]$Direction, - [Parameter (Mandatory=$false,ParameterSetName="SrcDest")] - # Source of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' - [ValidateScript({ ValidateSPFirewallSrcDest $_ })] - [object[]]$Source = "PoliciesSecurityGroup", - [Parameter (Mandatory=$false,ParameterSetName="SrcDest")] - # Destination of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' - [ValidateScript({ ValidateSPFirewallSrcDest $_ })] - [object[]]$Destination = "PoliciesSecurityGroup", - [Parameter (Mandatory=$false)] - # Service defined by the rule. Defaults to 'any'. Can be any valid PowerNSX Service object. - [ValidateScript({ ValidateService $_ })] - [object[]]$Service, - [Parameter (Mandatory=$true)] - # Service Profile object as retrieved using Get-NsxServiceProfile (as defined in Service Profile section of a specific Service Definition in the NSX UI). - [ValidateScript({ ValidateServiceProfile $_ })] - [System.Xml.XmlElement]$ServiceProfile, - [Parameter (Mandatory=$false)] - # Enable logging. Defaults to disabled. - [switch]$EnableLogging, - [Parameter (Mandatory=$false)] - # Disable redirection for this rule. Defaults to $false (Rule is created with redirection enabled). - [switch]$DisableRedirection + [Parameter (Mandatory = $true)] + # Name of the newly created network introspection rule + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + # Description of the newly created network introspection rule + [ValidateNotNull()] + [string]$Description, + [Parameter (Mandatory = $false)] + # Specify -disabled to create a rule as disabled. Rules default to enabled. + [switch]$Disabled, + [Parameter (Mandatory = $false, ParameterSetName = "Direction")] + # Security Group that defines the source or destination of the rule (depending on -Direction). Security Group is mandatory if direction is Inbound or Outbound. + [ValidateScript( { ValidateSecurityGroup $_ })] + [object[]]$SecurityGroup, + [Parameter (Mandatory = $true, ParameterSetName = "Direction")] + # Direction that dictates if the specified security group is the source or destination of the rule. Inbound : Security Group defines the source. Outbound : Security Group defines the destination. + [ValidateSet("Inbound", "Outbound", "Intra")] + [string]$Direction, + [Parameter (Mandatory = $false, ParameterSetName = "SrcDest")] + # Source of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' + [ValidateScript( { ValidateSPFirewallSrcDest $_ })] + [object[]]$Source = "PoliciesSecurityGroup", + [Parameter (Mandatory = $false, ParameterSetName = "SrcDest")] + # Destination of the rule. Can be 'Any', 'PoliciesSecurityGroup', or a valid PowerNSX securitygroup object. At least one of source or destination MUST be 'PoliciesSecurityGroup'. Defaults to 'PoliciesSecurityGroup' + [ValidateScript( { ValidateSPFirewallSrcDest $_ })] + [object[]]$Destination = "PoliciesSecurityGroup", + [Parameter (Mandatory = $false)] + # Service defined by the rule. Defaults to 'any'. Can be any valid PowerNSX Service object. + [ValidateScript( { ValidateService $_ })] + [object[]]$Service, + [Parameter (Mandatory = $true)] + # Service Profile object as retrieved using Get-NsxServiceProfile (as defined in Service Profile section of a specific Service Definition in the NSX UI). + [ValidateScript( { ValidateServiceProfile $_ })] + [System.Xml.XmlElement]$ServiceProfile, + [Parameter (Mandatory = $false)] + # Enable logging. Defaults to disabled. + [switch]$EnableLogging, + [Parameter (Mandatory = $false)] + # Disable redirection for this rule. Defaults to $false (Rule is created with redirection enabled). + [switch]$DisableRedirection ) begin { @@ -33403,7 +33582,7 @@ function New-NsxSecurityPolicyNetworkIntrospectionSpec { #Create the doc and root elem. We are only defining the action elem and down. $xmlDoc = New-Object System.XML.XMLDocument $xmlRoot = $xmlDoc.CreateElement("action") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null $xmlRoot.SetAttribute("class", "trafficSteeringSecurityAction") #Basic elements @@ -33411,11 +33590,11 @@ function New-NsxSecurityPolicyNetworkIntrospectionSpec { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "logged" -xmlElementText $EnableLogging.ToString().ToLower() Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "direction" -xmlElementText $Direction.ToLower() - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isEnabled" -xmlElementText ( -not $Disabled ) - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "redirect" -xmlElementText ( -not $DisableRedirection ) + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isEnabled" -xmlElementText ( -not $Disabled ) + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "redirect" -xmlElementText ( -not $DisableRedirection ) if ( $PSBoundParameters.ContainsKey("description")) { - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description } $xmlServiceProfile = $xmlDoc.CreateElement("serviceProfile") @@ -33425,7 +33604,7 @@ function New-NsxSecurityPolicyNetworkIntrospectionSpec { #Iterate securitygroups. 'PoliciesSecurityGroups' and 'Any' are taken care of in begin block. SecurityGroups is only popoulated if we really do have some to walk. foreach ( $Group in $SecurityGroup) { $xmlSecurityGroup = $xmlDoc.CreateElement("secondarySecurityGroup") - $xmlRoot.appendChild($xmlSecurityGroup) | out-null + $xmlRoot.appendChild($xmlSecurityGroup) | Out-Null Add-XmlElement -xmlRoot $xmlSecurityGroup -xmlElementName "objectId" -xmlElementText $group.objectId } @@ -33433,14 +33612,14 @@ function New-NsxSecurityPolicyNetworkIntrospectionSpec { #Iterate over services. if ( $PsBoundParameters.ContainsKey('Service') ) { $xmlApplications = $xmlDoc.CreateElement("applications") - $xmlRoot.appendChild($xmlApplications) | out-null + $xmlRoot.appendChild($xmlApplications) | Out-Null foreach ( $svc in $service) { switch ($svc.objectTypeName) { - "application" { $xmlElementName = "application"} - "applicationgroup" { $xmlElementName = "applicationGroup"} + "application" { $xmlElementName = "application" } + "applicationgroup" { $xmlElementName = "applicationGroup" } } $xmlApplicationsObject = $xmlDoc.CreateElement($xmlElementName) - $xmlApplications.appendChild($xmlApplicationsObject) | out-null + $xmlApplications.appendChild($xmlApplicationsObject) | Out-Null Add-XmlElement -xmlRoot $xmlApplicationsObject -xmlElementName "objectId" -xmlElementText $svc.objectId } } @@ -33492,39 +33671,39 @@ function New-NsxSecurityPolicyGuestIntrospectionSpec { Create a new Guest Introspection 'Apply' rule based on a Service Definition called ServiceDefinition1, and Service Profile Profile1 #> - [CmdletBinding(DefaultParameterSetName="Apply")] - param ( - - [Parameter (Mandatory=$false)] - # Name of the newly created GI rule. - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - # Description of the newly created rule. - [ValidateNotNull()] - [string]$Description, - [Parameter (Mandatory=$false)] - # Create the rule as disabled. - [switch]$Disabled, - [Parameter (Mandatory=$false)] - # Create the rule as Enforced (Rule is not enforced by default as per UI default) - [switch]$Enforced, - [Parameter (Mandatory=$true, ParameterSetName="Block")] - # Service Type of the Block rule. Accepts AntiVirus, VulnerabilityManagement or FileIntegrityMonitoring - [ValidateSet("AntiVirus", "VulnerabilityManagement", "FileIntegrityMonitoring")] - [string]$ServiceType, - [Parameter (Mandatory=$true, ParameterSetName="Apply")] - # Service Definition object as retrieved using Get-NsxServiceDefinition (as defined in Service Definitions section of the NSX UI). - [ValidateScript({ ValidateServiceDefinition $_ })] - [System.Xml.XmlElement]$ServiceDefinition, - [Parameter (Mandatory=$false, ParameterSetName="Apply")] - # Service Profile object as retrieved using Get-NsxServiceProfile (as defined in Service Profile section of a specific Service Definition in the NSX UI). - [ValidateScript({ ValidateServiceProfile $_ })] - [System.Xml.XmlElement]$ServiceProfile, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdletBinding(DefaultParameterSetName = "Apply")] + param ( + + [Parameter (Mandatory = $false)] + # Name of the newly created GI rule. + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + # Description of the newly created rule. + [ValidateNotNull()] + [string]$Description, + [Parameter (Mandatory = $false)] + # Create the rule as disabled. + [switch]$Disabled, + [Parameter (Mandatory = $false)] + # Create the rule as Enforced (Rule is not enforced by default as per UI default) + [switch]$Enforced, + [Parameter (Mandatory = $true, ParameterSetName = "Block")] + # Service Type of the Block rule. Accepts AntiVirus, VulnerabilityManagement or FileIntegrityMonitoring + [ValidateSet("AntiVirus", "VulnerabilityManagement", "FileIntegrityMonitoring")] + [string]$ServiceType, + [Parameter (Mandatory = $true, ParameterSetName = "Apply")] + # Service Definition object as retrieved using Get-NsxServiceDefinition (as defined in Service Definitions section of the NSX UI). + [ValidateScript( { ValidateServiceDefinition $_ })] + [System.Xml.XmlElement]$ServiceDefinition, + [Parameter (Mandatory = $false, ParameterSetName = "Apply")] + # Service Profile object as retrieved using Get-NsxServiceProfile (as defined in Service Profile section of a specific Service Definition in the NSX UI). + [ValidateScript( { ValidateServiceProfile $_ })] + [System.Xml.XmlElement]$ServiceProfile, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -33534,12 +33713,12 @@ function New-NsxSecurityPolicyGuestIntrospectionSpec { #Create the doc and root elem. We are only defining the action elem and down. $xmlDoc = New-Object System.XML.XMLDocument $xmlRoot = $xmlDoc.CreateElement("action") - $xmlDoc.appendChild($xmlRoot) | out-null + $xmlDoc.appendChild($xmlRoot) | Out-Null $xmlRoot.SetAttribute("class", "endpointSecurityAction") #Basic mandatory elements Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "category" -xmlElementText "endpoint" - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isEnabled" -xmlElementText ( -not $Disabled ) + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isEnabled" -xmlElementText ( -not $Disabled ) Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "isActionEnforced" -xmlElementText $Enforced #Optional elements @@ -33547,7 +33726,7 @@ function New-NsxSecurityPolicyGuestIntrospectionSpec { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "name" -xmlElementText $Name } if ( $PSBoundParameters.ContainsKey("description")) { - Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description + Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "description" -xmlElementText $Description } @@ -33555,7 +33734,7 @@ function New-NsxSecurityPolicyGuestIntrospectionSpec { switch ( $PSCmdlet.ParameterSetName ) { "Apply" { Add-XmlElement -xmlRoot $xmlRoot -xmlElementName "serviceId" -xmlElementText $ServiceDefinition.objectId - if ( $PSBoundParameters.ContainsKey("ServiceProfile") ){ + if ( $PSBoundParameters.ContainsKey("ServiceProfile") ) { $xmlServiceProfile = $xmlDoc.CreateElement("serviceProfile") $null = $xmlRoot.AppendChild($xmlServiceProfile) Add-XmlElement -xmlRoot $xmlServiceProfile -xmlElementName "objectId" $ServiceProfile.objectId @@ -33571,7 +33750,7 @@ function New-NsxSecurityPolicyGuestIntrospectionSpec { #Just emit the resulting xml. $xmlRoot - } + } end {} } @@ -33604,20 +33783,20 @@ function Get-NsxServiceDefinition { Retrieve the service definition with the specified Name. #> - [CmdletBinding(DefaultParameterSetName="Name")] + [CmdletBinding(DefaultParameterSetName = "Name")] param ( - [Parameter(Mandatory=$false, ParameterSetName="Name", Position=1)] - # Name of the Service Definition to retrieve. - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter(Mandatory=$false, ParameterSetName="ObjectId")] - # ObjectId of the Service Definition to retrieve. - [ValidateNotNullOrEmpty()] - [string]$ObjectId, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter(Mandatory = $false, ParameterSetName = "Name", Position = 1)] + # Name of the Service Definition to retrieve. + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter(Mandatory = $false, ParameterSetName = "ObjectId")] + # ObjectId of the Service Definition to retrieve. + [ValidateNotNullOrEmpty()] + [string]$ObjectId, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) switch ( $PSCmdlet.ParameterSetName ) { @@ -33625,7 +33804,7 @@ function Get-NsxServiceDefinition { $URI = "/api/2.0/si/service/$objectId" try { - $response = invoke-nsxwebrequest -method Get -Uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method Get -URI $URI -connection $connection if ( $response ) { [xml]$return = $response.content $return.service @@ -33640,7 +33819,7 @@ function Get-NsxServiceDefinition { $URI = "/api/2.0/si/services" try { - $response = invoke-nsxwebrequest -method Get -Uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method Get -URI $URI -connection $connection if ( $response ) { [xml]$return = $response.content if ( $PSBoundParameters.ContainsKey("Name")) { @@ -33696,27 +33875,27 @@ function Get-NsxServiceProfile { #> - [CmdletBinding(DefaultParameterSetName="Name")] + [CmdletBinding(DefaultParameterSetName = "Name")] param ( - [Parameter(Mandatory=$false, ValueFromPipeline=$true, ParameterSetName="ServiceDefinition")] - # Service Definition as returned by Get-NsxServiceDefinition. - [ValidateScript({ ValidateServiceDefinition $_ })] - [System.Xml.XmlElement]$ServiceDefinition, - [Parameter(Mandatory=$false, ParameterSetName="Name", Position=1)] - # Name of the Service Profile to retrieve. - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter(Mandatory=$false, ParameterSetName="ObjectId")] - # ObjectId of the Service Profile to retrieve. - [ValidateNotNullOrEmpty()] - [string]$ObjectId, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object. - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter(Mandatory = $false, ValueFromPipeline = $true, ParameterSetName = "ServiceDefinition")] + # Service Definition as returned by Get-NsxServiceDefinition. + [ValidateScript( { ValidateServiceDefinition $_ })] + [System.Xml.XmlElement]$ServiceDefinition, + [Parameter(Mandatory = $false, ParameterSetName = "Name", Position = 1)] + # Name of the Service Profile to retrieve. + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter(Mandatory = $false, ParameterSetName = "ObjectId")] + # ObjectId of the Service Profile to retrieve. + [ValidateNotNullOrEmpty()] + [string]$ObjectId, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object. + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) - Begin{} + Begin {} Process { switch ( $PSCmdlet.ParameterSetName ) { @@ -33724,7 +33903,7 @@ function Get-NsxServiceProfile { $URI = "/api/2.0/si/serviceprofile/$objectId" try { - $response = invoke-nsxwebrequest -method Get -Uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method Get -URI $URI -connection $connection if ( $response ) { [xml]$return = $response.content $return.serviceProfile @@ -33738,10 +33917,10 @@ function Get-NsxServiceProfile { $URI = "/api/2.0/si/serviceprofiles" try { - $response = invoke-nsxwebrequest -method Get -Uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method Get -URI $URI -connection $connection if ( $response ) { [xml]$return = $response.content - if ( invoke-xpathquery -node $return -querymethod SelectSingleNode -query ("child::serviceProfiles/serviceProfile")) { + if ( Invoke-XpathQuery -Node $return -QueryMethod SelectSingleNode -query ("child::serviceProfiles/serviceProfile")) { if ( $PSBoundParameters.ContainsKey("Name")) { $return.serviceProfiles.serviceProfile | Where-Object { $_.name -eq $Name } @@ -33762,10 +33941,10 @@ function Get-NsxServiceProfile { } } - End{} + End {} } -function New-NsxSecurityPolicyAssignment { +function New-NsxSecurityPolicyAssignment { <# .SYNOPSIS @@ -33794,18 +33973,18 @@ function New-NsxSecurityPolicyAssignment { [CmdletBinding()] param ( - [Parameter (Mandatory=$True,ValueFromPipeline=$True)] - # Security Policy to be applied. - [ValidateScript({ ValidateSecurityPolicy $_ })] - [System.Xml.XmlElement]$SecurityPolicy, - [Parameter (Mandatory=$false)] - # Security Group to which to apply the specified policy. Can specify a collection of security groups to perform assignment of policy to multiple groups. - [ValidateScript({ ValidateSecurityGroup $_ })] - [System.Xml.XmlElement[]]$SecurityGroup, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy to be applied. + [ValidateScript( { ValidateSecurityPolicy $_ })] + [System.Xml.XmlElement]$SecurityPolicy, + [Parameter (Mandatory = $false)] + # Security Group to which to apply the specified policy. Can specify a collection of security groups to perform assignment of policy to multiple groups. + [ValidateScript( { ValidateSecurityGroup $_ })] + [System.Xml.XmlElement[]]$SecurityGroup, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -33825,9 +34004,9 @@ function New-NsxSecurityPolicyAssignment { #Do the post $body = $_SecurityPolicy.OuterXml $URI = "/api/2.0/services/policy/securitypolicy/$($_SecurityPolicy.objectId)" - Write-Progress -activity "Updating SecurityGroup bindings for Security Policy $($SecurityPolicy.Name)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - Write-Progress -activity "Updating SecurityGroup bindings for Security Policy $($SecurityPolicy.Name)" -completed + Write-Progress -Activity "Updating SecurityGroup bindings for Security Policy $($SecurityPolicy.Name)" + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating SecurityGroup bindings for Security Policy $($SecurityPolicy.Name)" -Completed [xml]$return = $response.content $return.securityPolicy @@ -33836,7 +34015,7 @@ function New-NsxSecurityPolicyAssignment { end {} } -function Remove-NsxSecurityPolicyAssignment { +function Remove-NsxSecurityPolicyAssignment { <# .SYNOPSIS @@ -33860,19 +34039,19 @@ function Remove-NsxSecurityPolicyAssignment { [CmdletBinding()] param ( - [Parameter (Mandatory=$True,ValueFromPipeline=$True)] - # Security Policy whose application will be removed from the specified Security Group - [ValidateScript({ ValidateSecurityPolicy $_ })] - [System.Xml.XmlElement]$SecurityPolicy, - [Parameter (Mandatory=$true)] - # Security Group to remove the specified Security Policy from its applied policies list. - [ValidateScript({ ValidateSecurityGroup $_ })] - [System.Xml.XmlElement[]]$SecurityGroup, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy whose application will be removed from the specified Security Group + [ValidateScript( { ValidateSecurityPolicy $_ })] + [System.Xml.XmlElement]$SecurityPolicy, + [Parameter (Mandatory = $true)] + # Security Group to remove the specified Security Policy from its applied policies list. + [ValidateScript( { ValidateSecurityGroup $_ })] + [System.Xml.XmlElement[]]$SecurityGroup, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin {} @@ -33882,14 +34061,14 @@ function Remove-NsxSecurityPolicyAssignment { $ModifiedSP = $false #Check that the Sp we are processing is applied to at least one group. - if (invoke-xpathquery -node $SecurityPolicy -QueryMethod SelectSingleNode -Query "child::securityGroupBinding") { + if (Invoke-XpathQuery -Node $SecurityPolicy -QueryMethod SelectSingleNode -query "child::securityGroupBinding") { #Clone the node to avoid modifying input object. $_SecurityPolicy = $SecurityPolicy.CloneNode($true) #Iterate SecurityGroups, find and remove the ones that match the current SecurityGroup - foreach ($Group in $SecurityGroup){ - $CurrGroupBindingNode = invoke-xpathquery -node $_SecurityPolicy -QueryMethod SelectSingleNode -Query "child::securityGroupBinding[objectId=`'$($Group.objectId)`']" + foreach ($Group in $SecurityGroup) { + $CurrGroupBindingNode = Invoke-XpathQuery -Node $_SecurityPolicy -QueryMethod SelectSingleNode -query "child::securityGroupBinding[objectId=`'$($Group.objectId)`']" if ($CurrGroupBindingNode) { $null = $_SecurityPolicy.RemoveChild($CurrGroupBindingNode) $ModifiedSP = $true @@ -33897,22 +34076,22 @@ function Remove-NsxSecurityPolicyAssignment { else { #Let the user know there was nothing to do, but dont throw...want to make sure the pipeline continues. - write-warning "Security Policy $($SecurityPolicy.Name) ($($SecurityPolicy.objectId)) is not applied to Security Group $($Group.Name) ($($Group.objectId))" + Write-Warning "Security Policy $($SecurityPolicy.Name) ($($SecurityPolicy.objectId)) is not applied to Security Group $($Group.Name) ($($Group.objectId))" } } } - Else{ + Else { #Again, we dont throw, want to make sure the pipeline continues. - write-warning "No SecurityGroups are assoicated with SecurityPolicy: $($SecurityPolicy.name)" + Write-Warning "No SecurityGroups are assoicated with SecurityPolicy: $($SecurityPolicy.name)" } #Do the post if ( $ModifiedSP ) { $body = $_SecurityPolicy.OuterXml $URI = "/api/2.0/services/policy/securitypolicy/$($_SecurityPolicy.objectId)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - if ($response.StatusCode -eq "200"){ + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + if ($response.StatusCode -eq "200") { [xml]$return = $response.content $return.securityPolicy } @@ -33976,58 +34155,58 @@ function Get-NsxSecurityPolicyRule { #> - [CmdLetBinding(DefaultParameterSetName="securitygroup")] + [CmdLetBinding(DefaultParameterSetName = "securitygroup")] param ( [Parameter(Mandatory = $true, ValueFromPipeLine)] - #Security Policy to retrieve rules from. - [ValidateScript({ ValidateSecurityPolicy $_ })] - [System.Xml.XmlElement]$SecurityPolicy, + #Security Policy to retrieve rules from. + [ValidateScript( { ValidateSecurityPolicy $_ })] + [System.Xml.XmlElement]$SecurityPolicy, [Parameter()] - #Type of rule to retrieve. Defaults to all. - [ValidateSet("All","Firewall","Network","Guest")] - [String]$RuleType="All", - [Parameter(Position=1)] - #Name of rule to retrieve. - [ValidateNotNullOrEmpty()] - [String]$Name, + #Type of rule to retrieve. Defaults to all. + [ValidateSet("All", "Firewall", "Network", "Guest")] + [String]$RuleType = "All", + [Parameter(Position = 1)] + #Name of rule to retrieve. + [ValidateNotNullOrEmpty()] + [String]$Name, [Parameter()] - #Name of rule to retrieve. - [ValidateNotNullOrEmpty()] - [string]$ObjectId, - [Parameter(Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + #Name of rule to retrieve. + [ValidateNotNullOrEmpty()] + [string]$ObjectId, + [Parameter(Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} process { - #Define the XPATH search criteria based on RuleType. - Switch($RuleType) { + #Define the XPATH search criteria based on RuleType. + Switch ($RuleType) { "All" { $Query = "actionsByCategory/action" } "Firewall" { $Query = "actionsByCategory/action[@class='firewallSecurityAction']" } "Network" { $Query = "actionsByCategory/action[@class='trafficSteeringSecurityAction']" } "Guest" { $Query = "actionsByCategory/action[@class='endpointSecurityAction']" } } - if ($PSBoundParameters.ContainsKey("Name")) { + if ($PSBoundParameters.ContainsKey("Name")) { $Query += "[name=`'$Name`']" } - if ($PSBoundParameters.ContainsKey("ObjectId")) { + if ($PSBoundParameters.ContainsKey("ObjectId")) { $Query += "[objectId=`'$ObjectId`']" } - write-debug "Using xpath query $Query" - invoke-xpathquery -Node $SecurityPolicy -querymethod SelectNodes -query $Query + Write-Debug "Using xpath query $Query" + Invoke-XpathQuery -Node $SecurityPolicy -QueryMethod SelectNodes -query $Query } end {} } -function Move-NsxSecurityPolicyRule { +function Move-NsxSecurityPolicyRule { <# .SYNOPSIS @@ -34077,34 +34256,34 @@ function Move-NsxSecurityPolicyRule { [CmdletBinding()] param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { ValidateSecPolRule $_ })] - [System.Xml.XmlElement]$Rule, - [Parameter (Mandatory=$true)] - # Move the specified rule. Destination parameter must be used to specify the desired location. - [ValidateScript( { + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ })] + [System.Xml.XmlElement]$Rule, + [Parameter (Mandatory = $true)] + # Move the specified rule. Destination parameter must be used to specify the desired location. + [ValidateScript( { switch -regex ($_) { "^Top$" { $true; break } "^Bottom$" { $true; break } "^\d.*$" { $true; break } - default {throw "Specify position as 'Top', 'Bottom', or an integer to specify a new position. Use an existing rules property executionOrder to move relative to an existing rule." } + default { throw "Specify position as 'Top', 'Bottom', or an integer to specify a new position. Use an existing rules property executionOrder to move relative to an existing rule." } } })] - [string]$Destination, + [string]$Destination, [Parameter ()] - # Disable confirmation prompt - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} $ModifiedRules = @() } @@ -34122,16 +34301,16 @@ function Move-NsxSecurityPolicyRule { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #And do our updates... $CurrentRuleClass = $_Rule.class @@ -34140,17 +34319,17 @@ function Move-NsxSecurityPolicyRule { try { switch -regex ( $Destination ) { "Top" { - $refnode = invoke-xpathquery -node $PolicyXml -querymethod SelectSingleNode -Query "actionsByCategory/action[@class=`'$CurrentRuleClass`'][1]" + $refnode = Invoke-XpathQuery -Node $PolicyXml -QueryMethod SelectSingleNode -query "actionsByCategory/action[@class=`'$CurrentRuleClass`'][1]" break } "Bottom" { - $refnode = invoke-xpathquery -node $PolicyXml -querymethod SelectSingleNode -Query "actionsByCategory/action[@class=`'$CurrentRuleClass`'][last()]" + $refnode = Invoke-XpathQuery -Node $PolicyXml -QueryMethod SelectSingleNode -query "actionsByCategory/action[@class=`'$CurrentRuleClass`'][last()]" break } "\d.*" { - $refnode = invoke-xpathquery -node $PolicyXml -querymethod SelectSingleNode -Query "actionsByCategory/action[@class=`'$CurrentRuleClass`'][$Destination]" + $refnode = Invoke-XpathQuery -Node $PolicyXml -QueryMethod SelectSingleNode -query "actionsByCategory/action[@class=`'$CurrentRuleClass`'][$Destination]" break } } @@ -34162,7 +34341,7 @@ function Move-NsxSecurityPolicyRule { throw "Specified destination is invalid. Specify a valid destination and try again. $_" } - write-debug "$($MyInvocation.MyCommand.Name) : Ref node for new destination is $($refnode.objectId) )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Ref node for new destination is $($refnode.objectId) )" #Check user specified an actual move. if ( $_Rule.objectId -eq $refnode.objectId ) { @@ -34179,7 +34358,7 @@ function Move-NsxSecurityPolicyRule { $null = $Parent.InsertBefore($_Rule, $refnode) } - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated policy xml is : $( $PolicyXML | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated policy xml is : $( $PolicyXML | Format-XML )" $ModifiedRules += $_Rule.objectId } @@ -34187,14 +34366,14 @@ function Move-NsxSecurityPolicyRule { foreach ( $policy in $ModifiedPolicies.Values ) { $UpdatedPolicy = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm if ( $UpdatedPolicy) { - $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -Query "actionsByCategory/action" + $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -query "actionsByCategory/action" $AllPolicyRules | Where-Object { $ModifiedRules -contains $_.objectId } } } } } -function Remove-NsxSecurityPolicyRule { +function Remove-NsxSecurityPolicyRule { <# .SYNOPSIS @@ -34231,23 +34410,23 @@ function Remove-NsxSecurityPolicyRule { [CmdletBinding()] param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { ValidateSecPolRule $_ })] - [System.Xml.XmlElement]$Rule, + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ })] + [System.Xml.XmlElement]$Rule, [Parameter()] - # Disable confirmation prompt - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} } @@ -34259,37 +34438,37 @@ function Remove-NsxSecurityPolicyRule { # Policy has already been updated in this pipeline, so we modify the already updated xml. $PolicyXml = $ModifiedPolicies[$ParentPolicyObjectId] - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | Format-XML)" } else { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #And do our updates... $null = $_Rule.ParentNode.RemoveChild($_Rule) - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated policy xml is : $( $PolicyXML | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated policy xml is : $( $PolicyXML | Format-XML )" } end { foreach ( $policy in $ModifiedPolicies.Values ) { - $null = Set-NsxSecurityPolicy -Policy $policy -Noconfirm:$NoConfirm + $null = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm } } } -function Add-NsxSecurityPolicyRule { +function Add-NsxSecurityPolicyRule { <# .SYNOPSIS @@ -34461,26 +34640,26 @@ function Add-NsxSecurityPolicyRule { param ( [Parameter(Mandatory = $true, ValueFromPipeLine)] - #Security Policy to retrieve rules from. - [ValidateScript({ ValidateSecurityPolicy $_ })] - [System.Xml.XmlElement]$SecurityPolicy, - [Parameter (Mandatory=$false)] - # Security Policy Firewall Rule Spec as created by New-NsxSecurityPolicyFirewallRuleSpec - [ValidateScript({ ValidateSecPolFwSpec $_ })] - [System.Xml.XmlElement[]]$FirewallRuleSpec, - [Parameter (Mandatory=$false)] - # Guest Introspection Rule Spec as created by New-NsxSecurityPolicyGuestIntrospectionSpec - [ValidateScript({ ValidateSecPolGiSpec $_ })] - [System.Xml.XmlElement[]]$GuestIntrospectionSpec, - [Parameter (Mandatory=$false)] - # Network Introspection Rule Spec as created by New-NsxSecurityPolicyNetworkIntrospectionSpec - [ValidateScript({ ValidateSecPolNiSpec $_ })] - [System.Xml.XmlElement[]]$NetworkIntrospectionSpec, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + #Security Policy to retrieve rules from. + [ValidateScript( { ValidateSecurityPolicy $_ })] + [System.Xml.XmlElement]$SecurityPolicy, + [Parameter (Mandatory = $false)] + # Security Policy Firewall Rule Spec as created by New-NsxSecurityPolicyFirewallRuleSpec + [ValidateScript( { ValidateSecPolFwSpec $_ })] + [System.Xml.XmlElement[]]$FirewallRuleSpec, + [Parameter (Mandatory = $false)] + # Guest Introspection Rule Spec as created by New-NsxSecurityPolicyGuestIntrospectionSpec + [ValidateScript( { ValidateSecPolGiSpec $_ })] + [System.Xml.XmlElement[]]$GuestIntrospectionSpec, + [Parameter (Mandatory = $false)] + # Network Introspection Rule Spec as created by New-NsxSecurityPolicyNetworkIntrospectionSpec + [ValidateScript( { ValidateSecPolNiSpec $_ })] + [System.Xml.XmlElement[]]$NetworkIntrospectionSpec, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin {} @@ -34492,13 +34671,13 @@ function Add-NsxSecurityPolicyRule { #Create the firewall category actionsByCategory Elem if required if ($PSBoundParameters.ContainsKey("FirewallRuleSpec")) { - $xmlFwActionsByCategory = invoke-xpathquery -node $_SecurityPolicy -querymethod SelectSingleNode -query "actionsByCategory[category='firewall']" + $xmlFwActionsByCategory = Invoke-XpathQuery -Node $_SecurityPolicy -QueryMethod SelectSingleNode -query "actionsByCategory[category='firewall']" if ( -not $xmlFwActionsByCategory ) { $xmlFwActionsByCategory = $xmlDoc.CreateElement("actionsByCategory") $null = $_SecurityPolicy.appendChild($xmlFwActionsByCategory) Add-XmlElement -xmlRoot $xmlFwActionsByCategory -xmlElementName "category" -xmlElementText "firewall" } - foreach ($rule in $FirewallRuleSpec){ + foreach ($rule in $FirewallRuleSpec) { #Import the new fw node $null = $xmlFwActionsByCategory.AppendChild($xmlFwActionsByCategory.OwnerDocument.ImportNode($rule, $true)) } @@ -34506,13 +34685,13 @@ function Add-NsxSecurityPolicyRule { #Create the endpointSecurityAction actionsByCategory Elem if required. if ( $PSBoundParameters.ContainsKey("GuestIntrospectionSpec")) { - $xmlEndpointActionsByCategory = invoke-xpathquery -node $_SecurityPolicy -querymethod SelectSingleNode -query "actionsByCategory[category='endpoint']" + $xmlEndpointActionsByCategory = Invoke-XpathQuery -Node $_SecurityPolicy -QueryMethod SelectSingleNode -query "actionsByCategory[category='endpoint']" if ( -not $xmlEndpointActionsByCategory ) { $xmlEndpointActionsByCategory = $xmlDoc.CreateElement("actionsByCategory") $null = $_SecurityPolicy.appendChild($xmlEndpointActionsByCategory) Add-XmlElement -xmlRoot $xmlEndpointActionsByCategory -xmlElementName "category" -xmlElementText "endpoint" } - foreach ($rule in $GuestIntrospectionSpec){ + foreach ($rule in $GuestIntrospectionSpec) { #Import the new GI node $null = $xmlEndpointActionsByCategory.AppendChild($xmlEndpointActionsByCategory.OwnerDocument.ImportNode($rule, $true)) } @@ -34520,13 +34699,13 @@ function Add-NsxSecurityPolicyRule { #Create the trafficSteeringSecurityAction actionsByCategory Elem if required. if ( $PSBoundParameters.ContainsKey("NetworkIntrospectionSpec")) { - $xmlNetworkIntrospectionActionsByCategory = invoke-xpathquery -node $_SecurityPolicy -querymethod SelectSingleNode -query "actionsByCategory[category='traffic_steering']" + $xmlNetworkIntrospectionActionsByCategory = Invoke-XpathQuery -Node $_SecurityPolicy -QueryMethod SelectSingleNode -query "actionsByCategory[category='traffic_steering']" if ( -not $xmlNetworkIntrospectionActionsByCategory ) { $xmlNetworkIntrospectionActionsByCategory = $xmlDoc.CreateElement("actionsByCategory") $null = $_SecurityPolicy.appendChild($xmlNetworkIntrospectionActionsByCategory) Add-XmlElement -xmlRoot $xmlNetworkIntrospectionActionsByCategory -xmlElementName "category" -xmlElementText "traffic_steering" } - foreach ($rule in $NetworkIntrospectionSpec){ + foreach ($rule in $NetworkIntrospectionSpec) { #Import the new NI node $null = $xmlNetworkIntrospectionActionsByCategory.AppendChild($xmlNetworkIntrospectionActionsByCategory.OwnerDocument.ImportNode($rule, $true)) } @@ -34535,9 +34714,9 @@ function Add-NsxSecurityPolicyRule { #Do the post $body = $_SecurityPolicy.OuterXml $URI = "/api/2.0/services/policy/securitypolicy/$($_SecurityPolicy.objectId)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection - if ($response.StatusCode -eq "200"){ + if ($response.StatusCode -eq "200") { [xml]$xmldoc = $response.content $xmldoc.securityPolicy } @@ -34546,7 +34725,7 @@ function Add-NsxSecurityPolicyRule { } # We are only doing set for Firewall rule for the moment. Will do GI and NI if rcustomers request. -function Set-NsxSecurityPolicyFirewallRule { +function Set-NsxSecurityPolicyFirewallRule { <# .SYNOPSIS @@ -34602,51 +34781,51 @@ function Set-NsxSecurityPolicyFirewallRule { [CmdletBinding()] param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { + [Parameter (Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ if ( $_.class -ne "firewallSecurityAction" ) { throw "Specified rule is not a firewall rule." } })] - [System.Xml.XmlElement]$Rule, + [System.Xml.XmlElement]$Rule, [Parameter ()] - # Set the name of the specified rule - [ValidateNotNullOrEmpty()] - [String]$Name, + # Set the name of the specified rule + [ValidateNotNullOrEmpty()] + [String]$Name, [Parameter ()] - # Set the description of the specified rule - [ValidateNotNullOrEmpty()] - [String]$Description, + # Set the description of the specified rule + [ValidateNotNullOrEmpty()] + [String]$Description, [Parameter ()] - # Set the Action of the specified rule - [ValidateSet("Allow", "Block", "Reject")] - [String]$Action, + # Set the Action of the specified rule + [ValidateSet("Allow", "Block", "Reject")] + [String]$Action, [Parameter ()] - # Configure logging behaviour for the specified rule - [Boolean]$LoggingEnabled, + # Configure logging behaviour for the specified rule + [Boolean]$LoggingEnabled, [Parameter ()] - # Enable or disable the specified rule. - [Boolean]$Enabled, + # Enable or disable the specified rule. + [Boolean]$Enabled, [Parameter ()] - # Modify the 'direction' of the rule. Refer to mode '2' operation of New-NsxSecurityPolicyFirewallRuleSpec for more information. - [Validateset("Inbound", "Outbound", "Intra")] - [String]$Direction, + # Modify the 'direction' of the rule. Refer to mode '2' operation of New-NsxSecurityPolicyFirewallRuleSpec for more information. + [Validateset("Inbound", "Outbound", "Intra")] + [String]$Direction, [Parameter ()] - # Disable confirmation prompt - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} $ModifiedRules = @() } @@ -34659,36 +34838,36 @@ function Set-NsxSecurityPolicyFirewallRule { # Policy has already been updated in this pipeline, so we modify the already updated xml. $PolicyXml = $ModifiedPolicies[$ParentPolicyObjectId] - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | Format-XML)" } else { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #And do our updates... if ( $PSBoundParameters.ContainsKey("Name")) { - if ( -not ( invoke-xpathquery -querymethod SelectSingleNode -Node $_Rule -query "child::name" )) { + if ( -not ( Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Rule -query "child::name" )) { Add-XmlElement -xmlRoot $_Rule -xmlElementName "name" -xmlElementText $Name } else { - $_Rule.name= $Name + $_Rule.name = $Name } } if ( $PSBoundParameters.ContainsKey("Description")) { - if ( -not ( invoke-xpathquery -querymethod SelectSingleNode -Node $_Rule -query "child::description" )) { + if ( -not ( Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Rule -query "child::description" )) { Add-XmlElement -xmlRoot $_Rule -xmlElementName "description" -xmlElementText $description } else { @@ -34712,11 +34891,11 @@ function Set-NsxSecurityPolicyFirewallRule { if ( $_Rule.direction -ne $Direction.ToString().ToLower()) { # We dont expect that users will do this much as it's hard to concieve of an operational reason to do so # other than fat fingers. Still - its easy to implement, so we provide it, and just warn. - if ( $Direction -eq "Intra" ) { + if ( $Direction -eq "Intra" ) { $SecondaryGroups = $null - $secondaryGroups = Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Rule -Query "child::secondarySecurityGroup" - if ( $SecondaryGroups) { - write-warning "Specified rule specifies an explicit source or destination group. Converting the rule to direction 'Intra' will REMOVE all existing source and destination groups." + $secondaryGroups = Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Rule -query "child::secondarySecurityGroup" + if ( $SecondaryGroups) { + Write-Warning "Specified rule specifies an explicit source or destination group. Converting the rule to direction 'Intra' will REMOVE all existing source and destination groups." foreach ( $groupnode in $SecondaryGroups ) { $null = $_Rule.RemoveChild($groupnode) } @@ -34724,16 +34903,16 @@ function Set-NsxSecurityPolicyFirewallRule { } elseif ( $_Rule.direction -eq 'intra' ) { if ( $Direction -eq 'inbound') { $SrcDest = "source" } else { $SrcDest = "destination" } - write-warning "Changing the direction of a rule from intra to $($Direction.toLower()) will set the $srcdest to 'any'." + Write-Warning "Changing the direction of a rule from intra to $($Direction.toLower()) will set the $srcdest to 'any'." } else { - write-warning "Changing the direction of a rule from $($_Rule.Direction) to $($Direction.toLower()) is equivalent to swapping it's source and destination." + Write-Warning "Changing the direction of a rule from $($_Rule.Direction) to $($Direction.toLower()) is equivalent to swapping it's source and destination." } } $_Rule.direction = $Direction.ToString().ToLower() } - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml)" $ModifiedRules += $_Rule.objectId } @@ -34741,7 +34920,7 @@ function Set-NsxSecurityPolicyFirewallRule { foreach ( $policy in $ModifiedPolicies.Values ) { $UpdatedPolicy = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm if ( $UpdatedPolicy) { - $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -Query "actionsByCategory/action" + $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -query "actionsByCategory/action" $AllPolicyRules | Where-Object { $ModifiedRules -contains $_.objectId } } } @@ -34805,25 +34984,25 @@ function Set-NsxLoadBalancerPool { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateLoadBalancerPool $_ })] - [System.Xml.XmlElement]$LoadBalancerPool, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$False)] - [ValidateNotNull()] - [string]$Description="", - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [switch]$Transparent, - [Parameter (Mandatory=$false)] - [ValidateSet("round-robin", "ip-hash", "uri", "leastconn")] - [string]$Algorithm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateLoadBalancerPool $_ })] + [System.Xml.XmlElement]$LoadBalancerPool, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $False)] + [ValidateNotNull()] + [string]$Description = "", + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [switch]$Transparent, + [Parameter (Mandatory = $false)] + [ValidateSet("round-robin", "ip-hash", "uri", "leastconn")] + [string]$Algorithm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -34839,12 +35018,12 @@ function Set-NsxLoadBalancerPool { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_LoadBalancerPool.edgeId - $_LoadBalancerPool.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancerPool -Query 'descendant::edgeId')) ) | out-null + $_LoadBalancerPool.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_LoadBalancerPool -query 'descendant::edgeId')) ) | Out-Null if ( $PsBoundParameters.ContainsKey('name') ) { $_LoadBalancerPool.name = $name - $poolname = $name + $poolname = $name } if ( $PsBoundParameters.ContainsKey('Description') ) { @@ -34854,7 +35033,8 @@ function Set-NsxLoadBalancerPool { if ( $PsBoundParameters.ContainsKey('Transparent') ) { if ( $Transparent ) { $_LoadBalancerPool.Transparent = "true" - } else { + } + else { $_LoadBalancerPool.Transparent = "false" } } @@ -34866,20 +35046,20 @@ function Set-NsxLoadBalancerPool { $URI = "/api/4.0/edges/$EdgeId/loadbalancer/config/pools/$poolId" $body = $_LoadBalancerPool.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" -status "Load Balancer Pool Config" - $response = invoke-nsxwebrequest -method "PUT" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Status "Load Balancer Pool Config" + $response = Invoke-NsxWebRequest -method "PUT" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed - $UpdatedEdge = Get-NsxEdge -objectId $($EdgeId) -connection $connection - $return = $UpdatedEdge.features.loadBalancer.pool | ? { $_.name -eq $poolname } - Add-XmlElement -xmlroot $return -xmlElementName "edgeId" -xmlElementText $edgeId + $UpdatedEdge = Get-NsxEdge -objectId $($EdgeId) -Connection $connection + $return = $UpdatedEdge.features.loadBalancer.pool | Where-Object { $_.name -eq $poolname } + Add-XmlElement -xmlRoot $return -xmlElementName "edgeId" -xmlElementText $edgeId $return } end {} } -function Add-NsxSecurityPolicyRuleGroup { +function Add-NsxSecurityPolicyRuleGroup { <# .SYNOPSIS Modifies the configuration of an existing Security Policy Firewall or @@ -34937,33 +35117,33 @@ function Add-NsxSecurityPolicyRuleGroup { [CmdletBinding()] param ( - [Parameter(Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ if ( ($_.class -ne "firewallSecurityAction") -and ($_.class -ne "trafficSteeringSecurityAction") ) { throw "Specified rule is not a firewall or network introspection rule" } })] - [System.Xml.XmlElement]$Rule, - [Parameter(Mandatory=$true)] - # Group(s) to be added to source or destination of specified rule. Depends on currently configured direction of the rule. - [ValidateScript( { ValidateSecurityGroup $_ })] - [System.Xml.XmlElement[]]$SecurityGroup, + [System.Xml.XmlElement]$Rule, + [Parameter(Mandatory = $true)] + # Group(s) to be added to source or destination of specified rule. Depends on currently configured direction of the rule. + [ValidateScript( { ValidateSecurityGroup $_ })] + [System.Xml.XmlElement[]]$SecurityGroup, [Parameter()] - # Disable confirmation prompt - [switch]$NoConfirm, - [Parameter(Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt + [switch]$NoConfirm, + [Parameter(Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} $ModifiedRules = @() } @@ -34980,37 +35160,37 @@ function Add-NsxSecurityPolicyRuleGroup { # Policy has already been updated in this pipeline, so we modify the already updated xml. $PolicyXml = $ModifiedPolicies[$ParentPolicyObjectId] - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | Format-XML)" } else { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #Iterate securitygroups. foreach ( $Group in $SecurityGroup) { - if ( invoke-xpathquery -node $_Rule -querymethod SelectSingleNode -query "child::secondarySecurityGroup[objectId=`'$($Group.objectId)`']" ) { - write-warning "Group $($Group.name) ($($Group.objectId)) is already configured in rule $($_Rule.name) ($($_Rule.objectId))." + if ( Invoke-XpathQuery -Node $_Rule -QueryMethod SelectSingleNode -query "child::secondarySecurityGroup[objectId=`'$($Group.objectId)`']" ) { + Write-Warning "Group $($Group.name) ($($Group.objectId)) is already configured in rule $($_Rule.name) ($($_Rule.objectId))." } else { $xmlSecurityGroup = $_Rule.OwnerDocument.CreateElement("secondarySecurityGroup") - $_Rule.appendChild($xmlSecurityGroup) | out-null + $_Rule.appendChild($xmlSecurityGroup) | Out-Null Add-XmlElement -xmlRoot $xmlSecurityGroup -xmlElementName "objectId" -xmlElementText $group.objectId - write-debug "$($MyInvocation.MyCommand.Name) : Added group $($group.objectId) to rule $($_Rule.Name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Added group $($group.objectId) to rule $($_Rule.Name)" } } - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | Format-XML)" $ModifiedRules += $_Rule.objectId } @@ -35019,14 +35199,14 @@ function Add-NsxSecurityPolicyRuleGroup { foreach ( $policy in $ModifiedPolicies.Values ) { $UpdatedPolicy = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm if ( $UpdatedPolicy) { - $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -Query "actionsByCategory/action" + $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -query "actionsByCategory/action" $AllPolicyRules | Where-Object { $ModifiedRules -contains $_.objectId } } } } } -function Remove-NsxSecurityPolicyRuleGroup { +function Remove-NsxSecurityPolicyRuleGroup { <# .SYNOPSIS @@ -35088,36 +35268,36 @@ function Remove-NsxSecurityPolicyRuleGroup { [CmdletBinding()] param ( - [Parameter(Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ if ( ($_.class -ne "firewallSecurityAction") -and ($_.class -ne "trafficSteeringSecurityAction") ) { throw "Specified rule is not a firewall or network introspection rule" } })] - [System.Xml.XmlElement]$Rule, - [Parameter(Mandatory=$true)] - # Group(s) to be added to source or destination of specified rule. Depends on currently configured direction of the rule. - [ValidateScript( { ValidateSecurityGroup $_ })] - [System.Xml.XmlElement[]]$SecurityGroup, + [System.Xml.XmlElement]$Rule, + [Parameter(Mandatory = $true)] + # Group(s) to be added to source or destination of specified rule. Depends on currently configured direction of the rule. + [ValidateScript( { ValidateSecurityGroup $_ })] + [System.Xml.XmlElement[]]$SecurityGroup, [Parameter()] - # Disable confirmation prompt - [switch]$NoConfirm, + # Disable confirmation prompt + [switch]$NoConfirm, [Parameter()] - # Disable confirmation prompt for removal of last group - effectively converting rule to match ANY in the configured source or destination. - [switch]$NoConfirmOnLastGroupRemoval, - [Parameter(Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt for removal of last group - effectively converting rule to match ANY in the configured source or destination. + [switch]$NoConfirmOnLastGroupRemoval, + [Parameter(Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} $ModifiedRules = @() } @@ -35126,12 +35306,12 @@ function Remove-NsxSecurityPolicyRuleGroup { if ( $Rule.direction -eq "intra") { # We don't throw to avoid killing pipeline processing, but we warn that we cant do diddly to this particular rule. - write-warning "Unable to remove groups from rule $($_Rule.Name) ($($_Rule.objectId)) because it's source and destination are Policies Security Group (direction intra)" + Write-Warning "Unable to remove groups from rule $($_Rule.Name) ($($_Rule.objectId)) because it's source and destination are Policies Security Group (direction intra)" break } - if ( -not (invoke-xpathquery -node $Rule -querymethod selectsinglenode -query "child::secondarySecurityGroup" )) { - write-warning "Unable to remove groups from rule $($_Rule.Name) ($($_Rule.objectId)) because it is configured with source or destination of 'any'." + if ( -not (Invoke-XpathQuery -Node $Rule -QueryMethod selectsinglenode -query "child::secondarySecurityGroup" )) { + Write-Warning "Unable to remove groups from rule $($_Rule.Name) ($($_Rule.objectId)) because it is configured with source or destination of 'any'." break } $ParentPolicyObjectId = $Rule.ParentNode.ParentNode.objectId @@ -35141,30 +35321,30 @@ function Remove-NsxSecurityPolicyRuleGroup { # Policy has already been updated in this pipeline, so we modify the already updated xml. $PolicyXml = $ModifiedPolicies[$ParentPolicyObjectId] - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | Format-XML)" } else { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #Iterate securitygroups. foreach ( $Group in $SecurityGroup) { #Catch the special case of removal of the last group - the makes the rule apply to ALL traffic - need to ensure its what we want. - if (((invoke-xpathquery -node $_Rule -querymethod selectNodes -query "child::secondarySecurityGroup" ) | measure-object ).count -eq 1 ) { + if (((Invoke-XpathQuery -Node $_Rule -QueryMethod selectNodes -query "child::secondarySecurityGroup" ) | Measure-Object ).count -eq 1 ) { if ( -Not $NoConfirmOnLastGroupRemoval ) { - $message = "The last security group configured on rule $($_Rule.Name) ($($_Rule.objectId)) in policy $ParentPolicyObjectId is being removed. This will result in the rules source or destination being configured as 'any'." + $message = "The last security group configured on rule $($_Rule.Name) ($($_Rule.objectId)) in policy $ParentPolicyObjectId is being removed. This will result in the rules source or destination being configured as 'any'." $question = "Are you sure this is what you want?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -35178,18 +35358,18 @@ function Remove-NsxSecurityPolicyRuleGroup { throw "Aborting on user request." } } - $xmlSecurityGroup = invoke-xpathquery -node $_Rule -querymethod SelectSingleNode -query "child::secondarySecurityGroup[objectId=`'$($Group.objectId)`']" + $xmlSecurityGroup = Invoke-XpathQuery -Node $_Rule -QueryMethod SelectSingleNode -query "child::secondarySecurityGroup[objectId=`'$($Group.objectId)`']" if ( -not $xmlSecurityGroup ) { - write-warning "Group $($Group.name) ($($Group.objectId)) not configured in rule $($_Rule.name) ($($_Rule.objectId))." + Write-Warning "Group $($Group.name) ($($Group.objectId)) not configured in rule $($_Rule.name) ($($_Rule.objectId))." } else { - $_Rule.removeChild($xmlSecurityGroup) | out-null - write-debug "$($MyInvocation.MyCommand.Name) : Removed group $($group.objectId) from rule $($_Rule.Name)" + $_Rule.removeChild($xmlSecurityGroup) | Out-Null + Write-Debug "$($MyInvocation.MyCommand.Name) : Removed group $($group.objectId) from rule $($_Rule.Name)" } } - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | Format-XML)" $ModifiedRules += $_Rule.objectId } @@ -35198,14 +35378,14 @@ function Remove-NsxSecurityPolicyRuleGroup { foreach ( $policy in $ModifiedPolicies.Values ) { $UpdatedPolicy = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm if ( $UpdatedPolicy) { - $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -Query "actionsByCategory/action" + $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -query "actionsByCategory/action" $AllPolicyRules | Where-Object { $ModifiedRules -contains $_.objectId } } } } } -function Add-NsxSecurityPolicyRuleService { +function Add-NsxSecurityPolicyRuleService { <# .SYNOPSIS @@ -35238,33 +35418,33 @@ function Add-NsxSecurityPolicyRuleService { [CmdletBinding()] param ( - [Parameter(Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ if ( ($_.class -ne "firewallSecurityAction") -and ($_.class -ne "trafficSteeringSecurityAction") ) { throw "Specified rule is not a firewall or network introspection rule" } })] - [System.Xml.XmlElement]$Rule, - [Parameter(Mandatory=$true)] - # Group(s) to be added to source or destination of specified rule. Depends on currently configured direction of the rule. - [ValidateScript( { ValidateService $_ })] - [System.Xml.XmlElement[]]$Service, + [System.Xml.XmlElement]$Rule, + [Parameter(Mandatory = $true)] + # Group(s) to be added to source or destination of specified rule. Depends on currently configured direction of the rule. + [ValidateScript( { ValidateService $_ })] + [System.Xml.XmlElement[]]$Service, [Parameter()] - # Disable confirmation prompt - [switch]$NoConfirm, - [Parameter(Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt + [switch]$NoConfirm, + [Parameter(Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} $ModifiedRules = @() } @@ -35278,43 +35458,43 @@ function Add-NsxSecurityPolicyRuleService { # Policy has already been updated in this pipeline, so we modify the already updated xml. $PolicyXml = $ModifiedPolicies[$ParentPolicyObjectId] - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | Format-XML)" } else { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #Iterate services. foreach ( $Svc in $Service) { #Make sure we have the applications parent node. - $ApplicationsNode = invoke-xpathquery -node $_Rule -QueryMethod SelectSingleNode -Query "child::applications" + $ApplicationsNode = Invoke-XpathQuery -Node $_Rule -QueryMethod SelectSingleNode -query "child::applications" if ( -not ($applicationsNode)) { $ApplicationsNode = $_Rule.OwnerDocument.CreateElement("applications") $null = $_Rule.appendChild($ApplicationsNode) } - if ( invoke-xpathquery -node $_Rule -querymethod SelectSingleNode -query "child::applications/application[objectId=`'$($Svc.objectId)`']" ) { - write-warning "Service $($Svc.name) ($($Svc.objectId)) is already configured in rule $($_Rule.name) ($($_Rule.objectId))." + if ( Invoke-XpathQuery -Node $_Rule -QueryMethod SelectSingleNode -query "child::applications/application[objectId=`'$($Svc.objectId)`']" ) { + Write-Warning "Service $($Svc.name) ($($Svc.objectId)) is already configured in rule $($_Rule.name) ($($_Rule.objectId))." } else { $Application = $_Rule.OwnerDocument.CreateElement("application") $null = $ApplicationsNode.appendChild($Application) Add-XmlElement -xmlRoot $Application -xmlElementName "objectId" -xmlElementText $Svc.objectId - write-debug "$($MyInvocation.MyCommand.Name) : Added service $($Svc.objectId) to rule $($_Rule.Name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Added service $($Svc.objectId) to rule $($_Rule.Name)" } } - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | Format-XML)" $ModifiedRules += $_Rule.objectId } @@ -35323,14 +35503,14 @@ function Add-NsxSecurityPolicyRuleService { foreach ( $policy in $ModifiedPolicies.Values ) { $UpdatedPolicy = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm if ( $UpdatedPolicy) { - $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -Query "actionsByCategory/action" + $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -query "actionsByCategory/action" $AllPolicyRules | Where-Object { $ModifiedRules -contains $_.objectId } } } } } -function Remove-NsxSecurityPolicyRuleService { +function Remove-NsxSecurityPolicyRuleService { <# .SYNOPSIS @@ -35366,44 +35546,44 @@ function Remove-NsxSecurityPolicyRuleService { [CmdletBinding()] param ( - [Parameter(Mandatory=$True, ValueFromPipeline=$True)] - # Security Policy Rule to reconfigure - [ValidateScript( { + [Parameter(Mandatory = $True, ValueFromPipeline = $True)] + # Security Policy Rule to reconfigure + [ValidateScript( { ValidateSecPolRule $_ if ( ($_.class -ne "firewallSecurityAction") -and ($_.class -ne "trafficSteeringSecurityAction") ) { throw "Specified rule is not a firewall or network introspection rule" } })] - [System.Xml.XmlElement]$Rule, - [Parameter(Mandatory=$true)] - # Services(s) to be removed from the specified rule. Depends on currently configured direction of the rule. - [ValidateScript( { ValidateService $_ })] - [System.Xml.XmlElement[]]$Service, + [System.Xml.XmlElement]$Rule, + [Parameter(Mandatory = $true)] + # Services(s) to be removed from the specified rule. Depends on currently configured direction of the rule. + [ValidateScript( { ValidateService $_ })] + [System.Xml.XmlElement[]]$Service, [Parameter()] - # Disable confirmation prompt - [switch]$NoConfirm, + # Disable confirmation prompt + [switch]$NoConfirm, [Parameter()] - # Disable confirmation prompt for removal of last service - effectively converting rule to match ANY service. - [switch]$NoConfirmOnLastServiceRemoval, - [Parameter(Mandatory=$False)] - # PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + # Disable confirmation prompt for removal of last service - effectively converting rule to match ANY service. + [switch]$NoConfirmOnLastServiceRemoval, + [Parameter(Mandatory = $False)] + # PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin { # We process all rule modifications offline as part of pipeline processing, then we put the updated policies to the api in the end{} block to avoid overwriting changes to different rules in the same policy.. # Save modified policies in a hash table keyed by id - write-debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" + Write-Debug "$($MyInvocation.MyCommand.Name) : Initialising Policy cache" $ModifiedPolicies = @{} $ModifiedRules = @() } process { - if ( -not (invoke-xpathquery -node $Rule -querymethod selectsinglenode -query "child::applications" )) { - write-warning "Unable to remove service from rule $($Rule.Name) ($($Rule.objectId)) because it is configured with service of 'any'." + if ( -not (Invoke-XpathQuery -Node $Rule -QueryMethod selectsinglenode -query "child::applications" )) { + Write-Warning "Unable to remove service from rule $($Rule.Name) ($($Rule.objectId)) because it is configured with service of 'any'." break } $ParentPolicyObjectId = $Rule.ParentNode.ParentNode.objectId @@ -35413,35 +35593,35 @@ function Remove-NsxSecurityPolicyRuleService { # Policy has already been updated in this pipeline, so we modify the already updated xml. $PolicyXml = $ModifiedPolicies[$ParentPolicyObjectId] - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved specified rules parent policy from the policy cache. Policy XML is : $($PolicyXML | Format-XML)" } else { # We havent touched the policy yet, so we have to get it. We clone to avoid modifying the original. $PolicyXml = $Rule.ParentNode.ParentNode.CloneNode($true) $ModifiedPolicies.Add($ParentPolicyObjectId, $PolicyXml) - write-debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." + Write-Debug "$($MyInvocation.MyCommand.Name) : Specified rules parent policy not found in policy cache so it has been added." } #Now get our xml from the cached policy. - $_Rule = invoke-xpathquery -querymethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" + $_Rule = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $PolicyXml -query "actionsByCategory/action[objectId=`'$($Rule.objectId)`']" if ( -not $_Rule ) { #This should never happen throw "An unexpected error occured retrieving a rule from cache. Please report this as a bug at https://github.com/vmware/powernsx" } - write-debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | format-xml )" + Write-Debug "$($MyInvocation.MyCommand.Name) : Retrieved rule from cache: $( $_Rule | Format-XML )" #Iterate securitygroups. foreach ( $Svc in $Service) { - $ServiceXml = invoke-xpathquery -node $_Rule -querymethod SelectSingleNode -query "child::applications/application[objectId=`'$($Svc.objectId)`']" + $ServiceXml = Invoke-XpathQuery -Node $_Rule -QueryMethod SelectSingleNode -query "child::applications/application[objectId=`'$($Svc.objectId)`']" if ( -not $ServiceXml ) { - write-warning "Service $($Svc.name) ($($Svc.objectId)) not configured in rule $($_Rule.name) ($($_Rule.objectId))." + Write-Warning "Service $($Svc.name) ($($Svc.objectId)) not configured in rule $($_Rule.name) ($($_Rule.objectId))." } else { #Catch the special case of removal of the last service - the makes the rule apply to ALL traffic - need to ensure its what we want. - if (((invoke-xpathquery -node $_Rule -querymethod selectNodes -query "child::applications/application" ) | measure-object ).count -eq 1 ) { + if (((Invoke-XpathQuery -Node $_Rule -QueryMethod selectNodes -query "child::applications/application" ) | Measure-Object ).count -eq 1 ) { if ( -Not $NoConfirmOnLastServiceRemoval ) { - $message = "The last service configured on rule $($_Rule.Name) ($($_Rule.objectId)) in policy $ParentPolicyObjectId is being removed. This will result in the rule matching 'any' service." + $message = "The last service configured on rule $($_Rule.Name) ($($_Rule.objectId)) in policy $ParentPolicyObjectId is being removed. This will result in the rule matching 'any' service." $question = "Are you sure this is what you want?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] @@ -35455,12 +35635,12 @@ function Remove-NsxSecurityPolicyRuleService { throw "Aborting on user request." } } - $_Rule.applications.removeChild($ServiceXml) | out-null - write-debug "$($MyInvocation.MyCommand.Name) : Removed service $($Svc.objectId) from rule $($_Rule.Name)" + $_Rule.applications.removeChild($ServiceXml) | Out-Null + Write-Debug "$($MyInvocation.MyCommand.Name) : Removed service $($Svc.objectId) from rule $($_Rule.Name)" } } - write-debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | format-xml)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Rule processing complete. Updated rule xml is : $($_Rule.OuterXml | Format-XML)" $ModifiedRules += $_Rule.objectId } @@ -35469,7 +35649,7 @@ function Remove-NsxSecurityPolicyRuleService { foreach ( $policy in $ModifiedPolicies.Values ) { $UpdatedPolicy = Set-NsxSecurityPolicy -Policy $policy -NoConfirm:$NoConfirm if ( $UpdatedPolicy) { - $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -Query "actionsByCategory/action" + $AllPolicyRules = Invoke-XpathQuery -QueryMethod SelectNodes -Node $UpdatedPolicy -query "actionsByCategory/action" $AllPolicyRules | Where-Object { $ModifiedRules -contains $_.objectId } } } @@ -35515,12 +35695,13 @@ function Get-NsxApplicableSecurityAction { [CmdLetBinding()] param ( - [Parameter (Mandatory=$True, ValueFromPipeline=$true)] - # Object(s) to retrieve applicable rules for. Can be a SecurityGroup, Security Policy or Virtual Machine - [ValidateScript( { + [Parameter (Mandatory = $True, ValueFromPipeline = $true)] + # Object(s) to retrieve applicable rules for. Can be a SecurityGroup, Security Policy or Virtual Machine + [ValidateScript( { $arg = $_ try { - ValidateSecurityGroup $arg } + ValidateSecurityGroup $arg + } catch { try { ValidateSecurityPolicy $arg @@ -35535,11 +35716,11 @@ function Get-NsxApplicableSecurityAction { } } })] - [object[]]$Object, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [object[]]$Object, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -35552,7 +35733,7 @@ function Get-NsxApplicableSecurityAction { $URI = "/api/2.0/services/policy/virtualmachine/$($obj.ExtensionData.MoRef.Value)/securityactions" } else { - if ( $obj.ObjectTypeName -eq "SecurityGroup" ) { + if ( $obj.ObjectTypeName -eq "SecurityGroup" ) { $URI = "/api/2.0/services/policy/securitygroup/$($obj.objectId)/securityactions" } elseif ( $obj.ObjectTypeName -eq "Policy" ) { @@ -35565,9 +35746,9 @@ function Get-NsxApplicableSecurityAction { #Make the call try { - $response = Invoke-NsxRestMethod -Uri $Uri -method Get -connection $connection + $response = Invoke-NsxRestMethod -URI $Uri -method Get -connection $connection $ApplicableActions = Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::securityActionsByCategoryMap/actionsByCategory/action" - if ( $ApplicableActions ){ + if ( $ApplicableActions ) { $response.securityActionsByCategoryMap.actionsByCategory.action } } @@ -35581,7 +35762,7 @@ function Get-NsxApplicableSecurityAction { ###### # IPsec -function Get-NsxIPsecStats{ +function Get-NsxIPsecStats { <# .SYNOPSIS @@ -35607,21 +35788,21 @@ function Get-NsxIPsecStats{ #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection - ) + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection + ) begin {} process { $URI = "/api/4.0/edges/$($Edge.Id)/ipsec/statistics" - [system.xml.xmldocument]$response = invoke-nsxrestmethod -method "GET" -uri $URI -connection $connection - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $response -Query "child::ipsecStatusAndStats")) { + [system.xml.xmldocument]$response = Invoke-NsxRestMethod -method "GET" -URI $URI -connection $connection + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $response -query "child::ipsecStatusAndStats")) { $response.ipsecStatusAndStats } } @@ -35700,23 +35881,23 @@ function Get-NsxSecurityGroupEffectiveMember { #> - [CmdLetBinding(DefaultParameterSetName="object")] + [CmdLetBinding(DefaultParameterSetName = "object")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="object")] - [ValidateNotNull()] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$true, Position = 1, ParameterSetName="objectid" )] - [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id"} else { $true }})] - [string]$SecurityGroupId, - [Parameter (Mandatory=$false)] - [ValidateSet("All", "VirtualMachine", "IpAddress", "MacAddress", "Vnic")] - [string[]]$ReturnTypes="All", - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "object")] + [ValidateNotNull()] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "objectid" )] + [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id" } else { $true } })] + [string]$SecurityGroupId, + [Parameter (Mandatory = $false)] + [ValidateSet("All", "VirtualMachine", "IpAddress", "MacAddress", "Vnic")] + [string[]]$ReturnTypes = "All", + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -35737,55 +35918,55 @@ function Get-NsxSecurityGroupEffectiveMember { } if ( ($ReturnTypes -eq "All") -or ($ReturnTypes -eq "VirtualMachine")) { - write-debug "$($MyInvocation.MyCommand.Name) : Getting effective VM membership for Security Group $sgid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting effective VM membership for Security Group $sgid" $URI = "/api/2.0/services/securitygroup/$sgid/translation/virtualmachines" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection if ( $response.content -as [system.xml.xmldocument] ) { - write-debug "$($MyInvocation.MyCommand.Name) : got xml response from api" + Write-Debug "$($MyInvocation.MyCommand.Name) : got xml response from api" [system.xml.xmldocument]$body = $response.content - if ( $body.GetElementsByTagName("vmnodes").haschildnodes) { $EffectiveVMNodes = $body.GetElementsByTagName("vmnodes")} + if ( $body.GetElementsByTagName("vmnodes").haschildnodes) { $EffectiveVMNodes = $body.GetElementsByTagName("vmnodes") } } } if ( ($ReturnTypes -eq "All") -or ($ReturnTypes -eq "IpAddress")) { - write-debug "$($MyInvocation.MyCommand.Name) : Getting effective ipaddress membership for Security Group $sgid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting effective ipaddress membership for Security Group $sgid" $URI = "/api/2.0/services/securitygroup/$sgid/translation/ipaddresses" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection if ( $response.content -as [system.xml.xmldocument] ) { - write-debug "$($MyInvocation.MyCommand.Name) : got xml response from api" + Write-Debug "$($MyInvocation.MyCommand.Name) : got xml response from api" [system.xml.xmldocument]$body = $response.content if ( $body.GetElementsByTagName("ipNodes").haschildnodes) { $EffectiveIPNodes = $body.GetElementsByTagName("ipNodes") } } } if ( ($ReturnTypes -eq "All") -or ($ReturnTypes -eq "MacAddress")) { - write-debug "$($MyInvocation.MyCommand.Name) : Getting effective macaddress membership for Security Group $sgid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting effective macaddress membership for Security Group $sgid" $URI = "/api/2.0/services/securitygroup/$sgid/translation/macaddresses" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection if ( $response.content -as [system.xml.xmldocument] ) { - write-debug "$($MyInvocation.MyCommand.Name) : got xml response from api" + Write-Debug "$($MyInvocation.MyCommand.Name) : got xml response from api" [system.xml.xmldocument]$body = $response.content - if ( $body.GetElementsByTagName("macNodes").haschildnodes) { $EffectiveMACNodes = $body.GetElementsByTagName("macNodes")} + if ( $body.GetElementsByTagName("macNodes").haschildnodes) { $EffectiveMACNodes = $body.GetElementsByTagName("macNodes") } } } if ( ($ReturnTypes -eq "All") -or ($ReturnTypes -eq "Vnic")) { - write-debug "$($MyInvocation.MyCommand.Name) : Getting effective vnic membership for Security Group $sgid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Getting effective vnic membership for Security Group $sgid" $URI = "/api/2.0/services/securitygroup/$sgid/translation/vnics" - $response = invoke-nsxwebrequest -method "get" -uri $URI -connection $connection + $response = Invoke-NsxWebRequest -method "get" -URI $URI -connection $connection if ( $response.content -as [system.xml.xmldocument] ) { - write-debug "$($MyInvocation.MyCommand.Name) : got xml response from api" + Write-Debug "$($MyInvocation.MyCommand.Name) : got xml response from api" [system.xml.xmldocument]$body = $response.content - if ( $body.GetElementsByTagName("vnicNodes").haschildnodes) { $EffectiveVNICNodes = $body.GetElementsByTagName("vnicNodes")} + if ( $body.GetElementsByTagName("vnicNodes").haschildnodes) { $EffectiveVNICNodes = $body.GetElementsByTagName("vnicNodes") } } } [pscustomobject]@{ "VirtualMachine" = $EffectiveVMNodes - "IpAddress" = $EffectiveIPNodes - "MacAddress" = $EffectiveMACNodes - "Vnic" = $EffectiveVNICNodes + "IpAddress" = $EffectiveIPNodes + "MacAddress" = $EffectiveMACNodes + "Vnic" = $EffectiveVNICNodes } } @@ -35833,16 +36014,16 @@ function Get-NsxSecurityGroupEffectiveVirtualMachine { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="object")] - [ValidateNotNull()] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$true, Position = 1, ParameterSetName="objectid" )] - [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id"} else { $true }})] - [string]$SecurityGroupId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "object")] + [ValidateNotNull()] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "objectid" )] + [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id" } else { $true } })] + [string]$SecurityGroupId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -35850,7 +36031,7 @@ function Get-NsxSecurityGroupEffectiveVirtualMachine { process { - Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes VirtualMachine | select-object @{ "n" = "VmName"; "e" = { $_.virtualmachine.vmnode.vmname }}, @{ "n" = "VmId"; "e" = { $_.virtualmachine.vmnode.VmId }} + Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes VirtualMachine | Select-Object @{ "n" = "VmName"; "e" = { $_.virtualmachine.vmnode.vmname } }, @{ "n" = "VmId"; "e" = { $_.virtualmachine.vmnode.VmId } } } end {} @@ -35905,16 +36086,16 @@ function Get-NsxSecurityGroupEffectiveIpAddress { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="object")] - [ValidateNotNull()] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$true, Position = 1, ParameterSetName="objectid" )] - [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id"} else { $true }})] - [string]$SecurityGroupId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "object")] + [ValidateNotNull()] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "objectid" )] + [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id" } else { $true } })] + [string]$SecurityGroupId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -35922,7 +36103,7 @@ function Get-NsxSecurityGroupEffectiveIpAddress { process { - Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes IpAddress | select-object @{ "n" = "IpAddress"; "e" = { $_.ipaddress.ipnode.ipaddresses.string }} + Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes IpAddress | Select-Object @{ "n" = "IpAddress"; "e" = { $_.ipaddress.ipnode.ipaddresses.string } } } end {} @@ -35970,16 +36151,16 @@ function Get-NsxSecurityGroupEffectiveMacAddress { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="object")] - [ValidateNotNull()] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$true, Position = 1, ParameterSetName="objectid" )] - [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id"} else { $true }})] - [string]$SecurityGroupId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "object")] + [ValidateNotNull()] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "objectid" )] + [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id" } else { $true } })] + [string]$SecurityGroupId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -35987,7 +36168,7 @@ function Get-NsxSecurityGroupEffectiveMacAddress { process { - Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes MacAddress | select-object @{ "n" = "MacAddress"; "e" = { $_.macaddress.macnode.macaddress }} + Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes MacAddress | Select-Object @{ "n" = "MacAddress"; "e" = { $_.macaddress.macnode.macaddress } } } end {} @@ -36041,16 +36222,16 @@ function Get-NsxSecurityGroupEffectiveVnic { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="object")] - [ValidateNotNull()] - [System.Xml.XmlElement]$SecurityGroup, - [Parameter (Mandatory=$true, Position = 1, ParameterSetName="objectid" )] - [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id"} else { $true }})] - [string]$SecurityGroupId, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "object")] + [ValidateNotNull()] + [System.Xml.XmlElement]$SecurityGroup, + [Parameter (Mandatory = $true, Position = 1, ParameterSetName = "objectid" )] + [ValidateScript ( { if ( -not $_ -match 'securitygroup-\d+') { throw "Specify a valid SecurityGroup id" } else { $true } })] + [string]$SecurityGroupId, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) @@ -36058,7 +36239,7 @@ function Get-NsxSecurityGroupEffectiveVnic { process { - Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes Vnic | select-object @{ "n" = "Uuid"; "e" = { $_.Vnic.vnicnode.uuid }}, @{ "n" = "IpAddresses"; "e" = { $_.Vnic.vnicnode.IpAddresses.string }}, @{ "n" = "MacAddress"; "e" = { $_.Vnic.vnicnode.MacAddress }} + Get-NsxSecurityGroupEffectiveMember @PSBoundParameters -ReturnTypes Vnic | Select-Object @{ "n" = "Uuid"; "e" = { $_.Vnic.vnicnode.uuid } }, @{ "n" = "IpAddresses"; "e" = { $_.Vnic.vnicnode.IpAddresses.string } }, @{ "n" = "MacAddress"; "e" = { $_.Vnic.vnicnode.MacAddress } } } end {} @@ -36084,16 +36265,16 @@ function Find-NsxWhereVMUsed { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VM, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.VirtualMachineInterop]$VM, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { @@ -36103,19 +36284,19 @@ function Find-NsxWhereVMUsed { process { #Get Firewall rules - $L3FirewallRules = Get-nsxFirewallSection -connection $connection | Get-NsxFirewallRule -connection $connection - $L2FirewallRules = Get-nsxFirewallSection -sectionType layer2sections -connection $connection | Get-NsxFirewallRule -ruletype layer2sections -connection $connection + $L3FirewallRules = Get-NsxFirewallSection -Connection $connection | Get-NsxFirewallRule -Connection $connection + $L2FirewallRules = Get-NsxFirewallSection -sectionType layer2sections -Connection $connection | Get-NsxFirewallRule -RuleType layer2sections -Connection $connection #Get all SGs - $securityGroups = Get-NsxSecuritygroup -connection $connection + $securityGroups = Get-NsxSecurityGroup -Connection $connection $MatchedSG = @() $MatchedFWL3 = @() $MatchedFWL2 = @() foreach ( $SecurityGroup in $securityGroups ) { - $Members = $securityGroup | Get-NsxSecurityGroupEffectiveMember -connection $connection -ReturnTypes VirtualMachine + $Members = $securityGroup | Get-NsxSecurityGroupEffectiveMember -Connection $connection -ReturnTypes VirtualMachine - write-debug "$($MyInvocation.MyCommand.Name) : Checking securitygroup $($securitygroup.name) for VM $($VM.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Checking securitygroup $($securitygroup.name) for VM $($VM.name)" If ( $members.VirtualMachine ) { foreach ( $member in $members.VirtualMachine) { @@ -36126,10 +36307,10 @@ function Find-NsxWhereVMUsed { } } - write-debug "$($MyInvocation.MyCommand.Name) : Checking L3 FirewallRules for VM $($VM.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Checking L3 FirewallRules for VM $($VM.name)" foreach ( $FirewallRule in $L3FirewallRules ) { - write-debug "$($MyInvocation.MyCommand.Name) : Checking rule $($FirewallRule.Id) for VM $($VM.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Checking rule $($FirewallRule.Id) for VM $($VM.name)" If ( $FirewallRule | Get-Member -MemberType Properties -Name Sources) { foreach ( $Source in $FirewallRule.Sources.Source) { @@ -36138,7 +36319,7 @@ function Find-NsxWhereVMUsed { } } } - If ( $FirewallRule| Get-Member -MemberType Properties -Name Destinations ) { + If ( $FirewallRule | Get-Member -MemberType Properties -Name Destinations ) { foreach ( $Dest in $FirewallRule.Destinations.Destination) { if ( $Dest.value -eq $VM.ExtensionData.MoRef.Value ) { $MatchedFWL3 += $FirewallRule @@ -36154,10 +36335,10 @@ function Find-NsxWhereVMUsed { } } - write-debug "$($MyInvocation.MyCommand.Name) : Checking L2 FirewallRules for VM $($VM.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Checking L2 FirewallRules for VM $($VM.name)" foreach ( $FirewallRule in $L2FirewallRules ) { - write-debug "$($MyInvocation.MyCommand.Name) : Checking rule $($FirewallRule.Id) for VM $($VM.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Checking rule $($FirewallRule.Id) for VM $($VM.name)" If ( $FirewallRule | Get-Member -MemberType Properties -Name Sources) { foreach ( $Source in $FirewallRule.Sources.Source) { @@ -36182,10 +36363,10 @@ function Find-NsxWhereVMUsed { } } - $return = new-object psobject - $return | add-member -memberType NoteProperty -Name "MatchedSecurityGroups" -value $MatchedSG - $return | add-member -memberType NoteProperty -Name "MatchedL3FirewallRules" -value $MatchedFWL3 - $return | add-member -memberType NoteProperty -Name "MatchedL2FirewallRules" -value $MatchedFWL2 + $return = New-Object psobject + $return | Add-Member -MemberType NoteProperty -Name "MatchedSecurityGroups" -Value $MatchedSG + $return | Add-Member -MemberType NoteProperty -Name "MatchedL3FirewallRules" -Value $MatchedFWL3 + $return | Add-Member -MemberType NoteProperty -Name "MatchedL2FirewallRules" -Value $MatchedFWL2 $return @@ -36195,7 +36376,7 @@ function Find-NsxWhereVMUsed { } -function Get-NsxBackingPortGroup{ +function Get-NsxBackingPortGroup { <# .SYNOPSIS @@ -36222,11 +36403,11 @@ function Get-NsxBackingPortGroup{ #> - param ( + param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ValidateLogicalSwitch $_ })] - [object]$LogicalSwitch + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalSwitch $_ })] + [object]$LogicalSwitch ) begin { @@ -36241,7 +36422,7 @@ function Get-NsxBackingPortGroup{ $BackingVDS = $_.vdsContextWithBacking foreach ( $vDS in $BackingVDS ) { - write-debug "$($MyInvocation.MyCommand.Name) : Backing portgroup id $($vDS.backingValue)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Backing portgroup id $($vDS.backingValue)" try { Get-VDPortgroup -Id "DistributedVirtualPortgroup-$($vDS.backingValue)" @@ -36256,7 +36437,7 @@ function Get-NsxBackingPortGroup{ } -function Get-NsxBackingDVSwitch{ +function Get-NsxBackingDVSwitch { <# .SYNOPSIS @@ -36283,11 +36464,11 @@ function Get-NsxBackingDVSwitch{ #> - param ( + param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true)] - [ValidateScript({ValidateLogicalSwitch $_ })] - [object]$LogicalSwitch + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + [ValidateScript( { ValidateLogicalSwitch $_ })] + [object]$LogicalSwitch ) begin { @@ -36302,7 +36483,7 @@ function Get-NsxBackingDVSwitch{ $BackingVDS = $_.vdsContextWithBacking foreach ( $vDS in $BackingVDS ) { - write-debug "$($MyInvocation.MyCommand.Name) : Backing vDS id $($vDS.switch.objectId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Backing vDS id $($vDS.switch.objectId)" try { Get-VDSwitch -Id "VmwareDistributedVirtualSwitch-$($vDS.switch.objectId)" @@ -36344,12 +36525,12 @@ function Get-NsxIPsec { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin {} @@ -36422,26 +36603,26 @@ function Set-NsxIPsec { param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateIPsec $_ })] - [System.Xml.XmlElement]$IPsec, - [Parameter (Mandatory=$False)] - [switch]$Enabled, - [Parameter (Mandatory=$False)] - [switch]$EnableLogging, - [Parameter (Mandatory=$False)] - [ValidateSet("emergency","alert","critical","error","warning","notice","info","debug")] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$psk, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [string]$serviceCertificate, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateIPsec $_ })] + [System.Xml.XmlElement]$IPsec, + [Parameter (Mandatory = $False)] + [switch]$Enabled, + [Parameter (Mandatory = $False)] + [switch]$EnableLogging, + [Parameter (Mandatory = $False)] + [ValidateSet("emergency", "alert", "critical", "error", "warning", "notice", "info", "debug")] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$psk, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [string]$serviceCertificate, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { } @@ -36453,7 +36634,7 @@ function Set-NsxIPsec { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_IPsec.edgeId - $_IPsec.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_IPsec -Query 'descendant::edgeId')) ) | out-null + $_IPsec.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_IPsec -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. @@ -36476,20 +36657,21 @@ function Set-NsxIPsec { } if ( $PsBoundParameters.ContainsKey('serviceCertificate') ) { - if ( invoke-xpathquery -node $_IPsec -querymethod SelectSingleNode -Query "child::global/serviceCertificate" ) { + if ( Invoke-XpathQuery -Node $_IPsec -QueryMethod SelectSingleNode -query "child::global/serviceCertificate" ) { $_IPsec.global.serviceCertificate = $serviceCertificate - } else { - Add-XmlElement -xmlroot $_IPsec.global -xmlElementName "serviceCertificate" -xmlElementText $serviceCertificate + } + else { + Add-XmlElement -xmlRoot $_IPsec.global -xmlElementName "serviceCertificate" -xmlElementText $serviceCertificate } } $URI = "/api/4.0/edges/$($edgeId)/ipsec/config" $body = $_IPsec.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($edgeId)" -completed - Get-NsxEdge -objectId $($edgeId) -connection $connection | Get-NsxIPsec + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Completed + Get-NsxEdge -objectId $($edgeId) -Connection $connection | Get-NsxIPsec } end {} @@ -36527,29 +36709,29 @@ function Remove-NsxIPsec { #> - [CmdLetBinding(DefaultParameterSetName="Default")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility + [CmdLetBinding(DefaultParameterSetName = "Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #NSX Edge DNS to remove - [ValidateScript({ ValidateIPsec $_ })] - [System.Xml.XmlElement]$IPsec, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #NSX Edge DNS to remove + [ValidateScript( { ValidateIPsec $_ })] + [System.Xml.XmlElement]$IPsec, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } } @@ -36557,7 +36739,7 @@ function Remove-NsxIPsec { process { $edgeId = $IPsec.edgeId if ( -not ( $Noconfirm )) { - $message = "Edge IPsec removal is permanent." + $message = "Edge IPsec removal is permanent." $question = "Proceed with removal of Edge IPsec $($EdgeId) ?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -36567,9 +36749,9 @@ function Remove-NsxIPsec { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/4.0/edges/$($EdgeId)/ipsec/config" - Write-Progress -activity "Remove IPsec for Edge $($EdgeId)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Remove IPsec for Edge $($EdgeId)" -completed + Write-Progress -Activity "Remove IPsec for Edge $($EdgeId)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove IPsec for Edge $($EdgeId)" -Completed } } @@ -36614,59 +36796,59 @@ function Add-NsxIPsecSite { Add a IPsec Site using PSK and custom settings (use dhgroup dh14 and encryption AES256) #> - [CmdLetBinding(DefaultParameterSetName="IpAddress")] - param ( - - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateIPsec $_ })] - [System.Xml.XmlElement]$IPsec, - [Parameter (Mandatory=$false)] - [switch]$Enabled = $true, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$Description, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$localId, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [ipaddress]$localIp, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string[]]$localSubnet, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$peerId, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string]$peerIp, - [Parameter (Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string[]]$peerSubnet, - [Parameter (Mandatory=$false)] - [ValidateSet("AES", "AES256", "3DES", "AES-GCM")] - [string]$encryptionAlgorithm="AES", - [Parameter (Mandatory=$false)] - [ValidateSet("PSK", "x.509")] - [string]$authenticationMode="PSK", - [Parameter (Mandatory=$false)] - [switch]$enablepfs=$true, - [Parameter (Mandatory=$false)] - [ValidateSet("dh2", "dh5", "dh14", "dh15", "dh16")] - [string]$dhgroup="dh14", - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$psk, - [Parameter (Mandatory=$false)] - [ValidateNotNullOrEmpty()] - [string]$extension, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [CmdLetBinding(DefaultParameterSetName = "IpAddress")] + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateIPsec $_ })] + [System.Xml.XmlElement]$IPsec, + [Parameter (Mandatory = $false)] + [switch]$Enabled = $true, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Description, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$localId, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ipaddress]$localIp, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string[]]$localSubnet, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$peerId, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$peerIp, + [Parameter (Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string[]]$peerSubnet, + [Parameter (Mandatory = $false)] + [ValidateSet("AES", "AES256", "3DES", "AES-GCM")] + [string]$encryptionAlgorithm = "AES", + [Parameter (Mandatory = $false)] + [ValidateSet("PSK", "x.509")] + [string]$authenticationMode = "PSK", + [Parameter (Mandatory = $false)] + [switch]$enablepfs = $true, + [Parameter (Mandatory = $false)] + [ValidateSet("dh2", "dh5", "dh14", "dh15", "dh16")] + [string]$dhgroup = "dh14", + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$psk, + [Parameter (Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$extension, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -36677,18 +36859,19 @@ function Add-NsxIPsecSite { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_IPsec.edgeId - $_IPsec.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_IPsec -Query 'descendant::edgeId')) ) | out-null + $_IPsec.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_IPsec -query 'descendant::edgeId')) ) | Out-Null #For first site, you need to recreate sites field (by default a empty System.Object) if ($_IPsec.sites.gettype().basetype -eq [System.Object]) { - $_IPsec.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_IPsec -Query 'descendant::sites')) ) | out-null + $_IPsec.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_IPsec -query 'descendant::sites')) ) | Out-Null [System.XML.XMLElement]$xmlMemberSites = $_IPsec.OwnerDocument.CreateElement("sites") - $_IPsec.appendChild($xmlMemberSites) | out-null + $_IPsec.appendChild($xmlMemberSites) | Out-Null [System.XML.XMLElement]$xmlMember = $_IPsec.OwnerDocument.CreateElement("site") - $xmlMemberSites.appendChild($xmlMember) | out-null - } else { + $xmlMemberSites.appendChild($xmlMember) | Out-Null + } + else { [System.XML.XMLElement]$xmlMember = $_IPsec.OwnerDocument.CreateElement("site") - $_IPsec.Sites.appendChild($xmlMember) | out-null + $_IPsec.Sites.appendChild($xmlMember) | Out-Null } Add-XmlElement -xmlRoot $xmlMember -xmlElementName "enabled" -xmlElementText $Enabled.ToString().ToLower() @@ -36710,14 +36893,14 @@ function Add-NsxIPsecSite { } [System.XML.XMLElement]$xmllocalsubnet = $xmlMember.OwnerDocument.CreateElement('localSubnets') - $xmlMember.Appendchild($xmllocalsubnet) | out-null + $xmlMember.Appendchild($xmllocalsubnet) | Out-Null foreach ($subnet in $localSubnet) { Add-XmlElement -xmlRoot $xmllocalsubnet -xmlElementName "subnet" -xmlElementText $subnet.ToString() } [System.XML.XMLElement]$xmlpeersubnet = $xmlMember.OwnerDocument.CreateElement('peerSubnets') - $xmlMember.Appendchild($xmlpeersubnet) | out-null + $xmlMember.Appendchild($xmlpeersubnet) | Out-Null foreach ($subnet in $peerSubnet) { Add-XmlElement -xmlRoot $xmlpeersubnet -xmlElementName "subnet" -xmlElementText $subnet.ToString() @@ -36729,7 +36912,8 @@ function Add-NsxIPsecSite { if ( $authenticationMode -eq "PSK" ) { if ( $PsBoundParameters.ContainsKey("psk") ) { Add-XmlElement -xmlRoot $xmlMember -xmlElementName "psk" -xmlElementText $psk - } else { + } + else { #throw "You need to specify a PSK (-psk)" } } @@ -36745,13 +36929,13 @@ function Add-NsxIPsecSite { $URI = "/api/4.0/edges/$edgeId/ipsec/config" $body = $_IPsec.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($EdgeId)" -status "IPsec config for $($EdgeId)" - $null = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - write-progress -activity "Update Edge Services Gateway $($EdgeId)" -completed + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Status "IPsec config for $($EdgeId)" + $null = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($EdgeId)" -Completed #Get updated ipsec $URI = "/api/4.0/edges/$edgeId/ipsec/config" - $return = invoke-nsxrestmethod -method "get" -uri $URI -connection $connection + $return = Invoke-NsxRestMethod -method "get" -URI $URI -connection $connection $return.ipsec #Add-XmlElement -xmlroot $Pool -xmlElementName "edgeId" -xmlElementText $edgeId #$Pool @@ -36762,7 +36946,7 @@ function Add-NsxIPsecSite { } -function Copy-NsxEdge{ +function Copy-NsxEdge { <# .SYNOPSIS @@ -36843,137 +37027,137 @@ function Copy-NsxEdge{ #> - [CmdletBinding(DefaultParameterSetName="Default")] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope="Function", Target="*")] # Unable to remove without breaking backward compatibilty. - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - param ( - - [Parameter (Mandatory=$true, ValueFromPipeline=$true)] - #PowerNSX Edge Object as retrieved with Get-NsxEdge representing the source edge to duplicate. - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge, - [Parameter (Mandatory=$true)] - #Duplicated Edge Name (base of appliance name and default for fqdn) - [ValidateNotNullOrEmpty()] - [string]$Name, - [Parameter (Mandatory=$true,ParameterSetName="ResourcePool")] - #PowerCLI Resource Pool object representing vSphere Resource Pool to which duplicated edge appliances are deployed. If Resource Pool and Cluster are not specified, Copy-NsxEdge places the duplicated edge appliances in the same location as the source edge. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, - [Parameter (Mandatory=$true,ParameterSetName="Cluster")] - #PowerCLI Cluster object representing vSphere Cluster to which duplicated edge appliances are deployed. If Resource Pool and Cluster are not specified, Copy-NsxEdge places the duplicated edge appliances in the same location as the source edge. - [ValidateScript({ - if ( $_ -eq $null ) { throw "Must specify Cluster."} - if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled."} + [CmdletBinding(DefaultParameterSetName = "Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] # Unable to remove without breaking backward compatibilty. Alternate credential parameter exists. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Scope = "Function", Target = "*")] # Unable to remove without breaking backward compatibilty. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + param ( + + [Parameter (Mandatory = $true, ValueFromPipeline = $true)] + #PowerNSX Edge Object as retrieved with Get-NsxEdge representing the source edge to duplicate. + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge, + [Parameter (Mandatory = $true)] + #Duplicated Edge Name (base of appliance name and default for fqdn) + [ValidateNotNullOrEmpty()] + [string]$Name, + [Parameter (Mandatory = $true, ParameterSetName = "ResourcePool")] + #PowerCLI Resource Pool object representing vSphere Resource Pool to which duplicated edge appliances are deployed. If Resource Pool and Cluster are not specified, Copy-NsxEdge places the duplicated edge appliances in the same location as the source edge. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ResourcePoolInterop]$ResourcePool, + [Parameter (Mandatory = $true, ParameterSetName = "Cluster")] + #PowerCLI Cluster object representing vSphere Cluster to which duplicated edge appliances are deployed. If Resource Pool and Cluster are not specified, Copy-NsxEdge places the duplicated edge appliances in the same location as the source edge. + [ValidateScript( { + if ( $_ -eq $null ) { throw "Must specify Cluster." } + if ( -not $_.DrsEnabled ) { throw "Cluster is not DRS enabled." } $true })] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, - [Parameter (Mandatory=$false)] - #PowerCLI Datastore object representing vSphere datastore to which the primary duplicated edge appliance is deployed. Defaults to the same location as the source edge. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, - [Parameter (Mandatory=$false)] - #Edge CLI user name. Defaults to 'admin' - [ValidateNotNullOrEmpty()] - [String]$Username="admin", - [Parameter (Mandatory=$true)] - #Edge CLI password - [ValidateNotNullOrEmpty()] - [String]$Password, - [Parameter (Mandatory=$false)] - #PowerCLI Datastore object representing vSphere datastore to which the secondary edge appliance is deployed (requires HA). Defaults to the same location as the source edge. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$HADatastore, - [Parameter (Mandatory=$false)] - #Edge Appliance Form Factor. See NSX Documentation for appliance form factor details and recommendations. Defaults to the source edge form factor. - [ValidateSet("compact","large","xlarge","quadlarge",IgnoreCase=$false)] - [string]$FormFactor, - [Parameter (Mandatory=$false)] - #PowerCLI Folder object representing the vSphere VM inventory folder in which the appliances should be deployed. Defaults to the source edge location. - [ValidateNotNullOrEmpty()] - [VMware.VimAutomation.ViCore.Interop.V1.Inventory.FolderInterop]$VMFolder, - [Parameter (Mandatory=$false)] - #Tenant name used in appliance naming and API references. Defaults to the source edge tenant. - [ValidateNotNullOrEmpty()] - [String]$Tenant, - [Parameter (Mandatory=$false)] - #FQDN of Edge. Defaults to $name (undotted). - [ValidateNotNullOrEmpty()] - [String]$Hostname=$Name, - [Parameter (Mandatory=$false)] - #Enable SSH on the duplicated Edge. Defaults to source edge setting. - [ValidateNotNullOrEmpty()] - [switch]$EnableSSH, - [Parameter (Mandatory=$false)] - #Enable autogenerated firewall rules on the duplicated Edge. Defaults to source edge setting. - [ValidateNotNullOrEmpty()] - [switch]$AutoGenerateRules, - [Parameter (Mandatory=$false)] - #Enable firewall on the duplicated Edge. Defaults to source edge setting. - [switch]$FwEnabled, - [Parameter (Mandatory=$false)] - #Configure default firewall policy on the duplicated Edge. Defaults to source edge setting. - [switch]$FwDefaultPolicyAllow, - [Parameter (Mandatory=$false)] - #Configure default firewall action logging on the duplicated Edge. Defaults to source edge setting. - [switch]$FwLoggingEnabled, - [Parameter (Mandatory=$false)] - #Configure HA on the duplicated Edge. Defaults to source edge setting. - [ValidateNotNullOrEmpty()] - [switch]$EnableHa, - [Parameter (Mandatory=$false)] - #Configure HA dead time on the duplicated Edge. Defaults to source edge setting. - [ValidateRange(3,900)] - [int]$HaDeadTime, - [Parameter (Mandatory=$false)] - #Configure HA vNIC on the duplicated Edge. Defaults to source edge setting. - [ValidateRange(0,9)] - [int]$HaVnic, - [Parameter (Mandatory=$false)] - #Configure syslog on the duplicated Edge. Defaults to source edge setting. - [switch]$EnableSyslog, - [Parameter (Mandatory=$false)] - #Configure syslog server(s) on the duplicated Edge. Defaults to source edge setting. If specified, overrides source edge settings (not merged). - [ValidateNotNullOrEmpty()] - [string[]]$SyslogServer, - [Parameter (Mandatory=$false)] - [ValidateSet("udp","tcp",IgnoreCase=$true)] - #Configure syslog protocol on the duplicated Edge. Defaults to source edge setting. - [string]$SyslogProtocol, - [Parameter (Mandatory=$false)] - #Interface definitions. Specified as Interface Specs as returned by New-NsxEdgeInterfaceSpec. Must contain the SAME number of interfaces with the same interface indexes, addressgroups per interface, and primary and secondary addresses per addressgroup as the source edge interface. - #Netmasks and the CIDR network defined in each addressgroup must match that of the source edge. - # - #In summary, the only thing that can (must) change from the source edge is the primary and any secondary IP Addresses for every addressgroup on every interface, and potentially, the connected network. - #If not specified, the user is interactively prompted for replacement addresses on each primary and secondary address on each addressgroup on each enabled VNIC on the source edge. - [ValidateScript({ ValidateEdgeInterfaceSpec $_ })] - [System.Xml.XmlElement[]]$Interface, - [Parameter (Mandatory=$false)] - #Any self signed certificates found on the source edge will be regenerated on the destination edge as new certificates with the fqdn as the cn (all other details duplicated), and services configured to use the regenerated certificate. Set this to $false to disable autogeneration of certificates (services will have to be manually reconfigured to use a different certificate) - [switch]$CertFixUps=$true, - [Parameter (Mandatory=$false)] - #Any self signed certificates generated on the new edge will have the fqdn as the cn. Set -SelfSignedCertificateCN to change the CN used (for all Self Signed certificates) - [string]$SelfSignedCertificateCN, - [Parameter (Mandatory=$false)] - #Any NAT rules found on the source edge that specify any 'local' ip (defined on any interface), will be regenerated on the destination edge with the ip updated to the eqivalent IP on the new edge. Set this to $false to disable automatic fixups of NAT rules. Any rules referencing edge local ip addresses will need to be manually updated. - [switch]$NatRuleFixups=$true, - [Parameter (Mandatory=$false)] - #If routerId is defined and matches any 'local' ip (defined on any interface), it will be updated to match the equivalent IP on the new edge. Set to $false to disable automatic fixup. RouterID will need to be manually updated in this case. - [switch]$RouterIdFixup=$true, - [Parameter (Mandatory=$false)] - #Any user defined local firewall rules with locally scoped objects (ipsets, services, servicegroups) referenced will be updated to match the equivalent object on the new edge. Set to $false to disable automatic fixup. User defined firewall rules will not be duplicated and will need to be manually recreated in this case. - [switch]$FirewallFixups=$true, - [Parameter (Mandatory=$false)] - #Any locally scoped objects (ipsets, services, servicegroups and servicegroup membership) defined within the edges local scope will be recreated on the new edge. This is required for FirewallFixups. - [switch]$LocalObjectFixups=$true, - [Parameter (Mandatory=$false)] - #Number of days any regenerated certificates are valid for. Defaults to 365 - [int]$CertValidNumberOfDays=365, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.ClusterInterop]$Cluster, + [Parameter (Mandatory = $false)] + #PowerCLI Datastore object representing vSphere datastore to which the primary duplicated edge appliance is deployed. Defaults to the same location as the source edge. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$Datastore, + [Parameter (Mandatory = $false)] + #Edge CLI user name. Defaults to 'admin' + [ValidateNotNullOrEmpty()] + [String]$Username = "admin", + [Parameter (Mandatory = $true)] + #Edge CLI password + [ValidateNotNullOrEmpty()] + [String]$Password, + [Parameter (Mandatory = $false)] + #PowerCLI Datastore object representing vSphere datastore to which the secondary edge appliance is deployed (requires HA). Defaults to the same location as the source edge. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.DatastoreManagement.DatastoreInterop]$HADatastore, + [Parameter (Mandatory = $false)] + #Edge Appliance Form Factor. See NSX Documentation for appliance form factor details and recommendations. Defaults to the source edge form factor. + [ValidateSet("compact", "large", "xlarge", "quadlarge", IgnoreCase = $false)] + [string]$FormFactor, + [Parameter (Mandatory = $false)] + #PowerCLI Folder object representing the vSphere VM inventory folder in which the appliances should be deployed. Defaults to the source edge location. + [ValidateNotNullOrEmpty()] + [VMware.VimAutomation.ViCore.Interop.V1.Inventory.FolderInterop]$VMFolder, + [Parameter (Mandatory = $false)] + #Tenant name used in appliance naming and API references. Defaults to the source edge tenant. + [ValidateNotNullOrEmpty()] + [String]$Tenant, + [Parameter (Mandatory = $false)] + #FQDN of Edge. Defaults to $name (undotted). + [ValidateNotNullOrEmpty()] + [String]$Hostname = $Name, + [Parameter (Mandatory = $false)] + #Enable SSH on the duplicated Edge. Defaults to source edge setting. + [ValidateNotNullOrEmpty()] + [switch]$EnableSSH, + [Parameter (Mandatory = $false)] + #Enable autogenerated firewall rules on the duplicated Edge. Defaults to source edge setting. + [ValidateNotNullOrEmpty()] + [switch]$AutoGenerateRules, + [Parameter (Mandatory = $false)] + #Enable firewall on the duplicated Edge. Defaults to source edge setting. + [switch]$FwEnabled, + [Parameter (Mandatory = $false)] + #Configure default firewall policy on the duplicated Edge. Defaults to source edge setting. + [switch]$FwDefaultPolicyAllow, + [Parameter (Mandatory = $false)] + #Configure default firewall action logging on the duplicated Edge. Defaults to source edge setting. + [switch]$FwLoggingEnabled, + [Parameter (Mandatory = $false)] + #Configure HA on the duplicated Edge. Defaults to source edge setting. + [ValidateNotNullOrEmpty()] + [switch]$EnableHa, + [Parameter (Mandatory = $false)] + #Configure HA dead time on the duplicated Edge. Defaults to source edge setting. + [ValidateRange(3, 900)] + [int]$HaDeadTime, + [Parameter (Mandatory = $false)] + #Configure HA vNIC on the duplicated Edge. Defaults to source edge setting. + [ValidateRange(0, 9)] + [int]$HaVnic, + [Parameter (Mandatory = $false)] + #Configure syslog on the duplicated Edge. Defaults to source edge setting. + [switch]$EnableSyslog, + [Parameter (Mandatory = $false)] + #Configure syslog server(s) on the duplicated Edge. Defaults to source edge setting. If specified, overrides source edge settings (not merged). + [ValidateNotNullOrEmpty()] + [string[]]$SyslogServer, + [Parameter (Mandatory = $false)] + [ValidateSet("udp", "tcp", IgnoreCase = $true)] + #Configure syslog protocol on the duplicated Edge. Defaults to source edge setting. + [string]$SyslogProtocol, + [Parameter (Mandatory = $false)] + #Interface definitions. Specified as Interface Specs as returned by New-NsxEdgeInterfaceSpec. Must contain the SAME number of interfaces with the same interface indexes, addressgroups per interface, and primary and secondary addresses per addressgroup as the source edge interface. + #Netmasks and the CIDR network defined in each addressgroup must match that of the source edge. + # + #In summary, the only thing that can (must) change from the source edge is the primary and any secondary IP Addresses for every addressgroup on every interface, and potentially, the connected network. + #If not specified, the user is interactively prompted for replacement addresses on each primary and secondary address on each addressgroup on each enabled VNIC on the source edge. + [ValidateScript( { ValidateEdgeInterfaceSpec $_ })] + [System.Xml.XmlElement[]]$Interface, + [Parameter (Mandatory = $false)] + #Any self signed certificates found on the source edge will be regenerated on the destination edge as new certificates with the fqdn as the cn (all other details duplicated), and services configured to use the regenerated certificate. Set this to $false to disable autogeneration of certificates (services will have to be manually reconfigured to use a different certificate) + [switch]$CertFixUps = $true, + [Parameter (Mandatory = $false)] + #Any self signed certificates generated on the new edge will have the fqdn as the cn. Set -SelfSignedCertificateCN to change the CN used (for all Self Signed certificates) + [string]$SelfSignedCertificateCN, + [Parameter (Mandatory = $false)] + #Any NAT rules found on the source edge that specify any 'local' ip (defined on any interface), will be regenerated on the destination edge with the ip updated to the eqivalent IP on the new edge. Set this to $false to disable automatic fixups of NAT rules. Any rules referencing edge local ip addresses will need to be manually updated. + [switch]$NatRuleFixups = $true, + [Parameter (Mandatory = $false)] + #If routerId is defined and matches any 'local' ip (defined on any interface), it will be updated to match the equivalent IP on the new edge. Set to $false to disable automatic fixup. RouterID will need to be manually updated in this case. + [switch]$RouterIdFixup = $true, + [Parameter (Mandatory = $false)] + #Any user defined local firewall rules with locally scoped objects (ipsets, services, servicegroups) referenced will be updated to match the equivalent object on the new edge. Set to $false to disable automatic fixup. User defined firewall rules will not be duplicated and will need to be manually recreated in this case. + [switch]$FirewallFixups = $true, + [Parameter (Mandatory = $false)] + #Any locally scoped objects (ipsets, services, servicegroups and servicegroup membership) defined within the edges local scope will be recreated on the new edge. This is required for FirewallFixups. + [switch]$LocalObjectFixups = $true, + [Parameter (Mandatory = $false)] + #Number of days any regenerated certificates are valid for. Defaults to 365 + [int]$CertValidNumberOfDays = 365, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin {} @@ -36987,9 +37171,9 @@ function Copy-NsxEdge{ #that is not relevant to the new edge before initial post. #Remove EdgeSummary... - $edgeSummary = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query 'descendant::edgeSummary') + $edgeSummary = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query 'descendant::edgeSummary') if ( $edgeSummary ) { - $_Edge.RemoveChild($edgeSummary) | out-null + $_Edge.RemoveChild($edgeSummary) | Out-Null } #Naming @@ -37001,21 +37185,21 @@ function Copy-NsxEdge{ } #Appliances element - $FirstAppliance = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "descendant::appliances/appliance") | where-object { $_.highAvailabilityIndex -eq "0" } - switch ($psCmdlet.ParameterSetName){ - "Default" { - write-debug "$($MyInvocation.MyCommand.Name) : Invoked with Default ParameterSet" + $FirstAppliance = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "descendant::appliances/appliance") | Where-Object { $_.highAvailabilityIndex -eq "0" } + switch ($psCmdlet.ParameterSetName) { + "Default" { + Write-Debug "$($MyInvocation.MyCommand.Name) : Invoked with Default ParameterSet" if ( $FirstAppliance ) { $resPoolId = $FirstAppliance.resourcePoolId } if ( -not $resPoolId ) { throw "Unable to determine existing edges resource pool. Try again and specify appliance resource pool." } } - "Cluster" { - write-debug "$($MyInvocation.MyCommand.Name) : Invoked with Cluster ParameterSet" - $ResPoolId = $($cluster | get-resourcepool | where-object { $_.parent.id -eq $cluster.id }).extensiondata.moref.value + "Cluster" { + Write-Debug "$($MyInvocation.MyCommand.Name) : Invoked with Cluster ParameterSet" + $ResPoolId = $($cluster | Get-ResourcePool | Where-Object { $_.parent.id -eq $cluster.id }).extensiondata.moref.value } - "ResourcePool" { - write-debug "$($MyInvocation.MyCommand.Name) : Invoked with ResourcePool ParameterSet" + "ResourcePool" { + Write-Debug "$($MyInvocation.MyCommand.Name) : Invoked with ResourcePool ParameterSet" $ResPoolId = $ResourcePool.extensiondata.moref.value } } @@ -37037,60 +37221,60 @@ function Copy-NsxEdge{ } #Ditch the old appliances nodes completely and rebuild. - [system.xml.xmlElement]$xmlAppliances = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "descendant::appliances") - $oldAppliancesNodes = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $xmlAppliances -Query "child::appliance") + [system.xml.xmlElement]$xmlAppliances = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "descendant::appliances") + $oldAppliancesNodes = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $xmlAppliances -query "child::appliance") foreach ( $node in $oldAppliancesNodes) { - write-debug "$($MyInvocation.MyCommand.Name) : Removing appliance node from Edge XML with moref $($node.vmId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Removing appliance node from Edge XML with moref $($node.vmId)" $null = $xmlAppliances.RemoveChild($node) } #If user has overridden appliance size... if ( $PsBoundParameters.ContainsKey("Formfactor")) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting formfactor to $formfactor" + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting formfactor to $formfactor" $xmlAppliances.applianceSize = $FormFactor } - write-debug "$($MyInvocation.MyCommand.Name) : Creating new primary appliance node with ResourcePool moref: $ResPoolId, Datastore moref: $datastoreid, Folder moref: $VMFolderId." + Write-Debug "$($MyInvocation.MyCommand.Name) : Creating new primary appliance node with ResourcePool moref: $ResPoolId, Datastore moref: $datastoreid, Folder moref: $VMFolderId." [System.XML.XMLElement]$xmlAppliance = $XMLDoc.CreateElement("appliance") - $xmlAppliances.appendChild($xmlAppliance) | out-null + $xmlAppliances.appendChild($xmlAppliance) | Out-Null Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "resourcePoolId" -xmlElementText $ResPoolId Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "datastoreId" -xmlElementText $datastoreId Add-XmlElement -xmlRoot $xmlAppliance -xmlElementName "vmFolderId" -xmlElementText $VmFolderId #Kill the version props on edge and all features - $VersionNodes = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "descendant::version") + $VersionNodes = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "descendant::version") foreach ($node in $VersionNodes) { $null = $node.ParentNode.RemoveChild($Node) } #Kill any NAT Rule IDs/Tags (must be regenerated by API) - $NATRuleIds = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "child::features/nat/natRules/natRule/ruleId") + $NATRuleIds = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "child::features/nat/natRules/natRule/ruleId") foreach ($node in $NATRuleIds) { $null = $node.ParentNode.RemoveChild($Node) } - $NATRuleTags = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "child::features/nat/natRules/natRule/ruleTag") + $NATRuleTags = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "child::features/nat/natRules/natRule/ruleTag") foreach ($node in $NATRuleTags) { $null = $node.ParentNode.RemoveChild($Node) } #check for bgp neighbour credentials (cant be retrieved using API) - $peerPasswords = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "child::features/routing/bgp/bgpNeighbours/bgpNeighbour/password") + $peerPasswords = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "child::features/routing/bgp/bgpNeighbours/bgpNeighbour/password") foreach ($node in $peerPasswords) { - write-warning "BGP peer password defined for peer $($node.ParentNode.ipAddress). Password will be cleared on duplicated edge and must be manually reconfigured." + Write-Warning "BGP peer password defined for peer $($node.ParentNode.ipAddress). Password will be cleared on duplicated edge and must be manually reconfigured." $null = $node.ParentNode.RemoveChild($node) } #Check if IPSec is enabled - if so, warn about the removal of the global PSK if ( $_Edge.features.ipsec.enabled -eq 'true') { - write-warning "The IPSec feature is enabled. The global and any site specific Pre Shared Keys will be set to a random value on the duplicated edge and must be manually reconfigured." + Write-Warning "The IPSec feature is enabled. The global and any site specific Pre Shared Keys will be set to a random value on the duplicated edge and must be manually reconfigured." } - $pskNodes = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge.features.ipsec -Query "descendant::psk") + $pskNodes = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge.features.ipsec -query "descendant::psk") foreach ($node in $pskNodes) { #just invent a random 8 char (lower/upper/int) string and set the PSK to it. - $randomString = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 8 | foreach-object {[char]$_}) + $randomString = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 8 | ForEach-Object { [char]$_ }) $node."#text" = $randomString Write-Warning "IPSec PSK for site $($node.ParentNode.tostring()) set to $randomString. Please update manually as required." } @@ -37102,26 +37286,26 @@ function Copy-NsxEdge{ #but we will still attempt to provision the edge (dont know yet if invalid certs in config cause edge API to throw, but initial testing indicates it doesnt... Will rethink if this proves inaccurate...) if ( $certfixups ) { $SSCertificates = @() - $Certificates = $edge | Get-NsxEdgeCertificate -connection $Connection + $Certificates = $edge | Get-NsxEdgeCertificate -Connection $Connection foreach ( $cert in $Certificates ) { if ( $cert.certificateType -eq 'certificate_self_signed') { if ( $CertFixUps ) { - write-warning "Found self signed certificate $($cert.name) on source edge. Certificate will be regenerated on duplicated edge." + Write-Warning "Found self signed certificate $($cert.name) on source edge. Certificate will be regenerated on duplicated edge." #Store the certificate for later use once the edge is created with the replacement certificate. $SSCertificates += $cert } else { - write-warning "Found self signed certificate $($cert.name) on source edge. Any service using this certificate will have an invalid configuration on the duplicated edge and must be manually corrected." + Write-Warning "Found self signed certificate $($cert.name) on source edge. Any service using this certificate will have an invalid configuration on the duplicated edge and must be manually corrected." } } else { - write-warning "Found certificate $($cert.name) on source edge which is signed by an external CA. This certificate cannot be exported and must be manually reimported/generated on the destination edge. Any service using this certificate will have an invalid configuration on the duplicated edge and must be manually corrected." + Write-Warning "Found certificate $($cert.name) on source edge which is signed by an external CA. This certificate cannot be exported and must be manually reimported/generated on the destination edge. Any service using this certificate will have an invalid configuration on the duplicated edge and must be manually corrected." } } } #Get the features element. - [System.XML.XMLElement]$xmlFeatures = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "child::features") + [System.XML.XMLElement]$xmlFeatures = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "child::features") if ( $EnableHA -or ( $_Edge.features.highAvailability.enabled -eq "true" )) { @@ -37131,15 +37315,15 @@ function Copy-NsxEdge{ $HADatastoreId = $HAdatastore.extensiondata.moref.value } #Else if the source edge has a HA appliance, use that appliances datastore - elseif ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlAppliances -Query "appliance[highAvailabilityIndex=1]") ) { - $HADatastoreId = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $xmlAppliances -Query "appliance[highAvailabilityIndex=1]").datastoreId + elseif ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlAppliances -query "appliance[highAvailabilityIndex=1]") ) { + $HADatastoreId = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $xmlAppliances -query "appliance[highAvailabilityIndex=1]").datastoreId } #Else, use the first appliances datastore else { $HAdatastoreId = $datastoreId } - write-debug "$($MyInvocation.MyCommand.Name) : Source edge is HA or user requested HA. Generating secondary appliance node with Datastore moref: $HAdatastoreId " + Write-Debug "$($MyInvocation.MyCommand.Name) : Source edge is HA or user requested HA. Generating secondary appliance node with Datastore moref: $HAdatastoreId " #Define the HA appliance node [System.XML.XMLElement]$xmlAppliance = $XMLDoc.CreateElement("appliance") @@ -37157,7 +37341,7 @@ function Copy-NsxEdge{ #Node is not guaranteed to exist, have to test first. Love the consistency if ( $PsBoundParameters.containsKey('HaVnic')) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "features/highAvailability/vnic")) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "features/highAvailability/vnic")) { $_Edge.features.highAvailability.vnic = $HAvnic.ToString() } else { @@ -37169,51 +37353,51 @@ function Copy-NsxEdge{ #Configure the syslog element if ( $PSBoundParameters.ContainsKey("EnableSyslog")) { - write-debug "$($MyInvocation.MyCommand.Name) : Enabling Syslog" + Write-Debug "$($MyInvocation.MyCommand.Name) : Enabling Syslog" $_Edge.features.syslog.enabled = $EnableSyslog.ToString().ToLower() } if ( $PsBoundParameters.containsKey('SyslogProtocol')) { - write-debug "$($MyInvocation.MyCommand.Name) : Configuring Syslog Protocol" + Write-Debug "$($MyInvocation.MyCommand.Name) : Configuring Syslog Protocol" $_Edge.features.syslog.protocol = $SyslogProtocol.ToString() } #If user specified syslog server address, then we have to kill any existing config. if ( $PsBoundParameters.containsKey('SyslogServer')) { - $ExistingSyslogServerAddress = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge.features.syslog -Query "serverAddresses") - if ( $ExistingSyslogServerAddress ) { - write-debug "$($MyInvocation.MyCommand.Name) : Removing Existing Syslog servers (overidden by user)" + $ExistingSyslogServerAddress = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge.features.syslog -query "serverAddresses") + if ( $ExistingSyslogServerAddress ) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Removing Existing Syslog servers (overidden by user)" $_Edge.features.syslog.RemoveChild($ExistingSyslogServerAddress) } [System.XML.XMLElement]$xmlServerAddresses = $XMLDoc.CreateElement("serverAddresses") - $_Edge.features.syslog.appendChild($xmlServerAddresses) | out-null + $_Edge.features.syslog.appendChild($xmlServerAddresses) | Out-Null foreach ( $server in $SyslogServer ) { - write-debug "$($MyInvocation.MyCommand.Name) : Adding syslog server element for $server" + Write-Debug "$($MyInvocation.MyCommand.Name) : Adding syslog server element for $server" Add-XmlElement -xmlRoot $xmlServerAddresses -xmlElementName "ipAddress" -xmlElementText $server.ToString() } } #Enable/Disable FW if ( $PSBoundParameters.ContainsKey("FwEnabled")) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting Firewall to $FwEnabled" + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting Firewall to $FwEnabled" $_Edge.features.firewall.enabled = $FwEnabled.ToString().ToLower() } if ( $PsBoundParameters.ContainsKey("FwLoggingEnabled")) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting Firewall Logging to $FwLoggingEnabled" + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting Firewall Logging to $FwLoggingEnabled" $_Edge.features.firewall.loggingEnabled = $FwLoggingEnabled.ToString().ToLower() } #Override fw default policy if user specifies... if ( $PsBoundParameters.ContainsKey("FwDefaultPolicyAllow")) { if ( $FwDefaultPolicyAllow ) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting default firewall policy to accept" + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting default firewall policy to accept" $_Edge.features.firewwall.defaultPolicy.action = "accept" } else { - write-debug "$($MyInvocation.MyCommand.Name) : Setting default firewall policy to deny" + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting default firewall policy to deny" $_Edge.features.firewwall.defaultPolicy.action = "deny" } } @@ -37221,7 +37405,7 @@ function Copy-NsxEdge{ #Override Rule Autoconfiguration if user specifies if ( $PsBoundParameters.ContainsKey("AutoGenerateRules")) { if ( $AutoGenerateRules ) { - write-debug "$($MyInvocation.MyCommand.Name) : Configuring rule autoconfiguration as $AutoGenerateRules" + Write-Debug "$($MyInvocation.MyCommand.Name) : Configuring rule autoconfiguration as $AutoGenerateRules" $_Edge.autoConfiguration.enabled = $AutoGenerateRules.ToString().ToLower() } } @@ -37230,22 +37414,22 @@ function Copy-NsxEdge{ Add-XmlElement -xmlRoot $_Edge.cliSettings -xmlElementName "password" -xmlElementText $Password if ( $PsBoundParameters.ContainsKey('EnableSSH') ) { - write-debug "$($MyInvocation.MyCommand.Name) : Configuring SSH to be $EnableSssh" + Write-Debug "$($MyInvocation.MyCommand.Name) : Configuring SSH to be $EnableSssh" $_Edge.cliSettings.remoteAccess = $EnableSsh.ToString().ToLower() } #DNS Settings if ( $PsBoundParameters.ContainsKey('PrimaryDnsServer') -or $PSBoundParameters.ContainsKey('SecondaryDNSServer') -or $PSBoundParameters.ContainsKey('DNSDomainName') ) { - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "child::dnsClient")) { - write-debug "$($MyInvocation.MyCommand.Name) : Generating dnsClient element" + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "child::dnsClient")) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Generating dnsClient element" [System.XML.XMLElement]$xmlDnsClient = $XMLDoc.CreateElement("dnsClient") $null = $_Edge.appendChild($xmlDnsClient) } if ( $PsBoundParameters.ContainsKey('PrimaryDnsServer') ) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting Primary DNS to $PrimaryDnsServer" - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge.dnsClient -Query "primaryDNS")) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting Primary DNS to $PrimaryDnsServer" + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge.dnsClient -query "primaryDNS")) { Add-XmlElement -xmlRoot $_Edge.dnsClient -xmlElementName "primaryDns" -xmlElementText $PrimaryDnsServer } else { @@ -37254,8 +37438,8 @@ function Copy-NsxEdge{ } if ( $PsBoundParameters.ContainsKey('SecondaryDNSServer') ) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting Secondary DNS to $SecondaryDnsServer" - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge.dnsClient -Query "secondaryDNS")) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting Secondary DNS to $SecondaryDnsServer" + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge.dnsClient -query "secondaryDNS")) { Add-XmlElement -xmlRoot $_Edge.dnsClient -xmlElementName "secondaryDNS" -xmlElementText $SecondaryDNSServer } else { @@ -37264,8 +37448,8 @@ function Copy-NsxEdge{ } if ( $PsBoundParameters.ContainsKey('DNSDomainName') ) { - write-debug "$($MyInvocation.MyCommand.Name) : Setting DNS domain name to $DNSDomainName" - if ( -not (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge.dnsClient -Query "domainName")) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Setting DNS domain name to $DNSDomainName" + if ( -not (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge.dnsClient -query "domainName")) { Add-XmlElement -xmlRoot $_Edge.dnsClient -xmlElementName "domainName" -xmlElementText $DNSDomainName } else { @@ -37288,14 +37472,14 @@ function Copy-NsxEdge{ foreach ( $Vnic in $_Edge.vnics.vnic ) { - write-debug "$($MyInvocation.MyCommand.Name) : Processing VNIC $($Vnic.name)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Processing VNIC $($Vnic.name)" #First check if user has specified any interface specs: $UserVnic = $false if ( $PsBoundParameters.ContainsKey("Interface")) { #have they specified one for this specific vnic? - $UserVnic = $Interface | where-object { $_.index -eq $Vnic.Index } + $UserVnic = $Interface | Where-Object { $_.index -eq $Vnic.Index } If ( $UserVnic ) { #If so, we have to validate to ensure its valid. @@ -37303,12 +37487,12 @@ function Copy-NsxEdge{ [System.Array]$VnicAddressGroups = $Vnic.Addressgroups.AddressGroup #Check the right number of addressgroups. If different number, we cant guarantee that we can modify any service configuration for new listener addresses, or that the default route is still valid. - if ( $UserVnicAddressGroups.count -ne $VnicAddressGroups.count ) { + if ( $UserVnicAddressGroups.count -ne $VnicAddressGroups.count ) { Throw "Source Vnic '$($vnic.Name)' has different number of addressgroups ($($VnicAddressGroups.count)) to specified Vnic '$($UserVnic.Name)' ($($UserVnicAddressGroups.count)) " } - for ( $i=0; ($i -le ($VnicAddressGroups.count -1)); $i++ ) { - write-debug "$($MyInvocation.MyCommand.Name) : Validating AddressGroup $i specified for Vnic $($vnic.name)" + for ( $i = 0; ($i -le ($VnicAddressGroups.count - 1)); $i++ ) { + Write-Debug "$($MyInvocation.MyCommand.Name) : Validating AddressGroup $i specified for Vnic $($vnic.name)" $addressGroup = $VnicAddressGroups[$i] $ExistingPrimaryAddress = $addressGroup.primaryAddress $AddressGroupNetMask = $addressGroup.subnetMask @@ -37317,7 +37501,7 @@ function Copy-NsxEdge{ $NewPrimaryAddress = $UserVnicAddressGroups[$i].PrimaryAddress $NewAddressGroupNetMask = ConvertFrom-Bitmask -bitmask ($UserVnicAddressGroups[$i].subnetPrefixLength) - write-debug "$($MyInvocation.MyCommand.Name) : Existing Primary Address: $ExistingPrimaryAddress, AddressGroup Mask: $AddressGroupNetMask, AddressGroup Network: $AddressGroupNetwork, New Primary Address: $newPrimaryAddress, New AddressGroup NetMask: $NewAddressGroupNetMask" + Write-Debug "$($MyInvocation.MyCommand.Name) : Existing Primary Address: $ExistingPrimaryAddress, AddressGroup Mask: $AddressGroupNetMask, AddressGroup Network: $AddressGroupNetwork, New Primary Address: $newPrimaryAddress, New AddressGroup NetMask: $NewAddressGroupNetMask" if ( ( -not (Test-AddressInNetwork -Network $AddressGroupNetwork -SubnetMask $AddressGroupNetMask -Address $NewPrimaryAddress)) -or ($AllExistingAddresses.contains($NewPrimaryAddress)) -or ($updatedIps.containsvalue($NewPrimaryAddress)) -or ( $NewAddressGroupNetMask -ne $AddressGroupNetMask ) -or (( -not ( [ipaddress]::TryParse($NewPrimaryAddress, [ref][ipaddress]$null))))) { Throw "New Vnic '$($UserVnic.Name)', addressgroup $i Primary address ($NewPrimaryAddress/$NewAddressGroupNetMask) is not valid, not in same subnet as the original address, has different netmask, or conflicts with an interface address on the source edge." @@ -37327,17 +37511,17 @@ function Copy-NsxEdge{ $updatedIps.Add($ExistingPrimaryAddress, $NewPrimaryAddress) #Check secondary addresses - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $addressGroup -Query "secondaryAddresses")) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $addressGroup -query "secondaryAddresses")) { #If we have them, check they are the right number. [System.Array]$VnicSecondaryAddresses = $addressGroup.secondaryAddresses.ipAddress [System.Array]$UserVnicSecondaryAddresses = $UserVnicAddressGroups[$i].secondaryAddresses.ipAddress #Check the right number of secondary addresses. If different number, we cant guarantee that we can modify any service configuration for new listener addresses, or that the default route is still valid. - if ( $UserVnicSecondaryAddresses.count -ne $VnicSecondaryAddresses.count ) { + if ( $UserVnicSecondaryAddresses.count -ne $VnicSecondaryAddresses.count ) { Throw "Source Vnic '$($vnic.Name)', addressgroup $i has different number of secondary addresses ($($VnicSecondaryAddresses.count) to specified Vnic '$($UserVnic.Name)', addressgroup $i ($($UserVnicSecondaryAddresses.count)) " } - for ($j=0; ($j -le ($VnicSecondaryAddresses.Count -1)); $j++) { + for ($j = 0; ($j -le ($VnicSecondaryAddresses.Count - 1)); $j++) { $ExistingSecondaryAddress = $VnicSecondaryAddresses[$j] $NewSecondaryAddress = $UserVnicSecondaryAddresses[$j] @@ -37352,7 +37536,7 @@ function Copy-NsxEdge{ } #Have to do this and first with selectsingle node otherwise PoSH can return a string object if we reference after we remove all child nodes. This ensures we get an XmlElement back - [system.xml.xmlelement]$SecondaryAddressesXml = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $addressgroup -Query "child::secondaryAddresses") + [system.xml.xmlelement]$SecondaryAddressesXml = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $addressgroup -query "child::secondaryAddresses") #secondary addresses are valid. Replace the array in the addressgroup xml $addressGroup.secondaryAddresses.RemoveAll() @@ -37362,7 +37546,7 @@ function Copy-NsxEdge{ } } - write-debug "$($MyInvocation.MyCommand.Name) : User defined vnic spec for this vnic has been specified by user. Importing spec." + Write-Debug "$($MyInvocation.MyCommand.Name) : User defined vnic spec for this vnic has been specified by user. Importing spec." $null = $_Edge.vnics.RemoveChild($vnic) $import = $xmlDoc.ImportNode(($UserVnic), $true) $null = $_Edge.vnics.AppendChild($import) @@ -37370,21 +37554,21 @@ function Copy-NsxEdge{ } if ( -not $userVnic ) { #User has not specified interface information on the command line. - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $Vnic -Query "addressGroups/addressGroup")) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $Vnic -query "addressGroups/addressGroup")) { #Only process if there is already addressing information... - write-debug "$($MyInvocation.MyCommand.Name) : No user defined vnic spec for this vnic has been specified. Prompting user for details" + Write-Debug "$($MyInvocation.MyCommand.Name) : No user defined vnic spec for this vnic has been specified. Prompting user for details" foreach ( $addressGroup in $Vnic.addressGroups.addressGroup ) { - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $addressGroup -Query "primaryAddress")) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $addressGroup -query "primaryAddress")) { $ExistingPrimaryAddress = $addressGroup.primaryAddress $AddressGroupNetMask = $addressGroup.subnetMask $AddressGroupNetwork = Get-NetworkFromHostAddress -Address $ExistingPrimaryAddress -SubnetMask $addressGroupNetMask - write-debug "$($MyInvocation.MyCommand.Name) : Existing Primary Address: $ExistingPrimaryAddress, AddressGroup Mask: $AddressGroupNetMask, AddressGroup Network: $AddressGroupNetwork" + Write-Debug "$($MyInvocation.MyCommand.Name) : Existing Primary Address: $ExistingPrimaryAddress, AddressGroup Mask: $AddressGroupNetMask, AddressGroup Network: $AddressGroupNetwork" $NewPrimaryAddress = Read-Host -Prompt "Enter new primary address for source edge addressgroup with existing IP $($addressGroup.PrimaryAddress) on vnic $($vnic.index)" while ( ( -not (Test-AddressInNetwork -Network $AddressGroupNetwork -SubnetMask $AddressGroupNetMask -Address $NewPrimaryAddress)) -or ($AllExistingAddresses.contains($NewPrimaryAddress)) -or ($updatedIps.containsvalue($NewPrimaryAddress)) -or ( -not ( [ipaddress]::TryParse($NewPrimaryAddress, [ref][ipaddress]$null)))) { - write-warning "New Primary address is not valid, not in same subnet as the original address, or conflicts with an interface address on the source edge." + Write-Warning "New Primary address is not valid, not in same subnet as the original address, or conflicts with an interface address on the source edge." $NewPrimaryAddress = Read-Host -Prompt "Enter new primary address for source edge addressgroup with existing IP $($addressGroup.PrimaryAddress) on vnic $($vnic.index)" } @@ -37395,17 +37579,17 @@ function Copy-NsxEdge{ $addressGroup.PrimaryAddress = $newPrimaryAddress.ToString() } - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $addressGroup -Query "secondaryAddresses")) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $addressGroup -query "secondaryAddresses")) { $NewSecondaryAddresses = @() #Have to iterate through a node collection here, so if the user 'blanks' the secondary ip, we have a node (not a string) to remove... - foreach ($secondaryAddress in (Invoke-XPathQuery -QueryMethod SelectNodes -Node $addressGroup.secondaryAddresses -Query '*')) { + foreach ($secondaryAddress in (Invoke-XpathQuery -QueryMethod SelectNodes -Node $addressGroup.secondaryAddresses -query '*')) { $NewSecondaryAddress = Read-Host -Prompt "Enter new secondary address for source edge addressgroup with existing secondary IP $($secondaryAddress."#text") on vnic $($vnic.index)" - write-debug "$($MyInvocation.MyCommand.Name) : Existing Secondary Address: $secondaryAddress, AddressGroup Mask: $AddressGroupNetMask, AddressGroup Network: $AddressGroupNetwork" + Write-Debug "$($MyInvocation.MyCommand.Name) : Existing Secondary Address: $secondaryAddress, AddressGroup Mask: $AddressGroupNetMask, AddressGroup Network: $AddressGroupNetwork" - while ( ( -not (Test-AddressInNetwork -Network $AddressGroupNetwork -SubnetMask $AddressGroupNetMask -Address $NewSecondaryAddress)) -or ($AllExistingAddresses.contains($NewSecondaryAddress)) -or ($updatedIps.containsvalue($NewSecondaryAddress)) -or ( -not ( [ipaddress]::TryParse($NewSecondaryAddress, [ref][ipaddress]$null)))) { - write-warning "New Secondary address is not valid, not in same subnet as the original address, or conflicts with an interface address on the source edge." + while ( ( -not (Test-AddressInNetwork -Network $AddressGroupNetwork -SubnetMask $AddressGroupNetMask -Address $NewSecondaryAddress)) -or ($AllExistingAddresses.contains($NewSecondaryAddress)) -or ($updatedIps.containsvalue($NewSecondaryAddress)) -or ( -not ( [ipaddress]::TryParse($NewSecondaryAddress, [ref][ipaddress]$null)))) { + Write-Warning "New Secondary address is not valid, not in same subnet as the original address, or conflicts with an interface address on the source edge." $NewSecondaryAddress = Read-Host -Prompt "Enter new secondary address for source edge addressgroup with existing secondary IP $($secondaryAddress."#text") on vnic $($vnic.index)" } @@ -37417,7 +37601,7 @@ function Copy-NsxEdge{ } #Have to do this and first with selectsingle node otherwise PoSH can return a string object if we reference after we remove all child nodes. This ensures we get an XmlElement back - [system.xml.xmlelement]$SecondaryAddressesXml = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $addressgroup -Query "child::secondaryAddresses") + [system.xml.xmlelement]$SecondaryAddressesXml = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $addressgroup -query "child::secondaryAddresses") #secondary addresses are valid. Replace the array in the addressgroup xml $addressGroup.secondaryAddresses.RemoveAll() @@ -37432,46 +37616,46 @@ function Copy-NsxEdge{ #Update any listening services that bind to IPs that have been replaced... #Ipsec... - $ipsecSiteNodes = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "descendant::features/ipsec/sites/site") + $ipsecSiteNodes = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "descendant::features/ipsec/sites/site") foreach ( $node in $ipsecSiteNodes ) { if ( -not $updatedIps.Contains($node.localIp )) { throw "Unable to determine new Local Ip Address for IPSec site $($node.name). This should not happen." } else { - write-warning "Updating listener address for IpSec service $($node.name). Previous Address : $($node.localIp), Updated Address $($updatedIps.item($($node.localIp)))" + Write-Warning "Updating listener address for IpSec service $($node.name). Previous Address : $($node.localIp), Updated Address $($updatedIps.item($($node.localIp)))" #Update the ipsec listener with the IP that replaced the original listen ip $node.localIp = $updatedIps.($node.localIp).ToString() } } #LB - $LBVips = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "descendant::features/loadBalancer/virtualServer") + $LBVips = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "descendant::features/loadBalancer/virtualServer") foreach ( $node in $LBVips ) { if ( -not $updatedIps.Contains($node.ipAddress )) { throw "Unable to determine new Local Ip Address for LoadBalancer VIP $($node.name) with ip address $($node.ipAddress). This should not happen." } else { - write-warning "Updating listener address for LoadBalancer VIP $($node.name). Previous Address : $($node.ipAddress), Updated Address $($updatedIps.item($($node.ipAddress)))" + Write-Warning "Updating listener address for LoadBalancer VIP $($node.name). Previous Address : $($node.ipAddress), Updated Address $($updatedIps.item($($node.ipAddress)))" #Update the LB listener with the IP that replaced the original listen ip $node.ipAddress = $updatedIps.item($node.ipAddress).ToString() } } #SSLVPN - [System.Xml.XmlElement]$SSLVpnListeners = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "descendant::features/sslvpnConfig/serverSettings/serverAddresses") + [System.Xml.XmlElement]$SSLVpnListeners = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "descendant::features/sslvpnConfig/serverSettings/serverAddresses") if ( $SSLVpnListeners ) { - #Not sure if the API will allow and empty serverAddresses element, but just in case.. testing for it here. - if ( (Invoke-XPathQuery -QueryMethod SelectNodes -Node $SSLVpnListeners -Query "child::ipAddress") ) { + #Not sure if the API will allow and empty serverAddresses element, but just in case.. testing for it here. + if ( (Invoke-XpathQuery -QueryMethod SelectNodes -Node $SSLVpnListeners -query "child::ipAddress") ) { foreach ( $node in $SSLVpnListeners ) { if ( -not $updatedIps.Contains($node.ipAddress )) { throw "Unable to determine new listener address for SSL VPN Server with existing ip address $($node.ipAddress). This should not happen." } else { - write-warning "Updating listener address for SSL VPN Server . Previous Address : $($node.ipAddress), Updated Address $($updatedIps.item($($node.ipAddress)))" + Write-Warning "Updating listener address for SSL VPN Server . Previous Address : $($node.ipAddress), Updated Address $($updatedIps.item($($node.ipAddress)))" #Update the LB listener with the IP that replaced the original listen ip $node.ipAddress = $updatedIps.item($node.ipAddress).ToString() } @@ -37481,14 +37665,14 @@ function Copy-NsxEdge{ #RouterId Fixup. If ( $RouterIdFixup ) { - [System.Xml.XmlElement]$RoutingConfig = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Edge -Query "descendant::features/routing/routingGlobalConfig") - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $RoutingConfig -Query "child::routerId")) { + [System.Xml.XmlElement]$RoutingConfig = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Edge -query "descendant::features/routing/routingGlobalConfig") + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $RoutingConfig -query "child::routerId")) { #RouterId is defined. Update it. if ( -not $updatedIps.Contains($RoutingConfig.routerId )) { - write-warning "Unable to update Router Id as existing ID does not belong to any interface address of the original edge. RouterId for the new edge will need to be manually updated." + Write-Warning "Unable to update Router Id as existing ID does not belong to any interface address of the original edge. RouterId for the new edge will need to be manually updated." } else { - write-warning "Updating Router ID. Previous ID : $($RoutingConfig.routerId), Updated ID : $($updatedIps.item($($RoutingConfig.routerId)))" + Write-Warning "Updating Router ID. Previous ID : $($RoutingConfig.routerId), Updated ID : $($updatedIps.item($($RoutingConfig.routerId)))" #Update the LB listener with the IP that replaced the original listen ip $RoutingConfig.routerId = $($updatedIps.item($($RoutingConfig.routerId))).ToString() } @@ -37497,19 +37681,19 @@ function Copy-NsxEdge{ #NatFixups If ( $NatRuleFixups ) { - $UserRules = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "descendant::features/nat/natRules/natRule[ruleType=`'user`']") + $UserRules = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "descendant::features/nat/natRules/natRule[ruleType=`'user`']") if ( $UserRules ) { #There are User defined NAT rules on the Edge. foreach ( $Rule in $UserRules ) { if ( $updatedIps.Contains($Rule.originalAddress )) { - write-warning "Updating user defined NAT Rule with source edge interface address found as original address. Previous Address : $($Rule.originalAddress), Updated address : $($($updatedIps.item($($Rule.originalAddress))))" + Write-Warning "Updating user defined NAT Rule with source edge interface address found as original address. Previous Address : $($Rule.originalAddress), Updated address : $($($updatedIps.item($($Rule.originalAddress))))" #Update the LB listener with the IP that replaced the original listen ip $Rule.originalAddress = $($updatedIps.item($($Rule.originalAddress))).ToString() } if ( $updatedIps.Contains($Rule.translatedAddress )) { - write-warning "Updating user defined NAT Rule with source edge interface address found as translated address. Previous Address : $($Rule.translatedAddress), Updated address : $($($updatedIps.item($($Rule.translatedAddress))))" + Write-Warning "Updating user defined NAT Rule with source edge interface address found as translated address. Previous Address : $($Rule.translatedAddress), Updated address : $($($updatedIps.item($($Rule.translatedAddress))))" #Update the LB listener with the IP that replaced the original listen ip $Rule.translatedAddress = $($updatedIps.item($($Rule.translatedAddress))).ToString() } @@ -37527,7 +37711,7 @@ function Copy-NsxEdge{ #Firewall Fixups #The FW can potentially contain grouping objects or service objects that exist only in the edge scope. API wont let us push invalid FW config, so get user rules here and remove them: - $UserFWRules = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_Edge -Query "descendant::features/firewall/firewallRules/firewallRule[ruleType=`'user`']") + $UserFWRules = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_Edge -query "descendant::features/firewall/firewallRules/firewallRule[ruleType=`'user`']") if ( $UserFWRules ) { foreach ($rule in $UserFwRules ) { $null = $_Edge.features.firewall.firewallRules.RemoveChild($rule) @@ -37537,16 +37721,16 @@ function Copy-NsxEdge{ #################################### # Intial Deployment #################################### - write-debug "$($MyInvocation.MyCommand.Name) : Performing initial creation post of new Edge XML to NSX API" + Write-Debug "$($MyInvocation.MyCommand.Name) : Performing initial creation post of new Edge XML to NSX API" $body = $_Edge.OuterXml $URI = "/api/4.0/edges" - Write-Progress -activity "Creating Edge Services Gateway $Name" - $response = invoke-nsxwebrequest -method "post" -uri $URI -body $body -connection $connection - Write-progress -activity "Creating Edge Services Gateway $Name" -completed + Write-Progress -Activity "Creating Edge Services Gateway $Name" + $response = Invoke-NsxWebRequest -method "post" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Creating Edge Services Gateway $Name" -Completed $edgeId = $response.Headers.Location.split("/")[$response.Headers.Location.split("/").GetUpperBound(0)] - write-debug "$($MyInvocation.MyCommand.Name) : Created Edge $edgeid" + Write-Debug "$($MyInvocation.MyCommand.Name) : Created Edge $edgeid" ################################## # Post Initial Deployment fixup @@ -37555,20 +37739,20 @@ function Copy-NsxEdge{ #First - object creation. We use hashtables to track old -> new id mappings. if ( -not $LocalObjectFixups ) { - write-warning "Local object recreation is disabled. Any edge scoped user defined firewall rules will also not be duplicated as a result." + Write-Warning "Local object recreation is disabled. Any edge scoped user defined firewall rules will also not be duplicated as a result." } else { #Services: #Local Object fixups #Locally scoped objects like ipsets and services/servicegroups can exist on the edge. If FW rules and other (LB only?) config are using them, they have to be recreated. - $LocalServices = Get-NsxService -scopeId $_Edge.id -connection $Connection | where-object { $_.scope.id -eq $_Edge.id } #getting by scope id includes inherited services from globalscope-0, we need to filter for services explicitly defined on this edge too :( - $LocalServiceGroups = Get-NsxServiceGroup -scopeId $_Edge.id -connection $Connection | where-object { $_.scope.id -eq $_Edge.id } - $LocalIpSets = Get-NsxIpSet -scopeId $_Edge.id -connection $Connection | where-object { $_.scope.id -eq $_Edge.id } + $LocalServices = Get-NsxService -scopeId $_Edge.id -Connection $Connection | Where-Object { $_.scope.id -eq $_Edge.id } #getting by scope id includes inherited services from globalscope-0, we need to filter for services explicitly defined on this edge too :( + $LocalServiceGroups = Get-NsxServiceGroup -scopeId $_Edge.id -Connection $Connection | Where-Object { $_.scope.id -eq $_Edge.id } + $LocalIpSets = Get-NsxIpSet -scopeId $_Edge.id -Connection $Connection | Where-Object { $_.scope.id -eq $_Edge.id } $UpdatedServices = @{} foreach ( $Service in $LocalServices ) { - write-warning "Recreating local service $($Service.name) on new edge." + Write-Warning "Recreating local service $($Service.name) on new edge." $NewServiceId = Invoke-NsxRestMethod -method Post -URI "/api/2.0/services/application/$edgeId" -body $Service.OuterXml -connection $Connection $UpdatedServices.Add($Service.objectId, $NewServiceId) } @@ -37580,13 +37764,13 @@ function Copy-NsxEdge{ #Clone the xmlelement so we can modify it $_ServiceGroup = $ServiceGroup.CloneNode($true) - if ( (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_ServiceGroup -Query 'child::member') ) { + if ( (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_ServiceGroup -query 'child::member') ) { #If it has a membership, then remove it. - foreach ( $node in (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_ServiceGroup -Query 'child::member')) { + foreach ( $node in (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_ServiceGroup -query 'child::member')) { $null = $_ServiceGroup.RemoveChild($node) } } - write-warning "Recreating local ServiceGroup $($ServiceGroup.name) on new edge." + Write-Warning "Recreating local ServiceGroup $($ServiceGroup.name) on new edge." $NewServiceGroupId = Invoke-NsxRestMethod -method Post -URI "/api/2.0/services/applicationgroup/$edgeId" -body $_ServiceGroup.OuterXml -connection $Connection $UpdatedServiceGroups.Add($_ServiceGroup.objectId, $NewServiceGroupId) @@ -37595,7 +37779,7 @@ function Copy-NsxEdge{ #ServiceGroup membership foreach ( $ServiceGroup in $LocalServiceGroups ) { - $SGMembers = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $ServiceGroup -Query 'child::member') + $SGMembers = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $ServiceGroup -query 'child::member') foreach ( $member in $SGMembers ) { $UpdatedMemberId = $null switch ($member.objectTypeName) { @@ -37607,13 +37791,13 @@ function Copy-NsxEdge{ #Member is a service... lookup updated value $UpdatedMemberId = $UpdatedServices.Item($member.objectId) } - default { throw "Unknown member type for ServiceGroup: $ServiceGroup.objectId, Member : $($member.objectId), objectType : $_"} + default { throw "Unknown member type for ServiceGroup: $ServiceGroup.objectId, Member : $($member.objectId), objectType : $_" } } #Member may not be local and so update may not be required. - if ( $UpdatedMemberId ) { + if ( $UpdatedMemberId ) { $UpdatedServiceGroupId = $($UpdatedServiceGroups.Item($($ServiceGroup.objectId))) - write-warning "Updating local ServiceGroup membership for ServiceGroup: $UpdatedServiceGroupId, member: $UpdatedMemberId." + Write-Warning "Updating local ServiceGroup membership for ServiceGroup: $UpdatedServiceGroupId, member: $UpdatedMemberId." $null = Invoke-NsxRestMethod -method put -URI "/api/2.0/services/applicationgroup/$UpdatedServiceGroupId/members/$UpdatedMemberId" -connection $Connection } } @@ -37623,7 +37807,7 @@ function Copy-NsxEdge{ $UpdatedIpSets = @{} foreach ( $IpSet in $LocalIpSets ) { - write-warning "Recreating local ipset $($ipset.name) on new edge." + Write-Warning "Recreating local ipset $($ipset.name) on new edge." $NewIpSetId = Invoke-NsxRestMethod -method Post -URI "/api/2.0/services/ipset/$edgeId" -body $IpSet.OuterXml -connection $Connection $UpdatedIpSets.Add($ipSet.objectId, $NewIpSetId) } @@ -37632,7 +37816,7 @@ function Copy-NsxEdge{ #Now we have everything we need to readd the firewall rules with any updated local object references. if ( $LocalObjectFixups -and $FirewallFixups) { - write-warning "Performing firewall fixups for any user based rules that contained local object references on $edgeid." + Write-Warning "Performing firewall fixups for any user based rules that contained local object references on $edgeid." if ( @($UserFwRules).count -ne 0 ) { #If there are userrules to process @@ -37641,23 +37825,23 @@ function Copy-NsxEdge{ foreach ( $rule in $UserFWRules ) { #For each rule - perform any local object updates required, then append it to the new edge fw rules... #IPSets first. - $RuleGroupingObjects = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $rule -Query "child::source/groupingObjectId | child::destination/groupingObjectId") + $RuleGroupingObjects = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $rule -query "child::source/groupingObjectId | child::destination/groupingObjectId") foreach ($GroupingObject in $RuleGroupingObjects) { if ($updatedIpSets.Item($GroupingObject."#text")) { - write-warning "Processing FW Rule $($rule.Name), Updating reference to local ipset $($GroupingObject."#text") to $($updatedIpSets.Item($GroupingObject."#text"))." + Write-Warning "Processing FW Rule $($rule.Name), Updating reference to local ipset $($GroupingObject."#text") to $($updatedIpSets.Item($GroupingObject."#text"))." #Ipset was local and was recreated on the new edge...update the rule. $GroupingObject."#text" = $updatedIpSets.Item($GroupingObject."#text") } } #Now Services - $RuleServices = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $rule -Query "child::application/applicationId") + $RuleServices = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $rule -query "child::application/applicationId") foreach ($Service in $RuleServices) { #Might be a service... if ($updatedServices.Item($Service."#text")) { - write-warning "Processing FW Rule $($rule.Name), Updating reference to local service $($Service."#text") to $($updatedServices.Item($Service."#text"))." + Write-Warning "Processing FW Rule $($rule.Name), Updating reference to local service $($Service."#text") to $($updatedServices.Item($Service."#text"))." #Service was local service and was recreated on the new edge...update the rule. $Service."#text" = $updatedServices.Item($Service."#text") } @@ -37665,7 +37849,7 @@ function Copy-NsxEdge{ #... Or a Service Group if ($updatedServiceGroups.Item($Service."#text")) { - write-warning "Processing FW Rule $($rule.Name), Updating reference to local service $($Service."#text") to $($updatedServiceGroups.Item($Service."#text"))." + Write-Warning "Processing FW Rule $($rule.Name), Updating reference to local service $($Service."#text") to $($updatedServiceGroups.Item($Service."#text"))." #Service was local service group and was recreated on the new edge...update the rule. $Service."#text" = $updatedServiceGroups.Item($Service."#text") } @@ -37676,7 +37860,7 @@ function Copy-NsxEdge{ } # Rules can now be pushed at the new ege... - write-warning "Posting updated user firewall ruleset to Edge $edgeid." + Write-Warning "Posting updated user firewall ruleset to Edge $edgeid." $null = Invoke-NsxRestMethod -method post -URI "/api/4.0/edges/$edgeId/firewall/config/rules" -body $UserFWXml.OuterXml -connection $Connection } } @@ -37685,12 +37869,12 @@ function Copy-NsxEdge{ #Re-get the edge so we can perform further fixups. ###################### - $NewEdge = Get-NsxEdge -objectID $edgeId -connection $connection + $NewEdge = Get-NsxEdge -objectId $edgeId -Connection $connection #Clone the NewEdge Element so we can modify without barfing up the original object (we need it for new-csr...). $_NewEdge = $NewEdge.CloneNode($true) #And Remove EdgeSummary from newedge XML... - $edgeSummary = (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_NewEdge -Query 'descendant::edgeSummary') + $edgeSummary = (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_NewEdge -query 'descendant::edgeSummary') if ( $edgeSummary ) { $null = $_NewEdge.RemoveChild($edgeSummary) } @@ -37699,7 +37883,7 @@ function Copy-NsxEdge{ #Check for any certificates that need to be created on the new edge. if (($SSCertificates.count -ge 1 ) -and ( $CertFixUps ) ) { - write-debug "$($MyInvocation.MyCommand.Name) : Self signed Certificates found on source Edge. Re-generating them." + Write-Debug "$($MyInvocation.MyCommand.Name) : Self signed Certificates found on source Edge. Re-generating them." #Need an appropriate CN - either fqdn or user defined. Defaults to hostname. if ( $SelfSignedCertificateCN ) { @@ -37714,38 +37898,38 @@ function Copy-NsxEdge{ foreach ( $cert in $SSCertificates ) { #Recreate SS Certs on destination edge. $subject = $cert.x509Certificate.subject -split "," - $org = ($subject | where-object { $_ -match 'O='}) -replace '^O=','' - $ou = ($subject | where-object { $_ -match 'OU='}) -replace '^OU=','' - $c = ($subject | where-object { $_ -match 'C='}) -replace '^C=','' - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $cert -Query "child::description") ) { + $org = ($subject | Where-Object { $_ -match 'O=' }) -replace '^O=', '' + $ou = ($subject | Where-Object { $_ -match 'OU=' }) -replace '^OU=', '' + $c = ($subject | Where-Object { $_ -match 'C=' }) -replace '^C=', '' + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $cert -query "child::description") ) { $desc = $cert.description } else { $desc = "PowerNSX Regenerated Self Signed certificate" } - write-warning "Creating cert on new edge with CN : $CertCN, C : $c, O : $org, OU : $ou, Keysize : $($cert.x509Certificate.publicKeyLength), Algo : $($cert.x509Certificate.publicKeyAlgo), Desc : $desc, Name : $CertCN" + Write-Warning "Creating cert on new edge with CN : $CertCN, C : $c, O : $org, OU : $ou, Keysize : $($cert.x509Certificate.publicKeyLength), Algo : $($cert.x509Certificate.publicKeyAlgo), Desc : $desc, Name : $CertCN" $NewCSR = $NewEdge | New-NsxEdgeCsr -CommonName $CertCN -Country $c -Organisation $org -OrganisationalUnit $ou -Keysize $cert.x509Certificate.publicKeyLength -Algorithm $cert.x509Certificate.publicKeyAlgo -Description $desc -Name $CertCN -Connection $Connection $NewCert = $NewCSR | New-NsxEdgeSelfSignedCertificate -NumberOfDays $CertValidNumberOfDays -Connection $Connection $UpdatedSSCerts.add($cert.objectId, $newCert.objectId) - write-debug "$($MyInvocation.MyCommand.Name) : Add cert mapping - Old Cert : $($cert.objectId), New Cert : $($newCert.objectId)" + Write-Debug "$($MyInvocation.MyCommand.Name) : Add cert mapping - Old Cert : $($cert.objectId), New Cert : $($newCert.objectId)" } #Fixup cert references in IPSec VPN... - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_NewEdge.features.ipsec.global -Query "child::serviceCertificate") ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_NewEdge.features.ipsec.global -query "child::serviceCertificate") ) { if ( $UpdatedSSCerts.item($_NewEdge.features.ipsec.global.serviceCertificate) ) { - write-warning "Fixing up cert for IpSec listener : Old Cert : $($_NewEdge.features.ipsec.global.serviceCertificate), New Cert : $($UpdatedSSCerts.item($_NewEdge.features.ipsec.global.serviceCertificate))" + Write-Warning "Fixing up cert for IpSec listener : Old Cert : $($_NewEdge.features.ipsec.global.serviceCertificate), New Cert : $($UpdatedSSCerts.item($_NewEdge.features.ipsec.global.serviceCertificate))" $_NewEdge.features.ipsec.global.serviceCertificate = $UpdatedSSCerts.item($_NewEdge.features.ipsec.global.serviceCertificate) } else { - write-warning "Unable to configure valid cert for IPSec VPN Server with current invalid cert $($_NewEdge.features.ipsec.global.serviceCertificate). This may be due to the use of an externally signed certificate on the source Edge. The service will have to be manually updated." + Write-Warning "Unable to configure valid cert for IPSec VPN Server with current invalid cert $($_NewEdge.features.ipsec.global.serviceCertificate). This may be due to the use of an externally signed certificate on the source Edge. The service will have to be manually updated." } } #LB cert Fixup - $appProfileCerts = (Invoke-XPathQuery -QueryMethod SelectNodes -Node $_NewEdge.features.loadBalancer.applicationProfile -Query "descendant::serviceCertificate") + $appProfileCerts = (Invoke-XpathQuery -QueryMethod SelectNodes -Node $_NewEdge.features.loadBalancer.applicationProfile -query "descendant::serviceCertificate") foreach ( $cert in $appProfileCerts ) { $AppProfile = $cert.ParentNode.ParentNode.name if ( $cert.ParentNode.ToString() -eq 'clientSsl' ) { @@ -37755,22 +37939,22 @@ function Copy-NsxEdge{ $certType = "Pool Certificate" } if ( $UpdatedSSCerts.item($cert."#text") ) { - write-warning "Fixing up cert for Load Balancer application profile $AppProfile $certType : Old Cert : $($cert."#text"), New Cert : $($UpdatedSSCerts.item($cert."#text"))" + Write-Warning "Fixing up cert for Load Balancer application profile $AppProfile $certType : Old Cert : $($cert."#text"), New Cert : $($UpdatedSSCerts.item($cert."#text"))" $cert."#text" = $UpdatedSSCerts.item($cert."#text") } else { - write-warning "Unable to configure valid cert for Load Balancer Application Profile $AppProfile $certType with current invalid cert $($cert."#text"). This may be due to the use of an externally signed certificate on the source Edge. The application Profile will have to be manually updated." + Write-Warning "Unable to configure valid cert for Load Balancer Application Profile $AppProfile $certType with current invalid cert $($cert."#text"). This may be due to the use of an externally signed certificate on the source Edge. The application Profile will have to be manually updated." } } #SSLVPN cert Fixup - if ( (Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_NewEdge.features.sslvpnConfig.serverSettings -Query "child::certificateId") ) { + if ( (Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_NewEdge.features.sslvpnConfig.serverSettings -query "child::certificateId") ) { if ( $UpdatedSSCerts.item($_NewEdge.features.sslvpnConfig.serverSettings.certificateId) ) { - write-warning "Fixing up cert for SSLVPN server : Old Cert : $($_NewEdge.features.sslvpnConfig.serverSettings.certificateId), New Cert : $($UpdatedSSCerts.item($_NewEdge.features.sslvpnConfig.serverSettings.certificateId))" + Write-Warning "Fixing up cert for SSLVPN server : Old Cert : $($_NewEdge.features.sslvpnConfig.serverSettings.certificateId), New Cert : $($UpdatedSSCerts.item($_NewEdge.features.sslvpnConfig.serverSettings.certificateId))" $_NewEdge.features.sslvpnConfig.serverSettings.certificateId = $UpdatedSSCerts.item($_NewEdge.features.sslvpnConfig.serverSettings.certificateId) } else { - write-warning "Unable to configure valid cert for SSL VPN Server with current invalid cert $($_NewEdge.features.sslvpnConfig.serverSettings.certificateId). This may be due to the use of an externally signed certificate on the source Edge. The service will have to be manually updated." + Write-Warning "Unable to configure valid cert for SSL VPN Server with current invalid cert $($_NewEdge.features.sslvpnConfig.serverSettings.certificateId). This may be due to the use of an externally signed certificate on the source Edge. The service will have to be manually updated." } } } @@ -37782,12 +37966,12 @@ function Copy-NsxEdge{ $body = $_NewEdge.OuterXml $URI = "/api/4.0/edges/$edgeid" - Write-Progress -activity "Updating Edge Services Gateway $Name" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - Write-progress -activity "Updating Edge Services Gateway $Name" -completed + Write-Progress -Activity "Updating Edge Services Gateway $Name" + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Updating Edge Services Gateway $Name" -Completed #Get final updated Edge object and return to user. - Get-NsxEdge -objectID $edgeId -connection $connection + Get-NsxEdge -objectId $edgeId -Connection $connection } end {} @@ -37812,12 +37996,12 @@ function Get-NsxDns { #> - [CmdLetBinding(DefaultParameterSetName="Name")] + [CmdLetBinding(DefaultParameterSetName = "Name")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdge $_ })] - [System.Xml.XmlElement]$Edge + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdge $_ })] + [System.Xml.XmlElement]$Edge ) begin {} @@ -37884,27 +38068,27 @@ function Set-NsxDns { #> param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - [ValidateScript({ ValidateEdgeDNS $_ })] - [System.Xml.XmlElement]$DNS, - [Parameter (Mandatory=$False)] - [switch]$Enabled, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [ipaddress[]]$DNSServer, - [Parameter (Mandatory=$False)] - [ValidateRange(1,8196)] - [int]$CacheSize, - [Parameter (Mandatory=$False)] - [ValidateNotNullOrEmpty()] - [switch]$EnableLogging, - [Parameter (Mandatory=$False)] - [ValidateSet("emergency","alert","critical","error","warning","notice","info","debug")] - [string]$LogLevel, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + [ValidateScript( { ValidateEdgeDNS $_ })] + [System.Xml.XmlElement]$DNS, + [Parameter (Mandatory = $False)] + [switch]$Enabled, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [ipaddress[]]$DNSServer, + [Parameter (Mandatory = $False)] + [ValidateRange(1, 8196)] + [int]$CacheSize, + [Parameter (Mandatory = $False)] + [ValidateNotNullOrEmpty()] + [switch]$EnableLogging, + [Parameter (Mandatory = $False)] + [ValidateSet("emergency", "alert", "critical", "error", "warning", "notice", "info", "debug")] + [string]$LogLevel, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { } @@ -37915,24 +38099,26 @@ function Set-NsxDns { #Store the edgeId and remove it from the XML as we need to post it... $edgeId = $_Dns.edgeId - $_Dns.RemoveChild( $((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Dns -Query 'descendant::edgeId')) ) | out-null + $_Dns.RemoveChild( $((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Dns -query 'descendant::edgeId')) ) | Out-Null #Using PSBoundParamters.ContainsKey lets us know if the user called us with a given parameter. #If the user did not specify a given parameter, we dont want to modify from the existing value. if ( $PsBoundParameters.ContainsKey('Enabled') ) { - if ( invoke-xpathquery -node $_Dns -querymethod SelectSingleNode -Query "child::enabled" ) { + if ( Invoke-XpathQuery -Node $_Dns -QueryMethod SelectSingleNode -query "child::enabled" ) { $_Dns.enabled = $Enabled.ToString().ToLower() - } else { - Add-XmlElement -xmlroot $_Dns -xmlElementName "enabled" -xmlElementText $Enabled.ToString().ToLower() + } + else { + Add-XmlElement -xmlRoot $_Dns -xmlElementName "enabled" -xmlElementText $Enabled.ToString().ToLower() } } if ( $PsBoundParameters.ContainsKey('CacheSize') ) { - if ( invoke-xpathquery -node $_Dns -querymethod SelectSingleNode -Query "child::cacheSize" ) { + if ( Invoke-XpathQuery -Node $_Dns -QueryMethod SelectSingleNode -query "child::cacheSize" ) { $_Dns.CacheSize = $CacheSize.ToString() - } else { - Add-XmlElement -xmlroot $_Dns -xmlElementName "cacheSize" -xmlElementText $CacheSize.ToString() + } + else { + Add-XmlElement -xmlRoot $_Dns -xmlElementName "cacheSize" -xmlElementText $CacheSize.ToString() } } @@ -37940,12 +38126,12 @@ function Set-NsxDns { if ( $PSBoundParameters.ContainsKey("DNSServer")) { if ( Invoke-XpathQuery -Node $_Dns -QueryMethod SelectSingleNode -query "child::dnsViews/dnsView/forwarders" ) { - write-warning "Existing DNS servers configured are removed" + Write-Warning "Existing DNS servers configured are removed" #Remove DNS Server list... - $_Dns.dnsViews.dnsview.RemoveChild((Invoke-XPathQuery -QueryMethod SelectSingleNode -Node $_Dns -Query 'child::dnsViews/dnsView/forwarders')) | out-null + $_Dns.dnsViews.dnsview.RemoveChild((Invoke-XpathQuery -QueryMethod SelectSingleNode -Node $_Dns -query 'child::dnsViews/dnsView/forwarders')) | Out-Null [System.XML.XMLElement]$xmlDNSlist = $_Dns.OwnerDocument.CreateElement('forwarders') - $_Dns.dnsViews.dnsView.Appendchild($xmlDNSlist) | out-null + $_Dns.dnsViews.dnsView.Appendchild($xmlDNSlist) | Out-Null #Add list of new DNS Server foreach ($Server in $DNSServer) { @@ -37955,7 +38141,7 @@ function Set-NsxDns { else { [System.XML.XMLElement]$xmlDNSlist = $_Dns.OwnerDocument.CreateElement('forwarders') - $_Dns.dnsViews.dnsView.Appendchild($xmlDNSlist) | out-null + $_Dns.dnsViews.dnsView.Appendchild($xmlDNSlist) | Out-Null foreach ($Server in $DNSServer) { Add-XmlElement -xmlRoot $xmlDNSlist -xmlElementName "ipAddress" -xmlElementText $Server.ToString() } @@ -37964,31 +38150,33 @@ function Set-NsxDns { } if ( $PsBoundParameters.ContainsKey('EnableLogging') ) { - if ( invoke-xpathquery -node $_Dns -querymethod SelectSingleNode -Query "child::logging/enable" ) { + if ( Invoke-XpathQuery -Node $_Dns -QueryMethod SelectSingleNode -query "child::logging/enable" ) { $_Dns.logging.enable = $EnableLogging.ToString().ToLower() - } else { - Add-XmlElement -xmlroot $_Dns -xmlElementName "enable" -xmlElementText $EnableLogging + } + else { + Add-XmlElement -xmlRoot $_Dns -xmlElementName "enable" -xmlElementText $EnableLogging } } if ( $PsBoundParameters.ContainsKey('LogLevel') ) { - if ( invoke-xpathquery -node $_Dns -querymethod SelectSingleNode -Query "child::logging/logLevel" ) { + if ( Invoke-XpathQuery -Node $_Dns -QueryMethod SelectSingleNode -query "child::logging/logLevel" ) { $_Dns.logging.LogLevel = $LogLevel - } else { - Add-XmlElement -xmlroot $_Dns -xmlElementName "logLevel" -xmlElementText $LogLevel + } + else { + Add-XmlElement -xmlRoot $_Dns -xmlElementName "logLevel" -xmlElementText $LogLevel } } $URI = "/api/4.0/edges/$($edgeId)/dns/config" $body = $_Dns.OuterXml - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" - $response = invoke-nsxwebrequest -method "put" -uri $URI -body $body -connection $connection - Write-Progress -activity "Update Edge Services Gateway $($edgeId)" -completed - Get-NsxEdge -objectId $($edgeId) -connection $connection | Get-NsxDns + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" + $response = Invoke-NsxWebRequest -method "put" -URI $URI -body $body -connection $connection + Write-Progress -Activity "Update Edge Services Gateway $($edgeId)" -Completed + Get-NsxEdge -objectId $($edgeId) -Connection $connection | Get-NsxDns } - end{ } + end { } } function Remove-NsxDns { @@ -38020,29 +38208,29 @@ function Remove-NsxDns { #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter","")] # Cant remove without breaking backward compatibility - [CmdletBinding(DefaultParameterSetName="Default")] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")] # Cant remove without breaking backward compatibility + [CmdletBinding(DefaultParameterSetName = "Default")] param ( - [Parameter (Mandatory=$true,ValueFromPipeline=$true,Position=1)] - #NSX Edge DNS to remove - [ValidateScript({ ValidateEdgeDNS $_ })] - [System.Xml.XmlElement]$DNS, - [Parameter (Mandatory=$False, ParameterSetName="LegacyConfirm")] - #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt - [switch]$Confirm=$true, - [Parameter (Mandatory=$False, ParameterSetName="Default")] - #Disable Prompt for confirmation. - [switch]$NoConfirm, - [Parameter (Mandatory=$False)] - #PowerNSX Connection object - [ValidateNotNullOrEmpty()] - [PSCustomObject]$Connection=$defaultNSXConnection + [Parameter (Mandatory = $true, ValueFromPipeline = $true, Position = 1)] + #NSX Edge DNS to remove + [ValidateScript( { ValidateEdgeDNS $_ })] + [System.Xml.XmlElement]$DNS, + [Parameter (Mandatory = $False, ParameterSetName = "LegacyConfirm")] + #Prompt for confirmation. Specify as -confirm:$false to disable confirmation prompt + [switch]$Confirm = $true, + [Parameter (Mandatory = $False, ParameterSetName = "Default")] + #Disable Prompt for confirmation. + [switch]$NoConfirm, + [Parameter (Mandatory = $False)] + #PowerNSX Connection object + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Connection = $defaultNSXConnection ) begin { If ( $PSCmdlet.ParameterSetName -eq "LegacyConfirm") { - write-warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." + Write-Warning "The -confirm switch is deprecated and will be removed in a future release. Use -NoConfirm instead." $NoConfirm = ( -not $confirm ) } } @@ -38050,7 +38238,7 @@ function Remove-NsxDns { process { $edgeId = $DNS.edgeId if ( -not ( $Noconfirm )) { - $message = "Edge DNS removal is permanent." + $message = "Edge DNS removal is permanent." $question = "Proceed with removal of Edge DNS $($EdgeId) ?" $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) @@ -38060,9 +38248,9 @@ function Remove-NsxDns { else { $decision = 0 } if ($decision -eq 0) { $URI = "/api/4.0/edges/$($EdgeId)/dns/config" - Write-Progress -activity "Remove DNS for Edge $($EdgeId)" - $null = invoke-nsxwebrequest -method "delete" -uri $URI -connection $connection - Write-Progress -activity "Remove DNS for Edge $($EdgeId)" -completed + Write-Progress -Activity "Remove DNS for Edge $($EdgeId)" + $null = Invoke-NsxWebRequest -method "delete" -URI $URI -connection $connection + Write-Progress -Activity "Remove DNS for Edge $($EdgeId)" -Completed } } diff --git a/tests/integration/04.Edge.Tests.ps1 b/tests/integration/04.Edge.Tests.ps1 index 4591d47d..0d1b92b7 100644 --- a/tests/integration/04.Edge.Tests.ps1 +++ b/tests/integration/04.Edge.Tests.ps1 @@ -11,17 +11,18 @@ Describe "Edge" { #We load the mod and establish connection to NSX Manager here. #Put any setup tasks in here that are required to perform your tests. Typical defaults: - import-module $pnsxmodule + Import-Module $pnsxmodule $script:DefaultNsxConnection = Connect-NsxServer -vCenterServer $PNSXTestVC -NsxServerHint $PNSXTestNSX -Credential $PNSXTestDefViCred -ViWarningAction "Ignore" - $script:cl = get-cluster | select-object -first 1 - write-warning "Using cluster $cl for edge appliance deployment" - $script:ds = $cl | get-datastore | select-object -first 1 - write-warning "Using datastore $ds for edge appliance deployment" + $script:cl = Get-Cluster | Select-Object -First 1 + Write-Warning "Using cluster $cl for edge appliance deployment" + $script:ds = $cl | Get-Datastore | Select-Object -First 1 + Write-Warning "Using datastore $ds for edge appliance deployment" #Put any script scope variables you need to reference in your tests. #For naming items that will be created in NSX, use a unique prefix #pester__. example: $script:name = "pester_e_edge1" + $script:fipsName = "fips-$($script:name)" $script:ls1_name = "pester_e_ls1" $script:ls2_name = "pester_e_ls2" $script:ls3_name = "pester_e_ls3" @@ -53,21 +54,21 @@ Describe "Edge" { $script:PrefixNetwork = "1.2.3.0/24" $script:Password = "VMware1!VMware1!" $script:tenant = "pester_e_tenant1" - $tz = get-nsxtransportzone -LocalOnly | select-object -first 1 + $tz = Get-NsxTransportZone -LocalOnly | Select-Object -First 1 $script:lswitches = @() - $script:lswitches += $tz | new-nsxlogicalswitch $ls1_name - $script:lswitches += $tz | new-nsxlogicalswitch $ls2_name - $script:lswitches += $tz | new-nsxlogicalswitch $ls3_name - $script:lswitches += $tz | new-nsxlogicalswitch $ls4_name - $script:lswitches += $tz | new-nsxlogicalswitch $ls5_name - $script:pg1 = $cl | get-vmhost | Get-VDSwitch | select-object -first 1 | New-VDPortgroup -name $pg1_name + $script:lswitches += $tz | New-NsxLogicalSwitch $ls1_name + $script:lswitches += $tz | New-NsxLogicalSwitch $ls2_name + $script:lswitches += $tz | New-NsxLogicalSwitch $ls3_name + $script:lswitches += $tz | New-NsxLogicalSwitch $ls4_name + $script:lswitches += $tz | New-NsxLogicalSwitch $ls5_name + $script:pg1 = $cl | Get-VMHost | Get-VDSwitch | Select-Object -First 1 | New-VDPortgroup -Name $pg1_name $script:vnics = @() - $script:vnics += New-NsxEdgeInterfaceSpec -index 1 -Type uplink -Name "vNic1" -ConnectedTo $lswitches[0] -PrimaryAddress $ip1 -SubnetPrefixLength 24 - $script:vnics += New-NsxEdgeInterfaceSpec -index 2 -Type internal -Name "vNic2" -ConnectedTo $lswitches[1] -PrimaryAddress $ip2 -SubnetPrefixLength 24 - $script:vnics += New-NsxEdgeInterfaceSpec -index 3 -Type trunk -Name "vNic3" -ConnectedTo $pg1 + $script:vnics += New-NsxEdgeInterfaceSpec -Index 1 -Type uplink -Name "vNic1" -ConnectedTo $lswitches[0] -PrimaryAddress $ip1 -SubnetPrefixLength 24 + $script:vnics += New-NsxEdgeInterfaceSpec -Index 2 -Type internal -Name "vNic2" -ConnectedTo $lswitches[1] -PrimaryAddress $ip2 -SubnetPrefixLength 24 + $script:vnics += New-NsxEdgeInterfaceSpec -Index 3 -Type trunk -Name "vNic3" -ConnectedTo $pg1 $script:preexistingrulename = "pester_e_testrule1" - $edge = New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" - $edge | get-nsxedgefirewall | new-nsxedgefirewallrule -name $preexistingrulename -action accept | out-null + $edge = New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" + $edge | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name $preexistingrulename -Action accept | Out-Null $script:scopedservice = New-NsxService -scope $edge.id -Name "pester_e_scopedservice" -Protocol "TCP" -port "1234" $script:VersionLessThan623 = [version]$DefaultNsxConnection.Version -lt [version]"6.2.3" $script:VersionLessThan630 = [version]$DefaultNsxConnection.Version -lt [version]"6.3.0" @@ -77,716 +78,783 @@ Describe "Edge" { #AfterAll block runs _once_ at completion of invocation regardless of number of tests/contexts/describes. #We kill the connection to NSX Manager here. - write-warning "Cleaning up" - get-nsxedge $name | remove-nsxedge -confirm:$false + Write-Warning "Cleaning up" + Get-NsxEdge $name | Remove-NsxEdge -Confirm:$false + Get-NsxEdge $fipsName | Remove-NsxEdge -Confirm:$false - start-sleep 5 + Start-Sleep 5 foreach ( $lswitch in $lswitches) { - get-nsxlogicalswitch $lswitch.name | remove-nsxlogicalswitch -confirm:$false + Get-NsxLogicalSwitch $lswitch.name | Remove-NsxLogicalSwitch -Confirm:$false } - get-vdportgroup $pg1_name | Remove-VDPortGroup -Confirm:$false - disconnect-nsxserver + Get-VDPortgroup $pg1_name | Remove-VDPortGroup -Confirm:$false + Disconnect-NsxServer } Context "Edge Status" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } It "Get Edge Status" { $status = Get-NsxEdge $name | Get-NsxEdgeStatus - $status | should not be $null - $status.systemStatus| should not be $null - $status.edgeStatus | should not be $null - $status.publishStatus| should not be $null + $status | Should not be $null + $status.systemStatus | Should not be $null + $status.edgeStatus | Should not be $null + $status.publishStatus | Should not be $null } It "Get Edge Service Status" { $service = Get-NsxEdge $name | Get-NsxEdgeStatus - $service | should not be $null - $service.featureStatuses.featureStatus | should not be $null + $service | Should not be $null + $service.featureStatuses.featureStatus | Should not be $null } It "Get Edge Service Firewall Status" { $service = Get-NsxEdge $name | Get-NsxEdgeStatus - $service | should not be $null - $service.featureStatuses.featureStatus | should not be $null - ($service.featureStatuses.featureStatus | where-object { $_.service -eq 'firewall' }).status | should not be $null + $service | Should not be $null + $service.featureStatuses.featureStatus | Should not be $null + ($service.featureStatuses.featureStatus | Where-Object { $_.service -eq 'firewall' }).status | Should not be $null } } Context "Interfaces" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } - it "Can add an edge vnic" { + It "Can add an edge vnic" { $nic = Get-NsxEdge $name | Get-NsxEdgeInterface -Index 4 | Set-NsxEdgeInterface -Name "vNic4" -Type internal -ConnectedTo $lswitches[3] -PrimaryAddress $ip4 -SubnetPrefixLength 24 $nic = Get-NsxEdge $name | Get-NsxEdgeInterface -Index 4 - $nic.type | should be internal - $nic.portGroupName | should be $lswitches[3].name + $nic.type | Should be internal + $nic.portGroupName | Should be $lswitches[3].name } - it "Can add a sub-interface of VLAN Type" { - $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | New-NsxEdgeSubinterface -Name "sub1" -PrimaryAddress $ip5 -SubnetPrefixLength 24 -TunnelId 1 -Vlan 123 - $vnic | should not be $null + It "Can add a sub-interface of VLAN Type" { + $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | New-NsxEdgeSubInterface -Name "sub1" -PrimaryAddress $ip5 -SubnetPrefixLength 24 -TunnelId 1 -VLAN 123 + $vnic | Should not be $null $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | Get-NsxEdgeSubInterface - @($vnic).count | should be 1 + @($vnic).count | Should be 1 } - it "Can add a sub-interface of Network Type" { - $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | New-NsxEdgeSubinterface -Name "sub2" -PrimaryAddress $ip6 -SubnetPrefixLength 24 -TunnelId 2 -Network $lswitches[4] - $vnic | should not be $null + It "Can add a sub-interface of Network Type" { + $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | New-NsxEdgeSubInterface -Name "sub2" -PrimaryAddress $ip6 -SubnetPrefixLength 24 -TunnelId 2 -Network $lswitches[4] + $vnic | Should not be $null $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | Get-NsxEdgeSubInterface - @($vnic).count | should be 2 + @($vnic).count | Should be 2 } - it "Can get a sub-interface by name" { + It "Can get a sub-interface by name" { $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic3" | Get-NsxEdgeSubInterface "sub1" - @($vnic).count | should be 1 + @($vnic).count | Should be 1 } - it "Can get a sub-interface by index" { + It "Can get a sub-interface by index" { $vnic = Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" | Get-NsxEdgeSubInterface -Index 11 - @($vnic).count | should be 1 + @($vnic).count | Should be 1 } - it "Can remove a sub-interface" { + It "Can remove a sub-interface" { $subint = Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" | Get-NsxEdgeSubInterface -Index 11 - $subint | should not be $null - $subint | Remove-NsxEdgeSubinterface -confirm:$false - Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" | Get-NsxEdgeSubInterface -Index 11 | should be $null + $subint | Should not be $null + $subint | Remove-NsxEdgeSubInterface -Confirm:$false + Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" | Get-NsxEdgeSubInterface -Index 11 | Should be $null } - it "Returns an empty result set when querying for sub interfaces, and no sub-interfaces exist" { - Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" | Get-NsxEdgeSubInterface | Remove-NsxEdgeSubinterface -confirm:$false + It "Returns an empty result set when querying for sub interfaces, and no sub-interfaces exist" { + Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" | Get-NsxEdgeSubInterface | Remove-NsxEdgeSubInterface -Confirm:$false $int = Get-NsxEdge $name | Get-NsxEdgeInterface "Vnic3" - $int | should not be $null - $int | Get-NsxEdgeSubInterface | should be $null + $int | Should not be $null + $int | Get-NsxEdgeSubInterface | Should be $null } } Context "Static Routing" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } It "Can configure the default route" { Get-NsxEdge $name | Get-NsxEdgeRouting | Set-NsxEdgeRouting -DefaultGatewayVnic 1 -DefaultGatewayAddress $dgaddress -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.staticRouting.defaultRoute.gatewayAddress | should be $dgaddress + $rtg | Should not be $null + $rtg.staticRouting.defaultRoute.gatewayAddress | Should be $dgaddress } - it "Can add a static route" { - Get-NsxEdge $name | Get-NsxEdgeRouting | New-NsxEdgeStaticRoute -Network $staticroutenet -NextHop $staticroutenexthop -confirm:$false - $rtg = Get-NsxEdge $name | get-NsxEdgeRouting - $rtg | should not be $null - $rtg.staticRouting.staticRoutes | should not be $null + It "Can add a static route" { + Get-NsxEdge $name | Get-NsxEdgeRouting | New-NsxEdgeStaticRoute -Network $staticroutenet -NextHop $staticroutenexthop -Confirm:$false + $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting + $rtg | Should not be $null + $rtg.staticRouting.staticRoutes | Should not be $null } - it "Can remove a static route" { + It "Can remove a static route" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Get-NsxEdgeStaticRoute -Network $staticroutenet -NextHop $staticroutenexthop | Remove-NsxEdgeStaticRoute -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | Get-NsxEdgeStaticRoute -Network $staticroutenet -NextHop $staticroutenexthop | should be $null + $rtg | Should not be $null + $rtg | Get-NsxEdgeStaticRoute -Network $staticroutenet -NextHop $staticroutenexthop | Should be $null } } Context "Route Prefixes" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } - it "Can create a route prefix" { + It "Can create a route prefix" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | New-NsxEdgePrefix -Name $PrefixName -Network $PrefixNetwork -confirm:$false - Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -name $PrefixName | should not be $null + $rtg | Should not be $null + $rtg | New-NsxEdgePrefix -Name $PrefixName -Network $PrefixNetwork -Confirm:$false + Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -Name $PrefixName | Should not be $null } - it "Can can remove a route prefix" { + It "Can can remove a route prefix" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Get-NsxEdgePrefix | Remove-NsxEdgePrefix -Confirm:$false - Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -name $PrefixName | should be $null + Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -Name $PrefixName | Should be $null } } Context "OSPF" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } It "Can enable OSPF and define router id" { Get-NsxEdge $Name | Get-NsxEdgeRouting | Set-NsxEdgeRouting -EnableOspf -RouterId $routerId -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.routingGlobalConfig.routerId | should be $routerId - $rtg.ospf.enabled | should be "true" + $rtg | Should not be $null + $rtg.routingGlobalConfig.routerId | Should be $routerId + $rtg.ospf.enabled | Should be "true" } - it "Can add an OSPF Area" { + It "Can add an OSPF Area" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | New-NsxEdgeOspfArea -AreaId $OspfAreaId -Confirm:$false $area = Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgeOspfArea -AreaId $OspfAreaId - $area | should not be $null + $area | Should not be $null } It "Can add an OSPF Interface" { $UplinkVnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic1" - $uplinkVnic | should not be $null + $uplinkVnic | Should not be $null $UplinkVnicId = $uplinkVnic.index - $ospfint = Get-NsxEdge $name | Get-NsxEdgeRouting | New-NsxEdgeOspfInterface -AreaId $OspfAreaId -Vnic $UplinkVnicId -confirm:$false - $ospfint | should not be $null + $ospfint = Get-NsxEdge $name | Get-NsxEdgeRouting | New-NsxEdgeOspfInterface -AreaId $OspfAreaId -Vnic $UplinkVnicId -Confirm:$false + $ospfint | Should not be $null $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.ospf.ospfInterfaces.ospfInterface | Where-Object { $_.vnic -eq $UplinkVnicId } | should not be $null + $rtg | Should not be $null + $rtg.ospf.ospfInterfaces.ospfInterface | Where-Object { $_.vnic -eq $UplinkVnicId } | Should not be $null } - it "Can enable route redistribution into Ospf" { + It "Can enable route redistribution into Ospf" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | New-NsxEdgePrefix -Name $ospfPrefixName -Network $PrefixNetwork -confirm:$false - Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -name $ospfPrefixName | should not be $null - Get-NsxEdge $Name | Get-NsxEdgeRouting | New-NsxEdgeRedistributionRule -PrefixName $ospfPrefixName -Learner ospf -FromConnected -FromStatic -Action permit -confirm:$false - $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -learner ospf | where-object { $_.prefixName -eq $ospfPrefixName } - $rule.from.connected | should be "true" - $rule.from.static | should be "true" + $rtg | Should not be $null + $rtg | New-NsxEdgePrefix -Name $ospfPrefixName -Network $PrefixNetwork -Confirm:$false + Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -Name $ospfPrefixName | Should not be $null + Get-NsxEdge $Name | Get-NsxEdgeRouting | New-NsxEdgeRedistributionRule -PrefixName $ospfPrefixName -Learner ospf -FromConnected -FromStatic -Action permit -Confirm:$false + $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -Learner ospf | Where-Object { $_.prefixName -eq $ospfPrefixName } + $rule.from.connected | Should be "true" + $rule.from.static | Should be "true" } - it "Can remove an OSPF Interface" { + It "Can remove an OSPF Interface" { $UplinkVnic = Get-NsxEdge $name | Get-NsxEdgeInterface "vNic1" - $UplinkVnic | should not be $null + $UplinkVnic | Should not be $null $UplinkVnicId = $uplinkVnic.index - Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgeOspfInterface -AreaId $OspfAreaId -VnicId $UplinkVnicId | Remove-NsxEdgeOspfInterface -confirm:$false + Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgeOspfInterface -AreaId $OspfAreaId -vNicId $UplinkVnicId | Remove-NsxEdgeOspfInterface -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.ospf.ospfInterfaces.ospfInterface | Where-Object { $_.vnic -eq $UplinkVnicId } | should be $null + $rtg.ospf.ospfInterfaces.ospfInterface | Where-Object { $_.vnic -eq $UplinkVnicId } | Should be $null } - it "Can remove an OSPF Area" { + It "Can remove an OSPF Area" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | Get-NsxEdgeOspfArea -AreaId $OspfAreaId | Remove-NsxEdgeOspfArea -confirm:$false + $rtg | Should not be $null + $rtg | Get-NsxEdgeOspfArea -AreaId $OspfAreaId | Remove-NsxEdgeOspfArea -Confirm:$false $area = Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgeOspfArea -AreaId $OspfAreaId - $area | should be $null + $area | Should be $null } - it "Can remove ospf route redistribution rules" { + It "Can remove ospf route redistribution rules" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Get-NsxEdgeRedistributionRule -Learner ospf | Remove-NsxEdgeRedistributionRule -Confirm:$false - $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -learner ospf - $rule | should be $null + $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -Learner ospf + $rule | Should be $null } - it "Can disable Graceful Restart" { + It "Can disable Graceful Restart" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.ospf.gracefulRestart | should be true + $rtg | Should not be $null + $rtg.ospf.gracefulRestart | Should be true $rtg | Set-NsxEdgeOspf -GracefulRestart:$false -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.ospf.gracefulRestart | should be false + $rtg.ospf.gracefulRestart | Should be false } - it "Can enable Default Originate" { + It "Can enable Default Originate" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.ospf.defaultOriginate | should be false + $rtg | Should not be $null + $rtg.ospf.defaultOriginate | Should be false $rtg | Set-NsxEdgeOspf -DefaultOriginate -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.ospf.defaultOriginate | should be true + $rtg.ospf.defaultOriginate | Should be true } - it "Can disable OSPF" { + It "Can disable OSPF" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.ospf.enabled | should be "true" + $rtg | Should not be $null + $rtg.ospf.enabled | Should be "true" $rtg | Set-NsxEdgeRouting -EnableOspf:$false -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.ospf.enabled | should be "false" + $rtg.ospf.enabled | Should be "false" } } Context "BGP" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } - it "Can enable BGP" { + It "Can enable BGP" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Set-NsxEdgeRouting -EnableBgp -RouterId $routerId -LocalAS $LocalAS -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.routingGlobalConfig.routerId | should be $routerId - $rtg.bgp.enabled | should be "true" + $rtg.routingGlobalConfig.routerId | Should be $routerId + $rtg.bgp.enabled | Should be "true" } - it "Can add a BGP Neighbour" { + It "Can add a BGP Neighbour" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | New-NsxEdgeBgpNeighbour -IpAddress $bgpneighbour -RemoteAS $RemoteAs -Weight $bgpWeight -KeepAliveTimer $bgpKeepAliveTimer -HoldDownTimer $bgpHoldDownTimer -Password $bgpPassword -confirm:$false - $nbr = Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgeBgpNeighbour - $nbr.ipaddress | should be $bgpneighbour - $nbr.remoteAS | should be $RemoteAs - $nbr.weight | should be $bgpWeight - $nbr.keepAliveTimer | should be $bgpKeepAliveTimer - $nbr.holdDownTimer | should be $bgpHoldDownTimer - ($nbr | Get-Member -MemberType Properties -Name password).count | should be 1 - } - - it "Can enable route redistribution into BGP" { + $rtg | Should not be $null + $rtg | New-NsxEdgeBgpNeighbour -IpAddress $bgpneighbour -RemoteAS $RemoteAs -Weight $bgpWeight -KeepAliveTimer $bgpKeepAliveTimer -HoldDownTimer $bgpHoldDownTimer -Password $bgpPassword -Confirm:$false + $nbr = Get-NsxEdge $name | Get-NsxEdgeRouting | Get-NsxEdgeBgpNeighbour + $nbr.ipaddress | Should be $bgpneighbour + $nbr.remoteAS | Should be $RemoteAs + $nbr.weight | Should be $bgpWeight + $nbr.keepAliveTimer | Should be $bgpKeepAliveTimer + $nbr.holdDownTimer | Should be $bgpHoldDownTimer + ($nbr | Get-Member -MemberType Properties -Name password).count | Should be 1 + } + + It "Can enable route redistribution into BGP" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | New-NsxEdgePrefix -Name $bgpPrefixName -Network $PrefixNetwork -confirm:$false - Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -name $bgpPrefixName | should not be $null - Get-NsxEdge $Name | Get-NsxEdgeRouting | New-NsxEdgeRedistributionRule -PrefixName $bgpPrefixName -Learner bgp -FromConnected -FromStatic -FromOspf -Action permit -confirm:$false - $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -learner bgp - $rule.from.connected | should be "true" - $rule.from.static | should be "true" - $rule.from.ospf | should be "true" + $rtg | Should not be $null + $rtg | New-NsxEdgePrefix -Name $bgpPrefixName -Network $PrefixNetwork -Confirm:$false + Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgePrefix -Name $bgpPrefixName | Should not be $null + Get-NsxEdge $Name | Get-NsxEdgeRouting | New-NsxEdgeRedistributionRule -PrefixName $bgpPrefixName -Learner bgp -FromConnected -FromStatic -FromOspf -Action permit -Confirm:$false + $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -Learner bgp + $rule.from.connected | Should be "true" + $rule.from.static | Should be "true" + $rule.from.ospf | Should be "true" } - it "Can remove bgp route redistribution rules" { + It "Can remove bgp route redistribution rules" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Get-NsxEdgeRedistributionRule -Learner bgp | Remove-NsxEdgeRedistributionRule -Confirm:$false - $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -learner bgp - $rule | should be $null + $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule -Learner bgp + $rule | Should be $null } - it "Can retreive an empty result set of redistribution rules" { + It "Can retreive an empty result set of redistribution rules" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Get-NsxEdgeRedistributionRule | Remove-NsxEdgeRedistributionRule -Confirm:$false $rule = Get-NsxEdge $Name | Get-NsxEdgeRouting | Get-NsxEdgeRedistributionRule - $rule | should be $null + $rule | Should be $null } - it "Can remove a BGP Neighbour" { + It "Can remove a BGP Neighbour" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | Get-NsxEdgeBgpNeighbour -IpAddress $bgpneighbour -RemoteAS $RemoteAs | Remove-NsxEdgeBgpNeighbour -confirm:$false + $rtg | Should not be $null + $rtg | Get-NsxEdgeBgpNeighbour -IpAddress $bgpneighbour -RemoteAS $RemoteAs | Remove-NsxEdgeBgpNeighbour -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg | Get-NsxEdgeBgpNeighbour -IpAddress $bgpneighbour -RemoteAS $RemoteAs | should be $null + $rtg | Should not be $null + $rtg | Get-NsxEdgeBgpNeighbour -IpAddress $bgpneighbour -RemoteAS $RemoteAs | Should be $null } - it "Can disable Graceful Restart" { + It "Can disable Graceful Restart" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.bgp.gracefulRestart | should be true + $rtg | Should not be $null + $rtg.bgp.gracefulRestart | Should be true $rtg | Set-NsxEdgeBgp -GracefulRestart:$false -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.bgp.gracefulRestart | should be false + $rtg.bgp.gracefulRestart | Should be false } - it "Can enable Default Originate" { + It "Can enable Default Originate" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.bgp.defaultOriginate | should be false + $rtg | Should not be $null + $rtg.bgp.defaultOriginate | Should be false $rtg | Set-NsxEdgeBgp -DefaultOriginate -Confirm:$false $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg.bgp.defaultOriginate | should be true + $rtg.bgp.defaultOriginate | Should be true } - it "Can disable BGP" { + It "Can disable BGP" { $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null + $rtg | Should not be $null $rtg | Set-NsxEdgeRouting -EnableBgp:$false -Confirm:$false - $rtg = Get-NSxEdge $name | Get-NsxEdgeRouting - $rtg | should not be $null - $rtg.bgp.enabled | should be "false" + $rtg = Get-NsxEdge $name | Get-NsxEdgeRouting + $rtg | Should not be $null + $rtg.bgp.enabled | Should be "false" } } Context "Grouping Objects" { - BeforeAll{ + BeforeAll { if ( -not ( Get-NsxEdge $name ) ) { - New-NsxEdge -Name $name -Interface $vnics[0],$vnics[1],$vnics[2] -Cluster $cl -Datastore $ds -password $password -tenant $tenant -enablessh -Hostname "pestertest" + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" } } - it "Can retrieve locally created IP Sets" { + It "Can retrieve locally created IP Sets" { } - it "Can add local IP Sets" { + It "Can add local IP Sets" { } - it "Can remove local IP Sets" { + It "Can remove local IP Sets" { } } Context "Edge Firewall" { - it "Can retrieve edge firewall rules" { + BeforeAll { + if ( -not ( Get-NsxEdge $name ) ) { + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" + } + } + + It "Can retrieve edge firewall rules" { $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | Get-NsxEdgeFirewallRule $preexistingrulename - $rule | should not be $null - $rule.name | should be $preexistingrulename + $rule | Should not be $null + $rule.name | Should be $preexistingrulename } It "Can add a simple edge firewall rule" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule1" -comment "testrule1" -action accept - $rule | should not be $null - $rule.name | should be "testrule1" - $rule.description | should be "testrule1" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule1" -Comment "testrule1" -Action accept + $rule | Should not be $null + $rule.name | Should be "testrule1" + $rule.description | Should be "testrule1" } It "Can add an edge firewall rule with service by existing nsx service object" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule2" -comment "testrule2" -service $scopedservice -action accept - $rule | should not be $null - $rule.application.applicationId -contains $scopedservice.objectid | should be $true + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule2" -Comment "testrule2" -Service $scopedservice -Action accept + $rule | Should not be $null + $rule.application.applicationId -contains $scopedservice.objectid | Should be $true } It "Can add an edge firewall rule with service by protocol and port" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule3" -comment "testrule3" -service tcp/4321 -action accept - $rule | should not be $null - $rule.application.service.protocol -contains "tcp" | should be $true - $rule.application.service.port -contains "4321" | should be $true + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule3" -Comment "testrule3" -Service tcp/4321 -Action accept + $rule | Should not be $null + $rule.application.service.protocol -contains "tcp" | Should be $true + $rule.application.service.port -contains "4321" | Should be $true } It "Can add an edge firewall rule with service by protocol only" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule4" -comment "testrule4" -service tcp -action accept - $rule | should not be $null - $rule.application.service.protocol -contains "tcp" | should be $true + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule4" -Comment "testrule4" -Service tcp -Action accept + $rule | Should not be $null + $rule.application.service.protocol -contains "tcp" | Should be $true # $rule.application.service.port -contains "any" | should be $true } It "Can remove an edge firewall rule" { $removerulename = "test_removerule1" - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name $removerulename -comment $removerulename -service tcp -action accept - $rule | should not be $null - { $rule | Remove-NsxEdgeFirewallRule -NoConfirm } | should not throw - $getrule = Get-NsxEdge $name | Get-NsxEdgeFirewall | Get-NsxEdgeFirewallRule -name $removerulename - $getrule | should be $null + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name $removerulename -Comment $removerulename -Service tcp -Action accept + $rule | Should not be $null + { $rule | Remove-NsxEdgeFirewallRule -NoConfirm } | Should not throw + $getrule = Get-NsxEdge $name | Get-NsxEdgeFirewall | Get-NsxEdgeFirewallRule -Name $removerulename + $getrule | Should be $null } It "Can add an edge firewall rule with logging enabled" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule5" -comment "testrule5" -enablelogging -action accept - $rule | should not be $null - $rule.loggingEnabled | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule5" -Comment "testrule5" -EnableLogging -Action accept + $rule | Should not be $null + $rule.loggingEnabled | Should be "true" } It "Can add an edge firewall rule with multiple source members" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule6" -comment "testrule6" -source "1.2.3.4","4.3.2.1" -action accept - $rule | should not be $null - $rule.source.ipaddress -contains "1.2.3.4" | should be "true" - $rule.source.ipaddress -contains "4.3.2.1" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule6" -Comment "testrule6" -Source "1.2.3.4", "4.3.2.1" -Action accept + $rule | Should not be $null + $rule.source.ipaddress -contains "1.2.3.4" | Should be "true" + $rule.source.ipaddress -contains "4.3.2.1" | Should be "true" } It "Can add an edge firewall rule with multiple destination members" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule7" -comment "testrule7" -destination "1.2.3.4","4.3.2.1" -action accept - $rule | should not be $null - $rule.destination.ipaddress -contains "1.2.3.4" | should be "true" - $rule.destination.ipaddress -contains "4.3.2.1" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule7" -Comment "testrule7" -Destination "1.2.3.4", "4.3.2.1" -Action accept + $rule | Should not be $null + $rule.destination.ipaddress -contains "1.2.3.4" | Should be "true" + $rule.destination.ipaddress -contains "4.3.2.1" | Should be "true" } It "Can add an edge firewall rule with negated sources" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule8" -comment "testrule8" -source "1.2.3.4" -negateSource -action accept - $rule | should not be $null - $rule.source.ipaddress -contains "1.2.3.4" | should be "true" - $rule.source.exclude | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule8" -Comment "testrule8" -Source "1.2.3.4" -NegateSource -Action accept + $rule | Should not be $null + $rule.source.ipaddress -contains "1.2.3.4" | Should be "true" + $rule.source.exclude | Should be "true" } It "Can add an edge firewall rule with negated destination" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule8" -comment "testrule8" -destination "1.2.3.4" -negateDestination -action accept - $rule | should not be $null - $rule.destination.ipaddress -contains "1.2.3.4" | should be "true" - $rule.destination.exclude | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule8" -Comment "testrule8" -Destination "1.2.3.4" -NegateDestination -Action accept + $rule | Should not be $null + $rule.destination.ipaddress -contains "1.2.3.4" | Should be "true" + $rule.destination.exclude | Should be "true" } It "Can add an edge firewall rule with specific nic source" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule9" -comment "testrule9" -sourceVnic 0 -action accept - $rule | should not be $null - $rule.source.vnicGroupId -contains "vnic-index-0" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule9" -Comment "testrule9" -SourceVnic 0 -Action accept + $rule | Should not be $null + $rule.source.vnicGroupId -contains "vnic-index-0" | Should be "true" } It "Can add an edge firewall rule with internal nic source" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule10" -comment "testrule10" -sourceVnic internal -action accept - $rule | should not be $null - $rule.source.vnicGroupId -contains "internal" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule10" -Comment "testrule10" -SourceVnic internal -Action accept + $rule | Should not be $null + $rule.source.vnicGroupId -contains "internal" | Should be "true" } It "Can add an edge firewall rule with external nic source" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule11" -comment "testrule11" -sourceVnic external -action accept - $rule | should not be $null - $rule.source.vnicGroupId -contains "external" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule11" -Comment "testrule11" -SourceVnic external -Action accept + $rule | Should not be $null + $rule.source.vnicGroupId -contains "external" | Should be "true" } It "Can add an edge firewall rule with vse nic source" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule12" -comment "testrule12" -sourceVnic vse -action accept - $rule | should not be $null - $rule.source.vnicGroupId -contains "vse" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule12" -Comment "testrule12" -SourceVnic vse -Action accept + $rule | Should not be $null + $rule.source.vnicGroupId -contains "vse" | Should be "true" } It "Can add an edge firewall rule with specific nic destination" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule13" -comment "testrule13" -destinationVnic 1 -action accept - $rule | should not be $null - $rule.destination.vnicGroupId -contains "vnic-index-1" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule13" -Comment "testrule13" -DestinationVnic 1 -Action accept + $rule | Should not be $null + $rule.destination.vnicGroupId -contains "vnic-index-1" | Should be "true" } It "Can add an edge firewall rule with internal nic destination" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule14" -comment "testrule14" -destinationVnic internal -action accept - $rule | should not be $null - $rule.destination.vnicGroupId -contains "internal" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule14" -Comment "testrule14" -DestinationVnic internal -Action accept + $rule | Should not be $null + $rule.destination.vnicGroupId -contains "internal" | Should be "true" } It "Can add an edge firewall rule with external nic destination" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule15" -comment "testrule15" -destinationVnic external -action accept - $rule | should not be $null - $rule.destination.vnicGroupId -contains "external" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule15" -Comment "testrule15" -DestinationVnic external -Action accept + $rule | Should not be $null + $rule.destination.vnicGroupId -contains "external" | Should be "true" } It "Can add an edge firewall rule with vse nic destination" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule16" -comment "testrule16" -destinationVnic vse -action accept - $rule | should not be $null - $rule.destination.vnicGroupId -contains "vse" | should be "true" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule16" -Comment "testrule16" -DestinationVnic vse -Action accept + $rule | Should not be $null + $rule.destination.vnicGroupId -contains "vse" | Should be "true" } It "Can add an edge firewall rule above an existing rule" { $existingrule = Get-NsxEdge $name | Get-NsxEdgeFirewall | Get-NsxEdgeFirewallRule $preexistingrulename - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule17" -comment "testrule17" -aboveRuleId $existingRule.id -action accept - $rule | should not be $null + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule17" -Comment "testrule17" -AboveRuleId $existingRule.id -Action accept + $rule | Should not be $null $fw = Get-NsxEdge $name | Get-NsxEdgeFirewall - ($fw.firewallRules.firewallRule | where-object { $_.ruleType -eq 'user' } | select-object -first 1).id | should be $rule.id + ($fw.firewallRules.firewallRule | Where-Object { $_.ruleType -eq 'user' } | Select-Object -First 1).id | Should be $rule.id } It "Can add an edge firewall rule with deny action" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule18" -comment "testrule18" -action deny - $rule | should not be $null - $rule.action | should be "deny" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule18" -Comment "testrule18" -Action deny + $rule | Should not be $null + $rule.action | Should be "deny" } It "Can add an edge firewall rule with reject action" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule19" -comment "testrule19" -action reject - $rule | should not be $null - $rule.action | should be "reject" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule19" -Comment "testrule19" -Action reject + $rule | Should not be $null + $rule.action | Should be "reject" } It "Can modifiy an edge firewall rule" { - $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -name "testrule20" -comment "testrule20" -action accept - $rule | should not be $null - $rule.enabled | should be "true" - $rule.loggingEnabled | should be "false" - $rule.action | should be "accept" - $rule.name | should be "testrule20" - $rule.description | should be "testrule20" - $rule = $rule | Set-NsxEdgeFirewallRule -name "testrule21" -comment "testrule21" -loggingEnabled $true -enabled $false -action deny - $rule | should not be $null - $rule.enabled | should be "false" - $rule.loggingEnabled | should be "true" - $rule.action | should be "deny" - $rule.name | should be "testrule21" - $rule.description | should be "testrule21" + $rule = Get-NsxEdge $name | Get-NsxEdgeFirewall | New-NsxEdgeFirewallRule -Name "testrule20" -Comment "testrule20" -Action accept + $rule | Should not be $null + $rule.enabled | Should be "true" + $rule.loggingEnabled | Should be "false" + $rule.action | Should be "accept" + $rule.name | Should be "testrule20" + $rule.description | Should be "testrule20" + $rule = $rule | Set-NsxEdgeFirewallRule -Name "testrule21" -comment "testrule21" -loggingEnabled $true -enabled $false -action deny + $rule | Should not be $null + $rule.enabled | Should be "false" + $rule.loggingEnabled | Should be "true" + $rule.action | Should be "deny" + $rule.name | Should be "testrule21" + $rule.description | Should be "testrule21" } It "Can disable the edge firewall" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -Enabled:$false -NoConfirm - $config.enabled | should be "false" + $config.enabled | Should be "false" } It "Can set edge default rule action" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -DefaultRuleAction "accept" -NoConfirm - $config.defaultPolicy.action | should be "accept" + $config.defaultPolicy.action | Should be "accept" } It "Can disable edge default rule logging" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -DefaultRuleLoggingEnabled:$false -NoConfirm - $config.defaultPolicy.loggingEnabled | should be "false" + $config.defaultPolicy.loggingEnabled | Should be "false" } It "Can set edge globalConfig option tcpPickOngoingConnections" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -tcpPickOngoingConnections -NoConfirm - $config.globalConfig.tcpPickOngoingConnections | should be "true" + $config.globalConfig.tcpPickOngoingConnections | Should be "true" } It "Can set edge globalConfig option tcpAllowOutOfWindowPackets" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -tcpAllowOutOfWindowPackets -NoConfirm - $config.globalConfig.tcpAllowOutOfWindowPackets | should be "true" + $config.globalConfig.tcpAllowOutOfWindowPackets | Should be "true" } It "Can set edge globalConfig option tcpSendResetForClosedVsePorts" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -tcpSendResetForClosedVsePorts:$false -NoConfirm - $config.globalConfig.tcpSendResetForClosedVsePorts | should be "false" + $config.globalConfig.tcpSendResetForClosedVsePorts | Should be "false" } It "Can set edge globalConfig option dropInvalidTraffic" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -dropInvalidTraffic:$false -NoConfirm - $config.globalConfig.dropInvalidTraffic | should be "false" + $config.globalConfig.dropInvalidTraffic | Should be "false" } It "Can set edge globalConfig option logInvalidTraffic" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -logInvalidTraffic -NoConfirm - $config.globalConfig.logInvalidTraffic | should be "true" + $config.globalConfig.logInvalidTraffic | Should be "true" } It "Can set edge globalConfig option tcpTimeoutOpen" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -tcpTimeoutOpen 40 -NoConfirm - $config.globalConfig.tcpTimeoutOpen | should be "40" + $config.globalConfig.tcpTimeoutOpen | Should be "40" } It "Can set edge globalConfig option tcpTimeoutEstablished" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -tcpTimeoutEstablished 45200 -NoConfirm - $config.globalConfig.tcpTimeoutEstablished | should be "45200" + $config.globalConfig.tcpTimeoutEstablished | Should be "45200" } It "Can set edge globalConfig option tcpTimeoutClose" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -tcpTimeoutClose 40 -NoConfirm - $config.globalConfig.tcpTimeoutClose | should be "40" + $config.globalConfig.tcpTimeoutClose | Should be "40" } It "Can set edge globalConfig option udpTimeout" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -udpTimeout 70 -NoConfirm - $config.globalConfig.udpTimeout | should be "70" + $config.globalConfig.udpTimeout | Should be "70" } It "Can set edge globalConfig option icmpTimeout" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -icmpTimeout 20 -NoConfirm - $config.globalConfig.icmpTimeout | should be "20" + $config.globalConfig.icmpTimeout | Should be "20" } It "Can set edge globalConfig option icmp6Timeout" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -icmp6Timeout 20 -NoConfirm - $config.globalConfig.icmp6Timeout | should be "20" + $config.globalConfig.icmp6Timeout | Should be "20" } It "Can set edge globalConfig option ipGenericTimeout" { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -ipGenericTimeout 130 -NoConfirm - $config.globalConfig.ipGenericTimeout | should be "130" + $config.globalConfig.ipGenericTimeout | Should be "130" } It "Can set edge globalConfig option enableSynFloodProtection on NSX -ge 6.2.3" -Skip:$VersionLessThan623 { - $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -enableSynFloodProtection -NoConfirm - $config.globalConfig.enableSynFloodProtection | should be "true" + $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -enableSynFloodProtection -NoConfirm + $config.globalConfig.enableSynFloodProtection | Should be "true" } It "Can set edge globalConfig option logIcmpErrors on NSX -ge 6.3.0" -Skip:$VersionLessThan630 { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -logIcmpErrors -NoConfirm - $config.globalConfig.logIcmpErrors | should be "true" + $config.globalConfig.logIcmpErrors | Should be "true" } It "Can set edge globalConfig option dropIcmpReplays on NSX -ge 6.3.0" -Skip:$VersionLessThan630 { $config = Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -dropIcmpReplays -NoConfirm - $config.globalConfig.dropIcmpReplays | should be "true" + $config.globalConfig.dropIcmpReplays | Should be "true" } It "Throws a warning when setting edge globalConfig option enableSynFloodProtection on NSX -lt 6.2.3" -Skip:(-not $VersionLessThan623) { - (( Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -enableSynFloodProtection -NoConfirm ) 3>&1) -match "The option enableSynFloodProtection requires at least NSX version 6.2.3" | should be $true + (( Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -enableSynFloodProtection -NoConfirm ) 3>&1) -match "The option enableSynFloodProtection requires at least NSX version 6.2.3" | Should be $true } It "Throws a warning when setting edge globalConfig option logIcmpErrors on NSX -lt 6.3.0" -Skip:(-not $VersionLessThan630) { - (( Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -logIcmpErrors -NoConfirm ) 3>&1) -match "The option logIcmpErrors requires at least NSX version 6.3.0" | should be $true + (( Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -logIcmpErrors -NoConfirm ) 3>&1) -match "The option logIcmpErrors requires at least NSX version 6.3.0" | Should be $true } It "Throws a warning when setting edge globalConfig option dropIcmpReplays on NSX -lt 6.3.0" -Skip:(-not $VersionLessThan630) { - (( Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -dropIcmpReplays -NoConfirm ) 3>&1) -match "The option dropIcmpReplays requires at least NSX version 6.3.0" | should be $true + (( Get-NsxEdge $name | Get-NsxEdgeFirewall | Set-NsxEdgeFirewall -dropIcmpReplays -NoConfirm ) 3>&1) -match "The option dropIcmpReplays requires at least NSX version 6.3.0" | Should be $true } } Context "SSH" { - it "Can disable SSH" { + BeforeAll { + if ( -not ( Get-NsxEdge $name ) ) { + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" + } + } + + It "Can disable SSH" { $edge = Get-NsxEdge $name #When deploy pstester ESG, the SSH is enabled - $edge.cliSettings.remoteAccess | should be "true" - Get-NsxEdge $name | Disable-NsxEdgeSsh -confirm:$false + $edge.cliSettings.remoteAccess | Should be "true" + Get-NsxEdge $name | Disable-NsxEdgeSsh -Confirm:$false $edge = Get-NsxEdge $name - $edge.cliSettings.remoteAccess | should be "false" + $edge.cliSettings.remoteAccess | Should be "false" } - it "Can enable SSH" { + It "Can enable SSH" { Get-NsxEdge $name | Enable-NsxEdgeSsh $edge = Get-NsxEdge $name - $edge.cliSettings.remoteAccess | should be "true" + $edge.cliSettings.remoteAccess | Should be "true" } } Context "CliSettings" { - it "Can retrieve cliSettings" { - $edge = Get-NsxEdge $name - $edge.cliSettings | should not be $null + BeforeAll { + if ( -not ( Get-NsxEdge $name ) ) { + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" + } + } + + It "Can retrieve cliSettings" { + $edge = Get-NsxEdge $name + $edge.cliSettings | Should not be $null #By default it is admin - $edge.cliSettings.userName | should be "admin" + $edge.cliSettings.userName | Should be "admin" #By default it is 99999 - $edge.cliSettings.passwordExpiry | should be "99999" + $edge.cliSettings.passwordExpiry | Should be "99999" } - it "Can disable SSH" { + It "Can disable SSH" { $edge = Get-NsxEdge $name - Get-NsxEdge $name | Set-NsxEdge -remoteAccess:$false -confirm:$false + Get-NsxEdge $name | Set-NsxEdge -remoteAccess:$false -Confirm:$false $edge = Get-NsxEdge $name - $edge.cliSettings.remoteAccess | should be "false" + $edge.cliSettings.remoteAccess | Should be "false" } - it "Can enable SSH" { - Get-NsxEdge $name | Set-NsxEdge -remoteAccess:$true -confirm:$false + It "Can enable SSH" { + Get-NsxEdge $name | Set-NsxEdge -remoteAccess:$true -Confirm:$false $edge = Get-NsxEdge $name - $edge.cliSettings.remoteAccess | should be "true" + $edge.cliSettings.remoteAccess | Should be "true" } - it "Change (SSH) username (and Password)" { + It "Change (SSH) username (and Password)" { #it is mandatory to change username (and Password) on the same time (bug or feature ?) - Get-NsxEdge $name | Set-NsxEdge -userName powernsxviasetnsxedge -Password "Vmware1!Vmware1!" -confirm:$false + Get-NsxEdge $name | Set-NsxEdge -userName powernsxviasetnsxedge -Password "Vmware1!Vmware1!" -Confirm:$false $edge = Get-NsxEdge $name - $edge.cliSettings.userName | should be "powernsxviasetnsxedge" + $edge.cliSettings.userName | Should be "powernsxviasetnsxedge" #It is impossible to check if the password is modified... } - it "Change Password Expiry" { - Get-NsxEdge $name | Set-NsxEdge -passwordExpiry 4242 -confirm:$false + It "Change Password Expiry" { + Get-NsxEdge $name | Set-NsxEdge -passwordExpiry 4242 -Confirm:$false + $edge = Get-NsxEdge $name + $edge.cliSettings.passwordExpiry | Should be "4242" + } + + It "Change sshLoginBannerText" { + Get-NsxEdge $name | Set-NsxEdge -sshLoginBannerText "Secured by Set-NsxEdge" -Confirm:$false + $edge = Get-NsxEdge $name + $edge.cliSettings.sshLoginBannerText | Should be "Secured by Set-NsxEdge" + } + } + + Context "FIPS" { + + BeforeAll { + if ( -not ( Get-NsxEdge $name ) ) { + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" + } + } + + It "Edge deployed by default with FIPS mode disabled" { $edge = Get-NsxEdge $name - $edge.cliSettings.passwordExpiry | should be "4242" + $edge | Should not be $null + $edge.enableFips | Should be "false" } - it "Change sshLoginBannerText" { - Get-NsxEdge $name | Set-NsxEdge -sshLoginBannerText "Secured by Set-NsxEdge" -confirm:$false + It "Can enable FIPS mode on an already deployed Edge" { $edge = Get-NsxEdge $name - $edge.cliSettings.sshLoginBannerText | should be "Secured by Set-NsxEdge" + $edge | Should not be $null + $edge.enableFips | Should be "false" + $edge | Enable-NsxEdgeFips -confirm:$false + $edgeFIPSEnabled = Get-NsxEdge $name + $edgeFIPSEnabled | Should not be $null + $edgeFIPSEnabled.enableFips | Should be "true" + } + + It "Can disable FIPS mode on an already deployed Edge" { + $edge = Get-NsxEdge $name + $edge | Should not be $null + $edge.enableFips | Should be "true" + $edge | Disable-NsxEdgeFips -confirm:$false + $edgeFIPSDisabled = Get-NsxEdge $name + $edgeFIPSDisabled | Should not be $null + $edgeFIPSDisabled.enableFips | Should be "false" + } + + It "Can deploy an edge with FIPS mode enabled" { + { $null = New-NsxEdge -Name $fipsName -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "fips-pestertest" -EnableFIPS } | Should not throw + $edgeNew = Get-NsxEdge $fipsName + $edgeNew | Should not be $null + $edgeNew.enableFips | Should be "true" } } Context "Misc" { - it "Can enable firewall via Set-NsxEdge" { + BeforeAll { + if ( -not ( Get-NsxEdge $name ) ) { + New-NsxEdge -Name $name -Interface $vnics[0], $vnics[1], $vnics[2] -Cluster $cl -Datastore $ds -Password $password -Tenant $tenant -EnableSSH -Hostname "pestertest" + } + } + + It "Can enable firewall via Set-NsxEdge" { $edge = Get-NsxEdge $name - $edge | should not be $null - $edge.features.firewall.enabled | should be "false" + $edge | Should not be $null + $edge.features.firewall.enabled | Should be "false" $edge.features.firewall.enabled = "true" - $edge | Set-NsxEdge -confirm:$false + $edge | Set-NsxEdge -Confirm:$false $edge = Get-NsxEdge $name - $edge.features.firewall.enabled | should be "true" + $edge.features.firewall.enabled | Should be "true" } - it "Can remove an edge" { - Get-NsxEdge $name | should not be $null - Get-NsxEdge $name | remove-nsxEdge -confirm:$false - get-nsxEdge $name | should be $null + It "Can remove an edge" { + Get-NsxEdge $name | Should not be $null + Get-NsxEdge $name | Remove-NsxEdge -Confirm:$false + Get-NsxEdge $name | Should be $null } } }