PowervRNI.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
# vRealize Network Insight PowerShell module
# Martijn Smit (@smitmartijn)
# msmit@vmware.com
# Version 1.0


# Keep a list handy of all data source types and the different URIs that is supposed to be called for that datasource
$Script:DatasourceURLs = @{}
$Script:DatasourceURLs.Add("vcenter", @("/data-sources/vcenters"))
$Script:DatasourceURLs.Add("nsxv", @("/data-sources/nsxv-managers"))
$Script:DatasourceURLs.Add("ciscoswitch", @("/data-sources/cisco-switches"))
$Script:DatasourceURLs.Add("aristaswitch", @("/data-sources/arista-switches"))
$Script:DatasourceURLs.Add("dellswitch", @("/data-sources/dell-switches"))
$Script:DatasourceURLs.Add("brocadeswitch", @("/data-sources/brocade-switches"))
$Script:DatasourceURLs.Add("juniperswitch", @("/data-sources/juniper-switches"))
$Script:DatasourceURLs.Add("ciscoucs", @("/data-sources/ucs-managers"))
$Script:DatasourceURLs.Add("hponeview", @("/data-sources/hpov-managers"))
$Script:DatasourceURLs.Add("hpvcmanager", @("/data-sources/hpvc-managers"))
$Script:DatasourceURLs.Add("checkpointfirewall", @("/data-sources/checkpoint-firewalls"))
$Script:DatasourceURLs.Add("panfirewall", @("/data-sources/panorama-firewalls"))
$Script:DatasourceURLs.Add("all", @("/data-sources/vcenters", "/data-sources/nsxv-managers", "/data-sources/cisco-switches", "/data-sources/arista-switches", "/data-sources/dell-switches", "/data-sources/brocade-switches", "/data-sources/juniper-switches", "/data-sources/ucs-managers", "/data-sources/hpov-managers", "/data-sources/hpvc-managers", "/data-sources/checkpoint-firewalls", "/data-sources/panorama-firewalls"))

# Keep another list handy which translates the internal vRNI Names for datasources to their relative URLs
$Script:DatasourceInternalURLs = @{}
$Script:DatasourceInternalURLs.Add("VCenterDataSource", "/data-sources/vcenters")
$Script:DatasourceInternalURLs.Add("NSXVManagerDataSource", "/data-sources/nsxv-managers")
$Script:DatasourceInternalURLs.Add("CiscoSwitchDataSource", "/data-sources/cisco-switches")
$Script:DatasourceInternalURLs.Add("AristaSwitchDataSource", "/data-sources/arista-switches")
$Script:DatasourceInternalURLs.Add("DellSwitchDataSource", "/data-sources/dell-switches")
$Script:DatasourceInternalURLs.Add("BrocadeSwitchDataSource", "/data-sources/brocade-switches")
$Script:DatasourceInternalURLs.Add("JuniperSwitchDataSource", "/data-sources/juniper-switches")
$Script:DatasourceInternalURLs.Add("UCSManagerDataSource", "/data-sources/ucs-managers")
$Script:DatasourceInternalURLs.Add("HPOneViewManagerDataSource", "/data-sources/hpov-managers")
$Script:DatasourceInternalURLs.Add("HPVCManagerDataSource", "/data-sources/hpvc-managers")
$Script:DatasourceInternalURLs.Add("CheckpointFirewallDataSource", "/data-sources/checkpoint-firewalls")
$Script:DatasourceInternalURLs.Add("PanFirewallDataSource", "/data-sources/panorama-firewalls")

# Thanks to PowerNSX (http://github.com/vmware/powernsx) for providing some of the base functions &
# principles on which this module is built on.

# Run at module load time to determine a few things about the platform this module is running on.
# TODO: use a psd1 to mask this function to the outside world
function _PvRNI_init 
{
  # $PSVersionTable.PSEdition property does not exist pre v5. We need to do a few things in
  # exported functions to workaround some limitations of core edition, so we export
  # the global PNSXPSTarget var to reference if required.
  if(($PSVersionTable.PSVersion.Major -ge 6) -or (($PSVersionTable.PSVersion.Major -eq 5) -And ($PSVersionTable.PSVersion.Minor -ge 1))) {
    $script:PvRNI_PlatformType = $PSVersionTable.PSEdition
  }
  else {
    $script:PvRNI_PlatformType = "Desktop"
  }

  # Define class required for certificate validation override. Version dependant.
  # For whatever reason, this does not work when contained within a function?
  $TrustAllCertsPolicy = @"
    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;
      }
    }
"@


  if($script:PvRNI_PlatformType -eq "Desktop") {
    if (-not ("TrustAllCertsPolicy" -as [type])) {
      Add-Type $TrustAllCertsPolicy
      Write-Host "TrustAllCertsPolicy"
    }
  }
}


