forked from vmware-archive/powernsx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PowerNSX.psm1
23190 lines (17860 loc) · 899 KB
/
PowerNSX.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Powershell NSX module
#Nick Bradford
#Version - See Manifest for version details.
<#
Copyright © 2015 VMware, Inc. All Rights Reserved.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTIBILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details.
You should have received a copy of the General Public License version 2 along with this program.
If not, see https://www.gnu.org/licenses/gpl-2.0.html.
The full text of the General Public License 2.0 is provided in the COPYING file.
Some files may be comprised of various open source software components, each of which
has its own license that is located in the source code of the respective component.
#>
#Requires -Version 3.0
#More sophisticated requirement checking done at module load time.
#My installer home and valid PNSX branches (releases) (used in Update-Powernsx.)
$PNsxUrlBase = "https://raw.githubusercontent.com/vmware/powernsx"
$ValidBranches = @("master","v1","v2")
set-strictmode -version Latest
## Custom classes
if ( -not ("TrustAllCertsPolicy" -as [type])) {
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
}
function Check-PowerCliAsemblies {
#Checks for known assemblies loaded by PowerCLI.
#PowerNSX uses a variety of types, and full operation requires
#extensive PowerCLI usage.
#As of v2, we now _require_ PowerCLI assemblies to be available.
#This method works for both PowerCLI 5.5 and 6 (snapin vs module),
#shouldnt be as heavy as loading each required type explicitly to check
#and should function in a modified PowerShell env, as well as normal
#PowerCLI.
$RequiredAsm = (
"VMware.VimAutomation.ViCore.Cmdlets",
"VMware.Vim",
"VMware.VimAutomation.Sdk.Util10Ps",
"VMware.VimAutomation.Sdk.Util10",
"VMware.VimAutomation.Sdk.Interop",
"VMware.VimAutomation.Sdk.Impl",
"VMware.VimAutomation.Sdk.Types",
"VMware.VimAutomation.ViCore.Types",
"VMware.VimAutomation.ViCore.Interop",
"VMware.VimAutomation.ViCore.Util10",
"VMware.VimAutomation.ViCore.Util10Ps",
"VMware.VimAutomation.ViCore.Impl",
"VMware.VimAutomation.Vds.Commands",
"VMware.VimAutomation.Vds.Impl",
"VMware.VimAutomation.Vds.Interop",
"VMware.VimAutomation.Vds.Types"
)
$CurrentAsmName = foreach( $asm in ([AppDomain]::CurrentDomain.GetAssemblies())) { $asm.getName() }
$CurrentAsmDict = $CurrentAsmName | Group-Object -AsHashTable -Property Name
foreach( $req in $RequiredAsm ) {
if ( -not $CurrentAsmDict.Contains($req) ) {
write-warning "PowerNSX requires PowerCLI."
throw "Assembly $req not found. Some required PowerCli types are not available in this PowerShell session. Please ensure you are running PowerNSX in a PowerCLI session, or have manually loaded the required assemblies."}
}
}
#Check required PowerCLI assemblies are loaded.
Check-PowerCliAsemblies
########
########
# Private functions
Function Test-WebServerSSL {
# Function original location: http://en-us.sysadmins.lv/Lists/Posts/Post.aspx?List=332991f0-bfed-4143-9eea-f521167d287c&ID=60
# Ref : https://communities.vmware.com/thread/501913?start=0&tstart=0 - Thanks Alan ;)
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$URL,
[Parameter(Position = 1)]
[ValidateRange(1,65535)]
[int]$Port = 443,
[Parameter(Position = 2)]
[Net.WebProxy]$Proxy,
[Parameter(Position = 3)]
[int]$Timeout = 15000,
[switch]$UseUserContext
)
Add-Type @"
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
namespace PKI {
namespace Web {
public class WebSSL {
public Uri OriginalURi;
public Uri ReturnedURi;
public X509Certificate2 Certificate;
//public X500DistinguishedName Issuer;
//public X500DistinguishedName Subject;
public string Issuer;
public string Subject;
public string[] SubjectAlternativeNames;
public bool CertificateIsValid;
//public X509ChainStatus[] ErrorInformation;
public string[] ErrorInformation;
public HttpWebResponse Response;
}
}
}
"@
$ConnectString = "https://$url`:$port"
$WebRequest = [Net.WebRequest]::Create($ConnectString)
$WebRequest.Proxy = $Proxy
$WebRequest.Credentials = $null
$WebRequest.Timeout = $Timeout
$WebRequest.AllowAutoRedirect = $true
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
try {$Response = $WebRequest.GetResponse()}
catch {}
if ($WebRequest.ServicePoint.Certificate -ne $null) {
$Cert = [Security.Cryptography.X509Certificates.X509Certificate2]$WebRequest.ServicePoint.Certificate.Handle
try {$SAN = ($Cert.Extensions | Where-Object {$_.Oid.Value -eq "2.5.29.17"}).Format(0) -split ", "}
catch {$SAN = $null}
$chain = New-Object Security.Cryptography.X509Certificates.X509Chain -ArgumentList (!$UseUserContext)
[void]$chain.ChainPolicy.ApplicationPolicy.Add("1.3.6.1.5.5.7.3.1")
$Status = $chain.Build($Cert)
New-Object PKI.Web.WebSSL -Property @{
OriginalUri = $ConnectString;
ReturnedUri = $Response.ResponseUri;
Certificate = $WebRequest.ServicePoint.Certificate;
Issuer = $WebRequest.ServicePoint.Certificate.Issuer;
Subject = $WebRequest.ServicePoint.Certificate.Subject;
SubjectAlternativeNames = $SAN;
CertificateIsValid = $Status;
Response = $Response;
ErrorInformation = $chain.ChainStatus | ForEach-Object {$_.Status}
}
$chain.Reset()
[Net.ServicePointManager]::ServerCertificateValidationCallback = $null
$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($ConnectString)
$ServicePoint.CloseConnectionGroup("") | out-null
write-debug "$($MyInvocation.MyCommand.Name) : Closing connections to $ConnectString."
} else {
Write-Error $Error[0]
}
}
function Add-XmlElement {
#Internal function used to simplify the exercise of adding XML text Nodes.
param (
[System.XML.XMLElement]$xmlRoot,
[String]$xmlElementName,
[String]$xmlElementText
)
#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
}
function Get-FeatureStatus {
param (
[string]$featurestring,
[system.xml.xmlelement[]]$statusxml
)
[system.xml.xmlelement]$feature = $statusxml | ? { $_.featureId -eq $featurestring } | select -first 1
[string]$statusstring = $feature.status
$message = $feature.SelectSingleNode('message')
if ( $message -and ( $message | get-member -membertype Property -Name '#Text')) {
$statusstring += " ($($message.'#text'))"
}
$statusstring
}
function Parse-CentralCliResponse {
param (
[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...
#Control flags for handling list and table processing.
$TableHeaderFound = $false
$MatchedVnicsList = $false
$MatchedRuleset = $false
$MatchedAddrSet = $false
$RuleSetName = ""
$AddrSetName = ""
$KeyValHash = @{}
$KeyValHashUsed = $false
#Defined this as variable as the swtich statement does not let me concat strings, which makes for a verrrrry long line...
$RegexDFWRule = "^(?<Internal>#\sinternal\s#\s)?(?<RuleSetMember>rule\s)?(?<RuleId>\d+)\sat\s(?<Position>\d+)\s(?<Direction>in|out|inout)\s" +
"(?<Type>protocol|ethertype)\s(?<Service>.*?)\sfrom\s(?<Source>.*?)\sto\s(?<Destination>.*?)(?:\sport\s(?<Port>.*))?\s" +
"(?<Action>accept|reject|drop)(?:\swith\s(?<Log>log))?(?:\stag\s(?<Tag>'.*'))?;"
foreach ( $line in ($response -split '[\r\n]')) {
#Init EntryHash hashtable
$EntryHash= @{}
switch -regex ($line.trim()) {
#C CLI appears to emit some error conditions as ^ Error:<digits>
"^Error \d+:.*$" {
write-debug "$($MyInvocation.MyCommand.Name) : Matched Error line. $_ "
Throw "CLI command returned an error: ( $_ )"
}
"^\s*$" {
#Blank line, ignore...
write-debug "$($MyInvocation.MyCommand.Name) : Ignoring blank line: $_"
break
}
"^# Filter rules$" {
#Filter line encountered in a ruleset list, ignore...
if ( $MatchedRuleSet ) {
write-debug "$($MyInvocation.MyCommand.Name) : Ignoring meaningless #Filter rules line in ruleset: $_"
break
}
else {
throw "Error parsing Centralised CLI command output response. Encountered #Filter rules line when not processing a ruleset: $_"
}
}
#Matches a single integer of 1 or more digits at the start of the line followed only by a fullstop.
#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: $_ "
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"
$VnicListHash = @{}
$VnicListHash += $KeyValHash
$KeyValHashUsed = $true
}
break
}
#Matches the start of a ruleset list. show dfw host host-xxx filter xxx rules will output in rulesets like this
"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: $_"
$MatchedRuleset = $true
$RuleSetName = $matches[1].trim()
break
}
#Matches the start of a addrset list. show dfw host host-xxx filter xxx addrset will output in addrsets like this
"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: $_"
$MatchedAddrSet = $true
$AddrSetName = $matches[1].trim()
break
}
#Matches a addrset entry. show dfw host host-xxx filter xxx addrset will output in addrsets.
"^(?<Type>ip|mac)\s(?<Address>.*),$" {
#Make sure we were expecting it...
if ( -not $MatchedAddrSet ) {
Throw "Error parsing Centralised CLI command output response. Unexpected dfw addrset entry : $_"
}
#We are processing a RuleSet, so we need to emit an output object that contains the ruleset name.
[PSCustomobject]@{
"AddrSet" = $AddrSetName;
"Type" = $matches.Type;
"Address" = $matches.Address
}
break
}
#Matches a rule, either within a ruleset, or individually listed. show dfw host host-xxx filter xxx rules will output in rulesets,
#or show dfw host-xxx filter xxx rule 1234 will output individual rule that should match.
$RegexDFWRule {
#Check if the rule is individual or part of ruleset...
if ( $Matches.ContainsKey("RuleSetMember") -and (-not $MatchedRuleset )) {
Throw "Error parsing Centralised CLI command output response. Unexpected dfw ruleset entry : $_"
}
$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 }
$Tag = if ( $matches.ContainsKey("Tag") ) { $matches.Tag } else { "" }
If ( $MatchedRuleset ) {
#We are processing a RuleSet, so we need to emit an output object that contains the ruleset name.
[PSCustomobject]@{
"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
}
}
else {
#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
}
}
break
}
#Matches the end of a ruleset and addr lists. show dfw host host-xxx filter xxx rules will output in lists like this
"^}$" {
if ( $MatchedRuleset ) {
#Clear the flag to say we matched a ruleset List
write-debug "$($MyInvocation.MyCommand.Name) : Matched end of DFW ruleset."
$MatchedRuleset = $false
$RuleSetName = ""
break
}
if ( $MatchedAddrSet ) {
#Clear the flag to say we matched an addrset List
write-debug "$($MyInvocation.MyCommand.Name) : Matched end of DFW addrset."
$MatchedAddrSet = $false
$AddrSetName = ""
break
}
throw "Error parsing Centralised CLI command output response. Encountered unexpected list completion character in line: $_"
}
#More Generic matches
#Matches the generic KV case where we have _only_ two strings separated by more than one space.
#This will do my head in later when I look at it, so the regex explanation is:
# - (?: gives non capturing group, we want to leverage $matches later, so dont want polluting groups.
# - (\S|\s(?!\s)) uses negative lookahead assertion to 'Match a non whitespace, or a single whitespace, as long as its not followed by another whitespace.
# - 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): $_ )"
$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"
$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."
[PSCustomobject]$VnicListHash
}
}
else {
#Add KV to hash table that we will append to output object
$KeyValHash.Add($key,$value)
}
break
}
#Matches a general case output line containing Key: Value for properties that are consistent accross all entries in a table.
#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) : $_"
#Add KV to hash table that we will append to output object
$KeyValHash.Add($matches[1].trim(),$matches[2].trim())
break
}
#Matches a Table header line. This is a special case of the table entry line match, with the first element being ^No\. Hoping that 'No.' start of the line is consistent :S
"^No\.\s{2,}(.+\s{2,})+.+$" {
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: $_"
$TableHeaderFound = $true
$Props = $_.trim() -split "\s{2,}"
break
}
#Matches the start of a Virtual Nics List output. We process the output lines following this as a different output object
"Virtual Nics List:" {
#When central cli outputs a NIC 'list' it does so with a vertical list of Key Value rather than a table format,
#and with multi space as the KV separator, rather than a : like normal KV output. WTF?
#So Now I have to go forth and collate my nic object over the next few lines...
#Example looks like this:
#Virtual Nics List:
#1.
#Vnic Name test-vm - Network adapter 1
#Vnic Id 50012d15-198c-066c-af22-554aed610579.000
#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: $_"
$MatchedVnicsList = $true
break
}
#Matches a table entry line. At least three properties (that may contain a single space) separated by more than one space.
"^((?:\S|\s(?!\s))+\s{2,}){2,}((?:\S|\s(?!\s))+)$" {
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: $_"
$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++ ) {
#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()
}
}
#Add the KV pairs that were parsed before the table.
try {
#This may fail if we have a key of the same name. For the moment, Im going to assume that this wont happen...
$EntryHash += $KeyValHash
$KeyValHashUsed = $true
}
catch {
throw "Unable to append static Key Values to EntryHash output object. Possibly due to a conflicting key"
}
#Emit the entry line as a PSCustomobject :)
[PSCustomObject]$EntryHash
break
}
default { throw "Unable to parse Centralised CLI output line : $($_ -replace '\s','_')" }
}
}
if ( (-not $KeyValHashUsed) -and $KeyValHash.count -gt 0 ) {
#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: $_"
[PSCustomObject]$KeyValHash
}
}
########
########
# Validation Functions
function Validate-UpdateBranch {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if ( $ValidBranches -contains $argument ) {
$true
} else {
throw "Invalid Branch. Specify one of the valid branches : $($Validbranches -join ", ")"
}
}
Function Validate-TransportZone {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
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 )) {
throw "Invalid Transport Zone object specified"
}
if ( -not ($argument.objectTypeName -eq "VdnScope")) {
throw "Invalid Transport Zone object specified"
}
$true
}
else {
throw "Invalid Transport Zone object specified"
}
}
Function Validate-LogicalSwitchOrDistributedPortGroup {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if (-not (
($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)) {
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)) {
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)) {
throw "Object specified does not contain a name property. Specify a Distributed PortGroup or Logical Switch object."
}
switch ($argument.objectTypeName) {
"VirtualWire" { }
default { throw "Object specified is not a supported type. Specify a Distributed PortGroup or Logical Switch object." }
}
}
else {
#Its a VDS type - no further Checking
}
}
$true
}
Function Validate-LogicalSwitchOrDistributedPortGroupOrStandardPortGroup {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if (-not (
($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)) {
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)) {
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)) {
throw "Object specified does not contain a name property. Specify a Distributed PortGroup, Standard PortGroup or Logical Switch object."
}
switch ($argument.objectTypeName) {
"VirtualWire" { }
default { throw "Object specified is not a supported type. Specify a Distributed PortGroup, Standard PortGroup or Logical Switch object." }
}
}
$true
}
Function Validate-IpPool {
Param (
[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)) {
throw "XML Element specified does not contain an objectId property."
}
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)) {
throw "XML Element specified does not contain a usedPercentage property."
}
$true
}
else {
throw "Specify a valid IP Pool object."
}
}
Function Validate-VdsContext {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if ($argument -is [System.Xml.XmlElement] ) {
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)) {
throw "XML Element specified does not contain an mtu property."
}
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)) {
throw "XML Element specified does not contain a promiscuousMode property."
}
$true
}
else {
throw "Specify a valid Vds Context object."
}
}
Function Validate-SegmentIdRange {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if ($argument -is [System.Xml.XmlElement] ) {
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)) {
throw "XML Element specified does not contain a name property."
}
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)) {
throw "XML Element specified does not contain an end property."
}
$true
}
else {
throw "Specify a valid Segment Id Range object."
}
}
Function Validate-DistributedSwitch {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if (-not ($argument -is [VMware.VimAutomation.ViCore.Interop.V1.Host.Networking.DistributedSwitchInterop] ))
{
throw "Must specify a distributed switch"
}
$true
}
Function Validate-LogicalSwitch {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
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)) {
throw "Object specified does not contain an objectId property. Specify a Logical Switch object."
}
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)) {
throw "Object specified does not contain a name property. Specify a Logical Switch object."
}
switch ($argument.objectTypeName) {
"VirtualWire" { }
default { throw "Object specified is not a supported type. Specify a Logical Switch object." }
}
}
$true
}
Function Validate-LogicalRouterInterfaceSpec {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
#temporary - need to script proper validation of a single valid NIC config for DLR (Edge and DLR have different specs :())
if ( -not $argument ) {
throw "Specify at least one interface configuration as produced by New-NsxLogicalRouterInterfaceSpec. Pass a collection of interface objects to configure more than one interface"
}
$true
}
Function Validate-EdgeInterfaceSpec {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
#temporary - need to script proper validation of a single valid NIC config for DLR (Edge and DLR have different specs :())
if ( -not $argument ) {
throw "Specify at least one interface configuration as produced by New-NsxLogicalRouterInterfaceSpec. Pass a collection of interface objects to configure more than one interface"
}
$true
}
Function Validate-EdgeInterfaceAddress {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if ($argument -is [System.Xml.XmlElement] ) {
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)) {
throw "XML Element specified does not contain a subnetPrefixLength property."
}
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)) {
throw "XML Element specified does not contain an edgeId property."
}
if ( -not ( $argument | get-member -name interfaceIndex -Membertype Properties)) {
throw "XML Element specified does not contain an interfaceIndex property."
}
$true
}
else {
throw "Specify a valid Edge Interface Address."
}
}
Function Validate-AddressGroupSpec {
Param (
[Parameter (Mandatory=$true)]
[object]$argument
)
if ($argument -is [System.Xml.XmlElement] ) {
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)) {
throw "XML Element specified does not contain a subnetPrefixLength property."
}
$true
}
else {
throw "Specify a valid Interface Spec."
}
}
Function Validate-LogicalRouter {
Param (
[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)) {
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)) {
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)) {
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)) {
throw "XML Element specified does not contain a type property. Specify a valid Logical Router Object"
}
if ($argument.edgeSummary.objectTypeName -ne "Edge" ) {
throw "Specified value is not a supported type. Specify a valid Logical Router Object."
}
if ($argument.type -ne "distributedRouter" ) {
throw "Specified value is not a supported type. Specify a valid Logical Router Object."
}
$true
}
else {
throw "Specify a valid Logical Router Object"
}
}
else {
throw "Specify a valid Logical Router Object"
}
}
Function Validate-Edge {
Param (
[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)) {
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)) {
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)) {
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)) {
throw "XML Element specified does not contain a type property. Specify an NSX Edge Services Gateway object"
}
if ($argument.edgeSummary.objectTypeName -ne "Edge" ) {
throw "Specified value is not a supported type. Specify an NSX Edge Services Gateway object."
}
if ($argument.type -ne "gatewayServices" ) {
throw "Specified value is not a supported type. Specify an NSX Edge Services Gateway object."
}
$true
}
else {
throw "Specify a valid Edge Services Gateway Object"
}
}
else {
throw "Specify a valid Edge Services Gateway Object"
}
}
Function Validate-EdgeRouting {
Param (
[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)) {
throw "XML Element specified does not contain a routingGlobalConfig property."
}
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)) {
throw "XML Element specified does not contain a version property."
}
if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) {
throw "XML Element specified does not contain an edgeId property."
}
$true
}
else {
throw "Specify a valid Edge Routing object."
}
}
Function Validate-EdgeStaticRoute {
Param (
[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)) {
throw "XML Element specified does not contain a type property."
}
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)) {
throw "XML Element specified does not contain a nextHop property."
}
if ( -not ( $argument | get-member -name edgeId -Membertype Properties)) {
throw "XML Element specified does not contain an edgeId property."
}
$true
}