function Invoke-vRNIRestMethod
{
  <#
  .SYNOPSIS
  Forms and executes a REST API call to a vRealize Network Insight Platform VM.
 
  .DESCRIPTION
  Invoke-vRNIRestMethod uses either a specified connection object as returned
  by Connect-vRNIServer, or the $defaultvRNIConnection global variable if
  defined to construct a REST api call to the vRNI API.
 
  Invoke-vRNIRestMethod constructs the appropriate request headers required by
  the vRNI API, including the authentication token (built from the connection
  object) and the content type, before making the rest call and returning the
  appropriate JSON object to the caller cmdlet.
 
  .EXAMPLE
  Invoke-vRNIRestMethod -Method GET -Uri "/api/ni/data-sources/vcenters"
 
  Performs a 'GET' against the URI /api/ni/data-sources/vcenters and returns
  the JSON object which contains the vRNI response. This call requires the
  $defaultvRNIConnection variable to exist and be populated with server and
  authentiation details as created by Connect-vRNIServer, or it fails with a
  message to first use Connect-vRNIServer
 
  .EXAMPLE
  $MyConnection = Connect-vRNIServer -Server vrni-platform.lab.local
  Invoke-vRNIRestMethod -Method GET -Uri "/api/ni/data-sources/vcenters" -Connection $MyConnection
 
  Connects to a vRNI Platform VM and stores the connection details in a
  variable, which in turn is used for the following cmdlet to retrieve
  all vCenter datasources. The JSON object containing the vRNI response
  is returned.
  #>


  [CmdletBinding(DefaultParameterSetName="ConnectionObj")]

  param (
    [Parameter (Mandatory=$true,ParameterSetName="Parameter")]
      # vRNI Platform server
      [string]$Server,
    [Parameter (Mandatory=$true,ParameterSetName="Parameter")]
    [Parameter (ParameterSetName="ConnectionObj")]
      # REST Method (GET, POST, DELETE, UPDATE)
      [string]$Method,
    [Parameter (Mandatory=$true,ParameterSetName="Parameter")]
    [Parameter (ParameterSetName="ConnectionObj")]
      # URI of API endpoint (/api/ni/endpoint)
      [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-vRNIServer
      [psObject]$Connection
  )

  if ($pscmdlet.ParameterSetName -eq "ConnectionObj")
  {
    # Ensure we were either called with a connection or there is a defaultConnection (user has called Connect-vRNIServer)
    if ($connection -eq $null)
    {
      # Now we need to assume that defaultvRNIConnection does not exist...
      if ( -not (test-path variable:global:defaultvRNIConnection) ) {
        throw "Not connected. Connect to vRNI with Connect-vRNIServer first."
      }
      else {
        Write-Host "$($MyInvocation.MyCommand.Name) : Using default connection"
        $connection = $defaultvRNIConnection
      }
    }

    $authtoken = $connection.AuthToken
    $authtoken_expiry = $connection.AuthTokenExpiry
    $server = $connection.Server

    # Check if the authentication token hasn't expired yet
    if([int][double]::Parse((Get-Date -UFormat %s)) -gt $authtoken_expiry) {
      throw "The vRNI Authentication token has expired. Please login again using Connect-vRNIServer."
    }
  }

  # Create a header option dictionary, to be used for authentication (if we have an existing session) and other RESTy stuff
  $headerDict = @{}
  $headerDict.add("Content-Type", "application/json")

  if($authtoken -ne "") {
    $headerDict.add("Authorization", "NetworkInsight $authtoken")
  }

  # Form the URL to call and write in our journal about this call
  $URL = "https://$($Server)$($URI)"
  Write-Debug "$(Get-Date -format s) REST Call via Invoke-RestMethod: $Method $URL - with body: $Body"

  # Build up Invoke-RestMethod parameters, can differ per platform
  $invokeRestMethodParams = @{
    "Method" = $Method;
    "Headers" = $headerDict;
    "ContentType" = "application/json";
    "Uri" = $URL;
  }

  if($Body -ne "") {
    $invokeRestMethodParams.Add("Body", $body)
  }

  # On PowerShell Desktop, add a trigger to ignore SSL certificate checks
  if(($script:PvRNI_PlatformType -eq "Desktop")) 
  {
    # Allow untrusted certificate presented by the remote system to be accepted
    if([System.Net.ServicePointManager]::CertificatePolicy.tostring() -ne 'TrustAllCertsPolicy') {
      [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
    }
  }
  # Core (for now) uses a different mechanism to manipulating [System.Net.ServicePointManager]::CertificatePolicy
  if(($script:PvRNI_PlatformType -eq "Core")) {
    $invokeRestMethodParams.Add("SkipCertificateCheck", $true)
  }

  # Energize!
  try
  {
    $response = Invoke-RestMethod @invokeRestMethodParams
  }

  # 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()
      $reader = New-Object system.io.streamreader($responseStream)
      $responseBody = $reader.readtoend()
      $ErrorString = "$($MyInvocation.MyCommand.Name) : The API response received indicates a failure. $($response.StatusCode.value__) : $($response.StatusDescription) : Response Body: $($responseBody)"

      # Log the error with response detail.
      throw $ErrorString
    }
    else
    {
      # No response, log and throw the underlying ex
      $ErrorString = "$($MyInvocation.MyCommand.Name) : Exception occured calling invoke-restmethod. $($_.exception.tostring())"
      throw $_.exception.tostring()
    }
  }

  catch {
    # 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())"
    throw $ErrorString
  }


  Write-Debug "$(Get-Date -format s) Invoke-RestMethod Result: $response"

  # Workaround for bug in invoke-restmethod where it doesnt complete the tcp session close to our server after certain calls.
  # We end up with connectionlimit number of tcp sessions in close_wait and future calls die with a timeout failure.
  # So, we are getting and killing active sessions after each call. Not sure of performance impact as yet - to test
  # and probably rewrite over time to use invoke-webrequest for all calls... PiTA!!!! :|

  #$ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($FullURI)
  #$ServicePoint.CloseConnectionGroup("") | out-null

  # Return result
  $response
}

#####################################################################################################################
#####################################################################################################################
######################################## Connection Management #####################################################
#####################################################################################################################
#####################################################################################################################

function Connect-vRNIServer
{
  <#
  .SYNOPSIS
  Connects to the specified vRealize Network Insight Platform VM and
  constructs a connection object.
 
  .DESCRIPTION
  The Connect-vRNIServer cmdlet returns a connection object that contains
  an authentication token which the rest of the cmdlets in this module
  use to perform authenticated REST API calls.
 
  The connection object contains the authentication token, the expiry
  timestamp that the token expires and the vRNI server IP.
 
 
  .EXAMPLE
  PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local
 
  Connect to vRNI Platform VM with the hostname vrni-platform.lab.local,
  the cmdlet will prompt for credentials. Returns the connection object,
  if successful.
 
  .EXAMPLE
  PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local -Username admin@local -Password secret
 
  Connect to vRNI Platform VM with the hostname vrni-platform.lab.local
  with the given local credentials. Returns the connection object, if successful.
 
  .EXAMPLE
  PS C:\> Connect-vRNIServer -Server vrni-platform.lab.local -Username martijn@ld.local -Password secret -Domain ld.local
 
  Connect to vRNI Platform VM with the hostname vrni-platform.lab.local
  with the given LDAP credentials. Returns the connection object, if successful.
 
  .EXAMPLE
  PS C:\> $MyConnection = Connect-vRNIServer -Server vrni-platform.lab.local -Username admin@local -Password secret
  PS C:\> Get-vRNIDataSource -Connection $MyConnection
 
  Connects to vRNI with the given credentials and then uses the returned
  connection object in the next cmdlet to retrieve all datasources from
  that specific vRNI instance.
  #>

  param (
    [Parameter (Mandatory=$true)]
      # vRNI Platform hostname or IP address
      [ValidateNotNullOrEmpty()]
      [string]$Server,
    [Parameter (Mandatory=$false)]
      # Username to use to login to vRNI
      [ValidateNotNullOrEmpty()]
      [string]$Username,
    [Parameter (Mandatory=$false)]
      # Password to use to login to vRNI
      [ValidateNotNullOrEmpty()]
      [string]$Password,
    [Parameter (Mandatory=$false)]
      #PSCredential object containing NSX API authentication credentials
      [PSCredential]$Credential,
    [Parameter (Mandatory=$false)]
      # Domain to use to login to vRNI (if it's not given, use LOCAL)
      [ValidateNotNullOrEmpty()]
      [string]$Domain = "LOCAL"
  )
  
  # Make sure either -Credential is set, or both -Username and -Password
  if(($PsBoundParameters.ContainsKey("Credential")  -And $PsBoundParameters.ContainsKey("Username")) -Or
     ($PsBoundParameters.ContainsKey("Credential") -And $PsBoundParameters.ContainsKey("Password"))) 
  {
    throw "Specify either -Credential or -Username to authenticate (if using -Username and omitting -Password, a prompt will be given)"
  }

  # Build cred object for default auth if user specified username/pass
  $connection_credentials = ""
  if($PsBoundParameters.ContainsKey("Username")) 
  {
    # Is the -Password omitted? Prompt securely
    if(!$PsBoundParameters.ContainsKey("Password")) {
      $connection_credentials = Get-Credential -UserName $Username -Message "vRealize Network Insight Platform Authentication"
    }
    # If the password has been given in cleartext,
    else {
      $connection_credentials = New-Object System.Management.Automation.PSCredential($Username, $(ConvertTo-SecureString $Password -AsPlainText -Force))
    }
  }
  # If a credential object was given as a parameter, use that
  elseif($PSBoundParameters.ContainsKey("Credential")) 
  {
    $connection_credentials = $Credential
  }
  # If no -Username or -Credential was given, prompt for credentials
  elseif(!$PSBoundParameters.ContainsKey("Credential")) {
    $connection_credentials = Get-Credential -Message "vRealize Network Insight Platform Authentication"
  }

  # Start building the hash table containing the login call we need to do
  $requestFormat = @{
    "username" = $connection_credentials.Username
    "password" = $connection_credentials.GetNetworkCredential().Password
  }

  # If no domain param is given, use the default LOCAL domain and populate the "domain" field
  if($Domain -eq "LOCAL") {
    $requestFormat.domain = @{
      "domain_type" = "LOCAL"
      "value" = "local"
    }
  }
  # Otherwise there a LDAP domain requested for credentials
  else {
    $requestFormat.domain = @{
      "domain_type" = "LDAP"
      "value" = $Domain
    }
  }

  # Convert the hash to JSON and send the request to vRNI
  $requestBody = ConvertTo-Json $requestFormat
  $response = Invoke-vRNIRestMethod -Server $Server -Method POST -URI "/api/ni/auth/token" -Body $requestBody

  if($response)
  {
    # Setup a custom object to contain the parameters of the connection
    $connection = [pscustomObject] @{
      "Server" = $Server
      "AuthToken" = $response.token
      "AuthTokenExpiry" = $response.expiry
    }

    # Remember this as the default connection
    Set-Variable -name defaultvRNIConnection -value $connection -scope Global

    # Return the connection
    $connection
  }
}

function Disconnect-vRNIServer
{
  <#
  .SYNOPSIS
  Destroys the Connection object if provided, otherwise this destroys the
  $defaultvRNIConnection global variable if it exists.
 
  .DESCRIPTION
  Although REST is not connection-orientated, vRNI does remember the authentication
  token which is used throughout the session. This cmdlet also invalidates the
  authentication token from vRNI, so it can no longer be used.
 
  .EXAMPLE
  PS C:\> Disconnect-vRNIServer
 
  Invalidates and removes the global default connection variable.
 
  .EXAMPLE
  PS C:\> Disconnect-vRNIServer -Connection $MyConnection
 
  Invalidates the authentication token of a specific connection object
  #>

  param (
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Invalidate auth token from vRNI
  $result = Invoke-vRNIRestMethod -Connection $Connection -Method DELETE -URI "/api/ni/auth/token"

  # Remove the global default connection variable, if the -Connection parameter is the same as the default
  if ($Connection -eq $defaultvRNIConnection) {
    if (Get-Variable -Name defaultvRNIConnection -scope global) {
      Remove-Variable -name defaultvRNIConnection -scope global
    }
  }

  $result
}

#####################################################################################################################
#####################################################################################################################
####################################### Infrastructure Management ##################################################
#####################################################################################################################
#####################################################################################################################

function Get-vRNINodes
{
  <#
  .SYNOPSIS
  Retrieve details of the vRealize Network Insight nodes.
 
  .DESCRIPTION
  Nodes within a vRealize Network Insight typically consist of two
  node types; collector VMs (or previously know as proxy VMs) and
  platform VMs. You can have multiple of each type to support your
  deployment and cluster them.
 
  .EXAMPLE
 
  PS C:\> Get-vRNINodes
 
  Retrieves information about all available nodes.
 
  .EXAMPLE
 
  PS C:\> Get-vRNINodes | Where {$_.node_type -eq "PROXY_VM"}
 
  Retrieves information about all available nodes, but filter on the collector VMs.
  #>

  param (
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Get a list of available nodes first, this call returns a list of node IDs, which we can use
  # to retrieve more details on the specific node
  $nodes = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/infra/nodes"

  # Use this as a result container
  $nodes_details = [System.Collections.ArrayList]@()

  foreach($node_record in $nodes.results)
  {
    # Retrieve the node details and store those
    $node_info = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/infra/nodes/$($node_record.id)"
    $nodes_details.Add($node_info) | Out-Null
  }

  $nodes_details
}

function Get-vRNIAPIVersion
{
  <#
  .SYNOPSIS
  Retrieve the version number of the vRealize Network Insight API.
 
  .DESCRIPTION
  The API of vRealize Network Insight is versioned and this retrieves
  that version number.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIAPIVersion
 
  Returns the version number of the vRNI API.
  #>

  param (
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  $version = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/info/version"
  $version
}

#####################################################################################################################
#####################################################################################################################
######################################## Datasource Management #####################################################
#####################################################################################################################
#####################################################################################################################

function Get-vRNIDataSource
{
  <#
  .SYNOPSIS
  Retrieve datasource information
 
  .DESCRIPTION
  Datasources within vRealize Network Insight provide the data shown in
  the UI. The vRNI Collectors periodically polls the datasources as the
  source of truth. Typically you have a vCenter, NSX Manager and physical
  switches as the datasource.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource
 
  Retrieves the details of all datasource types.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource -DataSourceType nsxv
 
  Retrieves the defaults of all NSX Managers added to vRNI as a datasource.
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Which datasource type to get - TODO: make this a dynamic param to get the values from $Script:data
      [ValidateSet ("vcenter", "nsxv", "ciscoswitch", "aristaswitch", "dellswitch", "brocadeswitch", "juniperswitch", "ciscoucs", "hponeview", "hpvcmanager", "checkpointfirewall", "panfirewall", "all")]
      [string]$DataSourceType="all",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Use this as a return container
  $datasources = [System.Collections.ArrayList]@()

  # Because each datasource type has its unique URL (/api/ni/data-sources/vcenter, /data-sources/ucs-manager, etc),
  # and we want all the datasource information, loop through the URLs of the types we want to retrieve and
  $datasource_types_to_get = $Script:DatasourceURLs.$DataSourceType
  foreach($datasource_uri in $datasource_types_to_get)
  {
    # Energize!
    $response = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni$($datasource_uri)"

    # Process results, if there are datasources of this type. The results of the /api/ni/data-sources/$TYPE call is a
    # list of datasource IDs and not much more. We take that ID and do a call for details on that datasource
    if($response.results -ne "")
    {
      foreach ($datasource in $response.results)
      {
        # Retrieve datasource details and store it
        $datasource_detail = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni$($datasource_uri)/$($datasource.entity_id)"
        $datasources.Add($datasource_detail) | Out-Null
      }
    }
  }

  # Return all found data sources
  $datasources
}

function New-vRNIDataSource
{
  <#
  .SYNOPSIS
  Create new datasources within vRealize Network Insight to retrieve data from.
 
  .DESCRIPTION
  Datasources within vRealize Network Insight provide the data shown in
  the UI. The vRNI Collectors periodically polls the datasources as the
  source of truth. Typically you have a vCenter, NSX Manager and physical
  switches as the datasource.
 
  This cmdlet adds new datasources to vRNI, so it can retrieve data from it and
  correlate and display this data in the interfce.
 
  .EXAMPLE
 
  PS C:\> $collectorId = (Get-vRNINodes | Where {$_.node_type -eq "PROXY_VM"} | Select -ExpandProperty id)
  PS C:\> New-vRNIDataSource -DataSourceType vcenter -FDQN vc.nsx.local -Username administrator@vsphere.local -Password secret -CollectorVMId $collectorId -Nickname vc.nsx.local
 
  First, get the node ID of the collector VM (assuming there's only one), then
  add a vCenter located at vc.nsx.local to vRNI.
 
  .EXAMPLE
 
  PS C:\> $collectorId = (Get-vRNINodes | Where {$_.node_type -eq "PROXY_VM"} | Select -ExpandProperty id)
  PS C:\> $vcId = (Get-vRNIDataSource | Where {$_.nickname -eq "vc.nsx.local"} | Select -ExpandProperty entity_id)
  PS C:\> New-vRNIDataSource -DataSourceType nsxv -FDQN mgr.nsx.local -Username admin -Password secret -Nickname mgr.nsx.local -CollectorVMId $collectorId -Enabled $True -NSXEnableCentralCLI $True -NSXEnableIPFIX $True -NSXvCenterID $vcId
 
  Adds a new NSX Manager as a data source, auto select the collector ID (if
  you only have one), enable the NSX Central CLI for collecting data,
  also enable NSX IPFIX for network datastream insight from the point of view
  of NSX.
  #>


  [CmdletBinding(DefaultParameterSetName="__AllParameterSets")]

  param (
    [Parameter (Mandatory=$true)]
      # Which datasource type to create - TODO: make this a dynamic param to get the values from $Script:data
      [ValidateSet ("vcenter", "nsxv", "ciscoswitch", "aristaswitch", "dellswitch", "brocadeswitch", "juniperswitch", "ciscoucs", "hponeview", "hpvcmanager", "checkpointfirewall", "panfirewall")]
      [string]$DataSourceType,
    [Parameter (Mandatory=$true)]
      # Username to use to login to the datasource
      [ValidateNotNullOrEmpty()]
      [string]$Username,
    [Parameter (Mandatory=$true)]
      # Password to use to login to the datasource
      [ValidateNotNullOrEmpty()]
      [string]$Password,

    [Parameter (Mandatory=$false)]
      # The IP address of the datasource
      [ValidateNotNullOrEmpty()]
      [string]$IP,
    [Parameter (Mandatory=$false)]
      # The FDQN address of the datasource
      [ValidateNotNullOrEmpty()]
      [string]$FDQN,

    [Parameter (Mandatory=$true)]
      # Collector (Proxy) Node ID
      [ValidateNotNullOrEmpty()]
      [string]$CollectorVMId,

    [Parameter (Mandatory=$true)]
      # Nickname for the datasource
      [ValidateNotNullOrEmpty()]
      [string]$Nickname="",

    [Parameter (Mandatory=$false)]
      # Whether we want to enable the datasource
      [ValidateNotNullOrEmpty()]
      [bool]$Enabled=$True,
    [Parameter (Mandatory=$false)]
      # Optional notes for the datasource
      [ValidateNotNullOrEmpty()]
      [string]$Notes="",

    # These params are only required when adding a NSX Manager as datasource
    [Parameter (Mandatory=$true, ParameterSetName="NSXDS")]
      # Enable the central CLI collection
      [ValidateNotNullOrEmpty()]
      [bool]$NSXEnableCentralCLI,

    [Parameter (Mandatory=$true, ParameterSetName="NSXDS")]
      # Enable NSX IPFIX as a source
      [ValidateNotNullOrEmpty()]
      [bool]$NSXEnableIPFIX,

    [Parameter (Mandatory=$true, ParameterSetName="NSXDS")]
      # vCenter ID that this NSX Manager will be linked too
      [ValidateNotNullOrEmpty()]
      [string]$NSXvCenterID,

    # This params is only required when adding a cisco switch
    [Parameter (Mandatory=$true, ParameterSetName="CISCOSWITCH")]
      # Set the switch type
      [ValidateSet ("CATALYST_3000", "CATALYST_4500", "CATALYST_6500", "NEXUS_5K", "NEXUS_7K", "NEXUS_9K")]
      [string]$CiscoSwitchType,

    # This params is only required when adding a dell switch
    [Parameter (Mandatory=$true, ParameterSetName="DELLSWITCH")]
      # Set the switch type
      [ValidateSet ("FORCE_10_MXL_10", "POWERCONNECT_8024", "S4048", "Z9100", "S6000")]
      [string]$DellSwitchType,

    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  if($IP -ne "" -And $FDQN -ne "") {
    throw "Please only provide the FDQN or the IP address for the datasource, not both."
  }

  # Check if the NSXDS parameter set is used when adding a NSX Manager as datasource
  if($DataSourceType -eq "nsxv" -And $PSCmdlet.ParameterSetName -ne "NSXDS") {
    throw "Please provide the NSX parameters when adding a NSX Manager."
  }

  # Check if the switch type is provided, when adding a Cisco of Dell switch
  if($DataSourceType -eq "ciscoswitch" -And $PSCmdlet.ParameterSetName -ne "CISCOSWITCH") {
    throw "Please provide the -CiscoSwitchType parameter when adding a Cisco switch."
  }
  if($DataSourceType -eq "dellswitch" -And $PSCmdlet.ParameterSetName -ne "DELLSWITCH") {
    throw "Please provide the -DellSwitchType parameter when adding a Dell switch."
  }

  # Format request with all given data
  $requestFormat = @{
    "ip" = $IP
    "fqdn" = $FDQN
    "proxy_id" = $CollectorVMId
    "nickname" = $Nickname
    "notes" = $Notes
    "enabled" = $Enabled
    "credentials" = @{
      "username" = $Username
      "password" = $Password
    }
  }

  # If we're adding a NSX Manager, also add the NSX parameters to the body
  if($PSCmdlet.ParameterSetName -eq "NSXDS") {
    $requestFormat.vcenter_id = $NSXvCenterID
    $requestFormat.ipfix_enabled = $NSXEnableIPFIX
    $requestFormat.central_cli_enabled = $NSXEnableCentralCLI
  }

  # Convert the hash to JSON, form the URI and send the request to vRNI
  $requestBody = ConvertTo-Json $requestFormat
  $URI = "/api/ni$($Script:DatasourceURLs.$DataSourceType[0])"

  $response = Invoke-vRNIRestMethod -Connection $Connection -Method POST -Uri $URI -Body $requestBody
  $response
}

function Remove-vRNIDataSource
{
  <#
  .SYNOPSIS
  Removes a datasource from vRealize Network Insight
 
  .DESCRIPTION
  Datasources within vRealize Network Insight provide the data shown in
  the UI. The vRNI Collectors periodically polls the datasources as the
  source of truth. Typically you have a vCenter, NSX Manager and physical
  switches as the datasource.
 
  This cmdlet removes a datasources from vRNI.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource | Where {$_.nickname -eq "vc.nsx.local"} | Remove-vRNIDataSource
 
  Removes a vCenter datasource with the nickname "vc.nsx.local"
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource | Where {$_.nickname -eq "manager.nsx.local"} | Remove-vRNIDataSource
 
  Removes a NSX Manager datasource with the nickname "manager.nsx.local"
 
  #>


  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1)]
      # Datasource object, gotten from Get-vRNIDataSource
      [ValidateNotNullOrEmpty()]
      [PSObject]$DataSource,

    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )


  # All we have to do is to send a DELETE request to URI /api/ni/$DataSourceType/$DatasourceId, so
  # form the URI and send the DELETE request to vRNI
  $URI = "/api/ni$($Script:DatasourceInternalURLs.$($DataSource.entity_type))/$($DataSource.entity_id)"

  $response = Invoke-vRNIRestMethod -Connection $Connection -Method DELETE -Uri $URI
  $response
}

function Enable-vRNIDataSource
{
  <#
  .SYNOPSIS
  Enables an existing datasources within vRealize Network Insight
 
  .DESCRIPTION
  Datasources within vRealize Network Insight provide the data shown in
  the UI. The vRNI Collectors periodically polls the datasources as the
  source of truth. Typically you have a vCenter, NSX Manager and physical
  switches as the datasource.
 
  This cmdlet enables an existing datasources within vRNI.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource | Where {$_.nickname -eq "vc.nsx.local"} | Enable-vRNIDataSource
 
  Enables a vCenter datasource with the nickname "vc.nsx.local"
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource | Where {$_.nickname -eq "manager.nsx.local"} | Enable-vRNIDataSource
 
  Enables a NSX Manager datasource with the nickname "manager.nsx.local"
 
  #>


  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1)]
      # Datasource object, gotten from Get-vRNIDataSource
      [ValidateNotNullOrEmpty()]
      [PSObject]$DataSource,

    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )


  # All we have to do is to send a POST request to URI /api/ni/$DataSourceType/$DatasourceId/enable, so
  # form the URI and send the request to vRNI
  $URI = "/api/ni$($Script:DatasourceInternalURLs.$($DataSource.entity_type))/$($DataSource.entity_id)/enable"

  $response = Invoke-vRNIRestMethod -Connection $Connection -Method POST -Uri $URI
  $response
}

function Disable-vRNIDataSource
{
  <#
  .SYNOPSIS
  Disables an existing datasources within vRealize Network Insight
 
  .DESCRIPTION
  Datasources within vRealize Network Insight provide the data shown in
  the UI. The vRNI Collectors periodically polls the datasources as the
  source of truth. Typically you have a vCenter, NSX Manager and physical
  switches as the datasource.
 
  This cmdlet disables an existing datasources within vRNI.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource | Where {$_.nickname -eq "vc.nsx.local"} | Disable-vRNIDataSource
 
  Disables a vCenter datasource with the nickname "vc.nsx.local"
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDataSource | Where {$_.nickname -eq "manager.nsx.local"} | Disable-vRNIDataSource
 
  Disables a NSX Manager datasource with the nickname "manager.nsx.local"
 
  #>


  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1)]
      # Datasource object, gotten from Get-vRNIDataSource
      [ValidateNotNullOrEmpty()]
      [PSObject]$DataSource,

    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )


  # All we have to do is to send a POST request to URI /api/ni/$DataSourceType/$DatasourceId/disable, so
  # form the URI and send the request to vRNI
  $URI = "/api/ni$($Script:DatasourceInternalURLs.$($DataSource.entity_type))/$($DataSource.entity_id)/disable"

  $response = Invoke-vRNIRestMethod -Connection $Connection -Method POST -Uri $URI
  $response
}

#####################################################################################################################
#####################################################################################################################
####################################### Application Management #####################################################
#####################################################################################################################
#####################################################################################################################

function Get-vRNIApplication
{
  <#
  .SYNOPSIS
  Get Application information from vRealize Network Insight.
 
  .DESCRIPTION
  Within vRNI there are applications, which can be viewed as groups of VMs.
  These groups can be used to group the VMs of a certain application together,
  and filter on searches within vRNI. For instance, you can generate recommended
  firewall rules based on an application group.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIApplication
 
  Show all existing applications and their details.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIApplication | Where {$_.name -eq "3 Tier App"}
 
  Get only the application details of the application named "3 Tier App"
  #>

  param (
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned to a specific name
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # First, get a list of all applications. This returns a list with application IDs which we can use
  # to retrieve the details of the applications
  $application_list = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/groups/applications"

  # Use this as a results container
  $applications = [System.Collections.ArrayList]@()

  foreach($app in $application_list.results)
  {
    # Retrieve application details and store them
    $app_info = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/groups/applications/$($app.entity_id)"
    $applications.Add($app_info) | Out-Null

    # Don't go on if we've already found the one the user wants specifically
    if($Name -eq $app_info.name) {
      break
    }
  }

  # Filter out other applications if the user wants one specifically
  if ($Name) {
    $applications | Where-Object { $_.name -eq $Name }
  } 
  else {
    $applications
  }
}

function Get-vRNIApplicationTier
{
  <#
  .SYNOPSIS
  Get Application Tier information from vRealize Network Insight.
 
  .DESCRIPTION
  Within vRNI there are applications, which can be viewed as groups of VMs.
  These groups can be used to group the VMs of a certain application together,
  and filter on searches within vRNI. For instance, you can generate recommended
  firewall rules based on an application group.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIApplication My3TierApp | Get-vRNIApplicationTier
 
  Show the tiers for the application container called "My3TierApp"
  #>

  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true)]
      # Application object, gotten from Get-vRNIApplication
      [ValidateNotNullOrEmpty()]
      [PSObject]$Application,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned to a specific name
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # First, get a list of all tier. This returns a list with application IDs which we can use
  # to retrieve the details of the applications
  $tier_list = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/groups/applications/$($Application.entity_id)/tiers"

  # Use this as a results container
  $tiers = [System.Collections.ArrayList]@()

  foreach($tier in $tier_list.results)
  {
    # Retrieve application details and store them
    $tier_info = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/groups/applications/$($Application.entity_id)/tiers/$($tier.entity_id)"
    $tiers.Add($tier_info) | Out-Null

    # Don't go on if we've already found the one the user wants specifically
    if($Name -eq $tier_info.name) {
      break
    }
  }

  # Filter out other application tiers if the user wants one specifically
  if ($Name) {
    $tiers | Where-Object { $_.name -eq $Name }
  } 
  else {
    $tiers
  }
}

function New-vRNIApplicationTier
{
  <#
  .SYNOPSIS
  Create a Tier in an Application container in vRealize Network Insight.
 
  .DESCRIPTION
  Within vRNI there are applications, which can be viewed as groups of VMs.
  These groups can be used to group the VMs of a certain application together,
  and filter on searches within vRNI. For instance, you can generate recommended
  firewall rules based on an application group.
 
 
  .EXAMPLE
 
  PS C:\> Get-vRNIApplication My3TierApp | New-vRNIApplicationTier -Name web-tier -Filters ("name = '3TA-Web01' or name = '3TA-Web02'")
 
  Create a new tier in the application 'My3TierApp' called 'web-tier' and assign the
  VMs named '3TA-Web01' and '3TA-Web02' to this tier.
 
  .EXAMPLE
 
  PS C:\> $security_group_id = (Get-vRNISecurityGroup SG-3Tier-App).entity_id
  PS C:\> Get-vRNIApplication My3TierApp | New-vRNIApplicationTier -Name app-tier -Filters ("name = '3TA-App01'", "security_groups.entity_id = '$security_group_id'")
 
  Create a new tier in the application 'My3TierApp' called 'web-tier' and assign the
  VMs named '3TA-Web01' and '3TA-Web02' to this tier.
 
  .PARAMETER Filters
 
  The filters within an application tier determine what VMs will be placed in that
  application. Currently, only these options are supported:
 
  Single VM: "name = '3TA-App01'"
  Multiple VMs: "name = '3TA-App01' or name = '3TA-App02'"
  VMs with a NSX Security Tag: "security_groups.entity_id = '18230:82:604573173'"
 
  #>

  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true)]
      # Application object, gotten from Get-vRNIApplication
      [ValidateNotNullOrEmpty()]
      [PSObject]$Application,
    [Parameter (Mandatory=$true)]
      # The name of the new tier
      [string]$Name,
    [Parameter (Mandatory=$true)]
      # The VM filters in the new tier
      [string[]]$Filters,
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Format request with all given data
  $requestFormat = @{
    "name" = $Name
    "group_membership_criteria" = @()
  }

  # TODO: also allow custom searches based on entity_type VirtualMachine
  foreach($filter in $Filters)
  {
    $criteria_record = @{}
    $criteria_record.membership_type = "SearchMembershipCriteria"
    $criteria_record.search_membership_criteria = @{
      "entity_type" = "BaseVirtualMachine"
      "filter" = $filter
    }
    $requestFormat.group_membership_criteria += $criteria_record
  }

  Write-Debug $requestFormat

  # Convert the hash to JSON, form the URI and send the request to vRNI
  $requestBody = ConvertTo-Json $requestFormat -Depth 5
  $result = Invoke-vRNIRestMethod -Connection $Connection -Method POST -URI "/api/ni/groups/applications/$($Application.entity_id)/tiers" -Body $requestBody

  $result

}


function Remove-vRNIApplicationTier
{
  <#
  .SYNOPSIS
  Remove a tier from an application container from vRealize Network Insight.
 
  .DESCRIPTION
  Within vRNI there are applications, which can be viewed as groups of VMs.
  These groups can be used to group the VMs of a certain application together,
  and filter on searches within vRNI. For instance, you can generate recommended
  firewall rules based on an application group.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIApplication My3TierApp | Get-vRNIApplicationTier web-tier | Remove-vRNIApplicationTier
 
  Remove the tier 'web-tier' from the application container called "My3TierApp"
  #>

  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1)]
      # Application Tier object, gotten from Get-vRNIApplicationTier
      [ValidateNotNullOrEmpty()]
      [PSObject]$ApplicationTier,
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Send the DELETE request and show the result
  $result = Invoke-vRNIRestMethod -Connection $Connection -Method DELETE -URI "/api/ni/groups/applications/$($ApplicationTier.application.entity_id)/tiers/$($ApplicationTier.entity_id)"

  $result
}

function New-vRNIApplication
{
  <#
  .SYNOPSIS
  Create a new Application container inside vRealize Network Insight.
 
  .DESCRIPTION
  Within vRNI there are applications, which can be viewed as groups of VMs.
  These groups can be used to group the VMs of a certain application together,
  and filter on searches within vRNI. For instance, you can generate recommended
  firewall rules based on an application group.
 
  .EXAMPLE
 
  PS C:\> New-vRNIApplication -Name My3TierApp
 
  Create a new application container with the name My3TierApp.
 
  #>

  param (
    [Parameter (Mandatory=$false, Position=1)]
      # Give the application a name
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Format request with all given data
  $requestFormat = @{
    "name" = $Name
  }

  # Convert the hash to JSON, form the URI and send the request to vRNI
  $requestBody = ConvertTo-Json $requestFormat
  $response = Invoke-vRNIRestMethod -Connection $Connection -Method POST -Uri "/api/ni/groups/applications" -Body $requestBody

  $response
}


function Remove-vRNIApplication
{
  <#
  .SYNOPSIS
  Remove an Application container from vRealize Network Insight.
 
  .DESCRIPTION
  Within vRNI there are applications, which can be viewed as groups of VMs.
  These groups can be used to group the VMs of a certain application together,
  and filter on searches within vRNI. For instance, you can generate recommended
  firewall rules based on an application group.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIApplication My3TierApp | Remove-vRNIApplication
 
  Remove the application container called "My3TierApp"
  #>

  param (
    [Parameter (Mandatory=$true, ValueFromPipeline=$true, Position=1)]
      # Application object, gotten from Get-vRNIApplication
      [ValidateNotNullOrEmpty()]
      [PSObject]$Application,
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Send the DELETE request and show the result
  $result = Invoke-vRNIRestMethod -Connection $Connection -Method DELETE -URI "/api/ni/groups/applications/$($Application.entity_id)"

  $result
}

#####################################################################################################################
#####################################################################################################################
######################################### Entity Management ########################################################
#####################################################################################################################
#####################################################################################################################

function Get-vRNIEntity
{
  <#
  .SYNOPSIS
  Get available entities from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all kinds of entities inside
  the monitored infrastructure. This is a catch-all function to retrieve
  any entity and the objects related to that entity.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIEntity -Entity_URI "security-groups"
 
  Get all security groups in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIEntity -Entity_URI "hosts" -Name "esxi01.lab"
 
  Get the entity object for the hypervisor host called "esxi01.lab"
 
  #>

  param (
    [Parameter (Mandatory=$true)]
      # Limit the amount of records returned
      [string]$Entity_URI,
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$false, ParameterSetName="TIMELIMIT")]
      # The epoch timestamp of when to start looking up records
      [int]$StartTime = 0,
    [Parameter (Mandatory=$false, ParameterSetName="TIMELIMIT")]
      # The epoch timestamp of when to stop looking up records
      [int]$EndTime = 0,
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Use this as a results container
  $entities = [System.Collections.ArrayList]@()

  # vRNI uses a paging system with (by default) 10 items per page. These vars are to keep track of the pages and retrieve what's left
  $size = 10
  $total_count = 0
  $current_count = 0
  $cursor = ""
  $finished = $false

  while(!$finished)
  {
    $using_params = 0
    # This is the base URI for the problems
    $URI = "/api/ni/entities/$($Entity_URI)"
    if($size -gt 0 -And $cursor -ne "") {
      $URI += "?size=$($size)&cursor=$($cursor)"
      $using_params++
    }

    # Check if we want to limit the results to a time window
    if($PSCmdlet.ParameterSetName -eq "TIMELIMIT" -And ($StartTime -gt 0 -And $EndTime -gt 0)) {
      if($using_params -gt 0) {
        $URI += "&start_time=$($StartTime)&end_time=$($EndTime)"
        $using_params++
      }
      else {
        $URI += "?start_time=$($StartTime)&end_time=$($EndTime)"
        $using_params++
      }
    }

    Write-Debug "Using URI: $($URI)"

    # Get a list of all entities
    $entity_list = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI $URI

    # If we're not finished, store information about the run for next use
    if($finished -eq $false)
    {
      $total_count = $entity_list.total_count
      $cursor      = $entity_list.cursor
    }

    # If the size is smaller than 10 (decreased by previous run), or the size is greater than the total records, finish up
    if($size -lt 10 -Or ($total_count -gt 0 -And $size -gt $total_count)) {
      $finished = $true
    }
  
    # Go through the entities individually and store them in the results array
    foreach($sg in $entity_list.results)
    {
      # Retrieve entity details and store them
      $entity_info = Invoke-vRNIRestMethod -Connection $Connection -Method GET -URI "/api/ni/entities/$($Entity_URI)/$($sg.entity_id)?time=$($sg.time)"

      # If we're retrieving flows, add the time of the main flow to this specific flow record
      if($Entity_URI -eq "flows") {
        $entity_info | Add-Member -Name "time" -value $entity_info.time -MemberType NoteProperty
      }

      $entities.Add($entity_info) | Out-Null

      if($Name -eq $entity_info.name) {
        $finished = true
        break
      }
      # Don't overload the API, pause a bit
      Start-Sleep -m 100

      $current_count++
      
      # If we are limiting the output, break from the loops and return results
      if($Limit -ne 0 -And ($Limit -lt $current_count -Or $Limit -eq $current_count)) {
        $finished = $true
        break
      }
    }
    # Check remaining items, if it's less than the default size, reduce the next page size
    if($size -gt ($total_count - $current_count)) {
      $size = ($total_count - $current_count)
    }
    
  }

  if ($Name) {
    $entities | Where-Object { $_.name -eq $Name }
  } 
  else {
    $entities
  }
}

function Get-vRNIProblem
{
  <#
  .SYNOPSIS
  Get open problems from vRealize Network Insight.
 
  .DESCRIPTION
  vRNI checks for problems in your environment and displays or alerts you
  about these problems. These problems can have multiple causes; for example
  latency issues with NSX Controllers, a configuration issue on the VDS, etc.
  In the end you're supposed to solve these problems and have no open ones.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIProblem
 
  Get a list of all open problems
 
  .EXAMPLE
 
  PS C:\> Get-vRNIProblem | Where {$_.severity -eq "CRITICAL"}
 
  Get a list of all open problems which have the CRITICAL severity (and are
  probably important to solve quickly)
 
  .EXAMPLE
 
  PS C:\> Get-vRNIProblem -StartTime ([DateTimeOffset]::Now.ToUnixTimeSeconds()-600) -EndTime ([DateTimeOffset]::Now.ToUnixTimeSeconds())
 
  Get all problems that have been open in the last 10 minutes.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, ParameterSetName="TIMELIMIT")]
      # The epoch timestamp of when to start looking up records
      [int]$StartTime = 0,
    [Parameter (Mandatory=$false, ParameterSetName="TIMELIMIT")]
      # The epoch timestamp of when to stop looking up records
      [int]$EndTime = 0,
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "problems" -Limit $Limit -StartTime $StartTime -EndTime $EndTime
  $results
}


function Get-vRNIFlow
{
  <#
  .SYNOPSIS
  Get network flows from vRealize Network Insight.
 
  .DESCRIPTION
  vRNI can consume NetFlow and IPFIX data from the vSphere Distributed
  Switch and physical switches which support NetFlow v5, v7, v9 or IPFIX.
  This cmdlet will let you export these flows
 
  .EXAMPLE
 
  PS C:\> Get-vRNIFlow
 
  Get the last 100 flows (100 = default)
 
  .EXAMPLE
 
  PS C:\> Get-vRNIFlow -Limit 10
 
  Get the last 10 flows
 
  .EXAMPLE
 
  PS C:\> Get-vRNIFlow -StartTime ([DateTimeOffset]::Now.ToUnixTimeSeconds()-600) -EndTime ([DateTimeOffset]::Now.ToUnixTimeSeconds())
 
  Get all flows that occurred in the last 10 minutes.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIFlow -StartTime ([DateTimeOffset]::Now.ToUnixTimeSeconds()-600) -EndTime ([DateTimeOffset]::Now.ToUnixTimeSeconds()) | Where {$_.protocol -eq "TCP"}
 
  Get all flows that occurred in the last 10 minutes and ignore all flows
  that are not TCP based.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIFlow -StartTime ([DateTimeOffset]::Now.ToUnixTimeSeconds()-600) -EndTime ([DateTimeOffset]::Now.ToUnixTimeSeconds()) | Where {$_.traffic_type -eq "INTERNET_TRAFFIC"}
 
  Get only internet-based (in or out) flows that occurred in the last 10 minutes.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 100,
    [Parameter (Mandatory=$false, ParameterSetName="TIMELIMIT")]
      # The epoch timestamp of when to start looking up records
      [int]$StartTime = 0,
    [Parameter (Mandatory=$false, ParameterSetName="TIMELIMIT")]
      # The epoch timestamp of when to stop looking up records
      [int]$EndTime = 0,
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # If we want to select flows in a time slot, make sure the end time is later then the start time
  if($PSCmdlet.ParameterSetName -eq "TIMELIMIT") {
    if($StartTime -gt $EndTime) {
      throw "Param StartTime cannot be greater than EndTime"
    }
  }

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "flows" -Limit $Limit -StartTime $StartTime -EndTime $EndTime
  $results
}

#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------- VM Entities ---------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#

function Get-vRNIVM
{
  <#
  .SYNOPSIS
  Get virtual machines from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all VMs in your environment
  and this cmdlet will help you discover these VMs.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIVM
 
  List all VMs in your vRNI environment (note: this may take a while if you
  have a lot of VMs)
 
  .EXAMPLE
 
  PS C:\> Get-vRNIVM -Name my-vm-name
 
  Retrieve only the VM object called "my-vm-name"
 
  .EXAMPLE
 
  PS C:\> $vcenter_entity_id = (Get-vRNIvCenter | Where {$_.name -eq "vcenter.lab"}).entity_id
  PS C:\> Get-vRNIVM | Where {$_.vcenter_manager.entity_id -eq $vcenter_entity_id}
 
  Get all VMs that are attached to the vCenter named "vcenter.lab"
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "vms" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIVMvNIC
{
  <#
  .SYNOPSIS
  Get virtual machine vnics from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all VM vNICs in your environment
  and this cmdlet will help you discover these VM vNICs.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIVMvNIC
 
  List all VM vNICs in your vRNI environment (note: this may take a while if you
  have a lot of VMs)
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "vnics" -Name $Name -Limit $Limit
  $results
}

#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#--------------------------------------- vCenter Entities -------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#

function Get-vRNIvCenter
{
  <#
  .SYNOPSIS
  Get configured vCenter instances from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all vCenters in your environment
  and this cmdlet will help you discover these vCenters.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIvCenter
 
  Get all vCenters in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIvCenter vcenter.lab
 
  Retrieve the vCenter object for the one called "vcenter.lab"
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "vcenter-managers" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIvCenterFolder
{
  <#
  .SYNOPSIS
  Get available vCenter folders from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all vCenter folders in your environment
  and this cmdlet will help you discover these folders.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIvCenterFolder
 
  Get all vCenter folders in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "folders" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIvCenterDatacenter
{
  <#
  .SYNOPSIS
  Get available vCenter Datacenters from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all vCenter Datacenters in your
  environment and this cmdlet will help you discover these Datacenters.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIvCenterDatacenter
 
  Get all vCenter Datacenters in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "vc-datacenters" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIvCenterCluster
{
  <#
  .SYNOPSIS
  Get available vCenter Clusters from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all vCenter Clusters in your
  environment and this cmdlet will help you discover these Clusters.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIvCenterCluster
 
  Get all vCenter Clusters in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "clusters" -Name $Name -Limit $Limit
  $results
}

#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#-------------------------------------- ESXi host Entities ------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
function Get-vRNIHost
{
  <#
  .SYNOPSIS
  Get available hypervisor hosts from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all hosts in your environment
  and this cmdlet will help you discover these hosts.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIHost
 
  Get all hypervisor hosts in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIHost esxi01.lab
 
  Retrieve the ESXi host object for the one called "esxi01.lab"
 
  .EXAMPLE
 
  PS C:\> Get-vRNIHost | Select name, service_tag
 
  Get a list of all hosts with their hardware service tag.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIHost | Where {$_.nsx_manager -ne ""}
 
  Get all hosts that are managed by a NSX Manager.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "hosts" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIHostVMKNic
{
  <#
  .SYNOPSIS
  Get available host vmknics from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all host vmknics in your
  environment and this cmdlet will help you discover these vmknids.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIHostVMKNic
 
  Get all host vmknics in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "vmknics" -Name $Name -Limit $Limit
  $results
}

#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#------------------------------------------- NSX Entities -------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#

function Get-vRNISecurityGroup
{
  <#
  .SYNOPSIS
  Get available security groups (SG) from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all SGs in your environment
  and this cmdlet will help you discover these SGs.
 
  .EXAMPLE
 
  PS C:\> Get-vRNISecurityGroup
 
  Get all security groups in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNISecurityGroup 3TA-Management-Access
 
  Retrieve the security group object for the one called "3TA-Management-Access"
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "security-groups" -Name $Name -Limit $Limit
  $results
}

function Get-vRNISecurityTag
{
  <#
  .SYNOPSIS
  Get available security tags (ST) from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all STs in your environment
  and this cmdlet will help you discover these STs.
 
  .EXAMPLE
 
  PS C:\> Get-vRNISecurityTag
 
  Get all security tags in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNISecurityTag ST-3TA-Management
 
  Retrieve the security tag object for the one called "ST-3TA-Management"
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "security-tags" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIIPSet
{
  <#
  .SYNOPSIS
  Get available NSX IP Sets from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all NSX IP Sets in your environment
  and this cmdlet will help you discover these IP sets.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIIPSet
 
  Get all IP Sets in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "ip-sets" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIService
{
  <#
  .SYNOPSIS
  Get available NSX Services from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all NSX Services in your environment
  and this cmdlet will help you discover these Services.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIService
 
  Get all NSX Services in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "services" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIServiceGroup
{
  <#
  .SYNOPSIS
  Get available NSX Service Groups from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all NSX Service Groups in your environment
  and this cmdlet will help you discover these groups.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIServiceGroup
 
  Get all NSX Service Groups in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "service-groups" -Name $Name -Limit $Limit
  $results
}

function Get-vRNINSXManager
{
  <#
  .SYNOPSIS
  Get available NSX Managers from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all NSX Managers in your environment
  and this cmdlet will help you discover these NSX Managers.
 
  .EXAMPLE
 
  PS C:\> Get-vRNINSXManager
 
  Get all NSX Managers in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "nsx-managers" -Name $Name -Limit $Limit
  $results
}

#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#---------------------------------------- Networking Entities ---------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#

function Get-vRNIFirewallRule
{
  <#
  .SYNOPSIS
  Get available firewall rules from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all firewall rules in your environment
  and this cmdlet will help you discover these rules.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIFirewallRule
 
  Get all firewall rules in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "firewall-rules" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIL2Network
{
  <#
  .SYNOPSIS
  Get available layer 2 networks from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all networks in your environment
  and this cmdlet will help you discover these layer 2 networks.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIL2Network
 
  Get all layer 2 networks in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIL2Network | Where {$_.entity_type -eq "VxlanLayer2Network"}
 
  Only show all VXLAN layer 2 networks.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "layer2-networks" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIDistributedSwitch
{
  <#
  .SYNOPSIS
  Get available vSphere Distributed Switches from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all VDSes in your environment
  and this cmdlet will help you discover these VDSes.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDistributedSwitch
 
  Get all vSphere Distributed Switches in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDistributedSwitch LabSwitch
 
  Get only the VDS called 'LabSwitch'
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "distributed-virtual-switches" -Name $Name -Limit $Limit
  $results
}

function Get-vRNIDistributedSwitchPortGroup
{
  <#
  .SYNOPSIS
  Get available VDS Portgroups from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all VDS Portgroups in your environment
  and this cmdlet will help you discover these portgroups.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDistributedSwitchPortGroup
 
  Get all VDS Portgroups in the vRNI environment.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDistributedSwitchPortGroup Web-Tier
 
  Get only the portgroup called 'Web-Tier'
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "distributed-virtual-portgroups" -Name $Name -Limit $Limit
  $results
}

#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------- Storage Entities -----------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------------#

function Get-vRNIDatastore
{
  <#
  .SYNOPSIS
  Get available datastores from vRealize Network Insight.
 
  .DESCRIPTION
  vRealize Network Insight has a database of all datastores in your environment
  and this cmdlet will help you discover these datastores.
 
  .EXAMPLE
 
  PS C:\> Get-vRNIDatastore
 
  Get all datastores in the vRNI environment.
 
  #>

  param (
    [Parameter (Mandatory=$false)]
      # Limit the amount of records returned
      [int]$Limit = 0,
    [Parameter (Mandatory=$false, Position=1)]
      # Limit the amount of records returned
      [string]$Name = "",
    [Parameter (Mandatory=$False)]
      # vRNI Connection object
      [ValidateNotNullOrEmpty()]
      [PSCustomObject]$Connection=$defaultvRNIConnection
  )

  # Call Get-vRNIEntity with the proper URI to get the entity results
  $results = Get-vRNIEntity -Entity_URI "datastores" -Name $Name -Limit $Limit
  $results
}

# Call Init function
_PvRNI_init