NavContainerHelper.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
Set-StrictMode -Version 2.0

$verbosePreference = "SilentlyContinue"
$warningPreference = "SilentlyContinue"
$errorActionPreference = 'Stop'

$demoFolder = "C:\DEMO"
New-Item -Path $demoFolder -ItemType Container -Force -ErrorAction Ignore
$extensionsFolder = Join-Path $demoFolder "Extensions"
New-Item -Path $extensionsFolder -ItemType Container -Force -ErrorAction Ignore

$containerDemoFolder = "C:\DEMO"

$sessions = @{}

#region Internal helper functions

function Log([string]$line, [string]$color = "Gray") { 
    Write-Host -ForegroundColor $color $line
}

function Get-DefaultAdminPassword {
    if (Test-Path "$demoFolder\settings.ps1") {
        . "$demoFolder\settings.ps1"
        if (Test-Path "$demoFolder\aes.key") {
            $key = Get-Content -Path "$demoFolder\aes.key"
            ConvertTo-SecureString -String $adminPassword -Key $key
        } else {
            ConvertTo-SecureString -String $adminPassword
        }
    } else {
        Read-Host -Prompt "Please enter the admin password for the Nav Container" -AsSecureString
    }
}

function Get-DefaultVmAdminUsername {
    if (Test-Path "$demoFolder\settings.ps1") {
        . "$demoFolder\settings.ps1"
        $vmAdminUsername
    } else {
        "$env:USERNAME"
    }
}

function DockerRun {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$imageName,
        [switch]$accept_eula,
        [switch]$accept_outdated,
        [switch]$wait,
        [string[]]$parameters
    )

    if ($accept_eula) {
        $parameters += "--env accept_eula=Y"
    }
    if ($accept_outdated) {
        $parameters += "--env accept_outdated=Y"
    }
    if (!$wait) {
        $parameters += "--detach"
    }
    $parameters += $imageName

    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = "docker.exe"
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = ("run "+[string]::Join(" ", $parameters))
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $output = $p.StandardOutput.ReadToEnd()
    $output += $p.StandardError.ReadToEnd()
    $output
}

function Get-NavContainerAuth {
    Param
    (
        [string]$containerName
    )

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { 
        $customConfigFile = Join-Path (Get-Item "C:\Program Files\Microsoft Dynamics NAV\*\Service").FullName "CustomSettings.config"
        [xml]$customConfig = [System.IO.File]::ReadAllText($customConfigFile)
        $customConfig.SelectSingleNode("//appSettings/add[@key='ClientServicesCredentialType']").Value
    }
}

function Update-Hosts {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$hostName,
        [string]$ip
    ) 

    $hostsFile = "c:\windows\system32\drivers\etc\hosts"

    if (Test-Path $hostsFile) {
        $retry = $true
        while ($retry) {
            try {
                [System.Collections.ArrayList]$hosts = @(Get-Content -Path $hostsFile -Encoding Ascii)
                $retry = $false
            } catch {
                Start-Sleep -Seconds 1
            }
        }
    } else {
        $hosts = New-Object System.Collections.ArrayList
    }
    $ln = 0
    while ($ln -lt $hosts.Count) {
        $line = $hosts[$ln]
        $idx = $line.IndexOf('#')
        if ($idx -ge 0) {
            $line = $line.Substring(0,$idx)
        }
        $hidx = ("$line ".Replace("`t"," ")).IndexOf(" $hostName ")
        if ($hidx -ge 0) {
            $hosts.RemoveAt($ln) | Out-Null
        } else {
            $ln++
        }
    }
    if ("$ip" -ne "") {
        $hosts.Add("$ip $hostName") | Out-Null
    }
    $retry = $true
    while ($retry) {
        try {
            Set-Content -Path $hostsFile -Value $($hosts -join [Environment]::NewLine) -Encoding Ascii -Force -ErrorAction Ignore
            $retry = $false
        } catch {
            Start-Sleep -Seconds 1
        }
    }
}

#endregion Internal helper functions

<#
 .Synopsis
  Get (or create) a PSSession for a Nav Container
 .Description
  Checks the session cache for an existing session. If a session exists, it will be reused.
  If no session exists, a new session will be created.
 .Parameter containerName
  Name of the container for which you want to create a session
 .Example
  $session = Get-NavContainerSession -containerName navserver
  PS C:\>Invoke-Command -Session $session -ScriptBlock { Set-NavServerInstance -ServerInstance NAV -restart }
#>

function Get-NavContainerSession {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $containerId = Get-NavContainerId -containerName $containerName

        if (!($sessions.ContainsKey($containerId))) {
            $session = New-PSSession -ContainerId $containerId -RunAsAdministrator
            Invoke-Command -Session $session -ScriptBlock {
                . "c:\run\prompt.ps1" | Out-Null
                . "c:\run\HelperFunctions.ps1" | Out-Null

                $txt2al = $NavIde.replace("finsql.exe","txt2al.exe")
                cd c:\run
            }
            $sessions.Add($containerId, $session)
        }
        $sessions[$containerId]
    }
}
Export-ModuleMember -function Get-NavContainerSession

<#
 .Synopsis
  Remove a PSSession for a Nav Container
 .Description
  If a session exists in the session cache, it will be removed and disposed.
  Remove-NavContainer automatically removes sessions created.
 .Parameter containerName
  Name of the container for which you want to remove the session
 .Example
  Remove-NavContainerSession -containerName navserver
#>

function Remove-NavContainerSession {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $containerId = Get-NavContainerId -containerName $containerName

        if ($sessions.ContainsKey($containerId)) {
            $session = $sessions[$containerId]
            Remove-PSSession -Session $session
            $sessions.Remove($containerId)
        }
    }
}
Export-ModuleMember -function Remove-NavContainerSession

<#
 .Synopsis
  Enter PowerShell session in Nav Container
 .Description
  Use the current PowerShell prompt to enter a PowerShell session in a Nav Container.
  Especially useful in PowerShell ISE, where you after entering a session, can use PSEdit to edit files inside the container.
  The PowerShell session will have the Nav PowerShell modules pre-loaded, meaning that you can use most Nav PowerShell CmdLets.
 .Parameter containerName
  Name of the container for which you want to enter a session
 .Example
  Enter-NavContainer -containerName
  [64b6ca872aefc93529bdfc7ec0a4eb7a2f0c022942000c63586a48c27b4e7b2d]: PS C:\run>psedit c:\run\navstart.ps1
#>

function Enter-NavContainer {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $session = Get-NavContainerSession $containerName
        Enter-PSSession -Session $session
    }
}
Export-ModuleMember -function Enter-NavContainer

<#
 .Synopsis
  Open a new PowerShell session for a Nav Container
 .Description
  Opens a new PowerShell window for a Nav Container.
  The PowerShell prompt will have the Nav PowerShell modules pre-loaded, meaning that you can use most Nav PowerShell CmdLets.
 .Parameter containerName
  Name of the container for which you want to open a session
 .Example
  Open-NavContainer -containerName navserver
#>

function Open-NavContainer {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        Start-Process "cmd.exe" @("/C";"docker exec -it $containerName powershell -noexit C:\Run\prompt.ps1")
    }
}
Export-ModuleMember -function Open-NavContainer

<#
 .Synopsis
  Get the version of NAV in a Nav container or a Nav container image
 .Description
  Returns the version of NAV in the format major.minor.build.release
 .Parameter containerOrImageName
  Name of the container or container image for which you want to enter a session
 .Example
  Get-NavContainerNavVersion -containerOrImageName navserver
 .Example
  Get-NavContainerNavVersion -containerOrImageName navdocker.azurecr.io/dynamics-nav:2017
#>

function Get-NavContainerNavVersion {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerOrImageName
    )

    Process {
        $inspect = docker inspect $containerOrImageName | ConvertFrom-Json
        return "$($inspect.Config.Labels.version)-$($inspect.Config.Labels.country)"
    }
}
Export-ModuleMember -function Get-NavContainerNavVersion

<#
 .Synopsis
  Get the name of the image used to run a Nav container
 .Description
  Get the name of the image used to run a Nav container
  The image name can be used to run a new instance of a Nav Container with the same version of Nav
 .Parameter containerName
  Name of the container for which you want to get the image name
 .Example
  $imageName = Get-NavContainerImageName -containerName navserver
  PS C:\>Docker run -e accept_eula=Y $imageName
#>

function Get-NavContainerImageName {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $inspect = docker inspect $containerName | ConvertFrom-Json
        return "$($inspect.Config.Image)"
    }
}
Export-ModuleMember -function Get-NavContainerImageName

<#
 .Synopsis
  Get the generic tag for a Nav container or a Nav container image
 .Description
  Returns the generic Tag version referring to a release from http://www.github.com/microsoft/nav-docker
 .Parameter containerOrImageName
  Name of the container or container image for which you want to get the generic tag
 .Example
  Get-NavContainerGenericTag -containerOrImageName navserver
 .Example
  Get-NavContainerGenericTag -containerOrImageName navdocker.azurecr.io/dynamics-nav:2017
#>

function Get-NavContainerGenericTag {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerOrImageName
    )

    Process {
        $inspect = docker inspect $containerOrImageName | ConvertFrom-Json
        return "$($inspect.Config.Labels.tag)"
    }
}
Export-ModuleMember -function Get-NavContainerGenericTag

<#
 .Synopsis
  Get the OS Version for a Nav container or a Nav container image
 .Description
  Returns the version of the WindowsServerCore image used to build the Nav container or Nav containerImage
 .Parameter containerOrImageName
  Name of the container or container image for which you want to get the OS Version
 .Example
  Get-NavContainerOsVersion -containerOrImageName navserver
 .Example
  Get-NavContainerOsVersion -containerOrImageName navdocker.azurecr.io/dynamics-nav:2017
#>

function Get-NavContainerOsVersion {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerOrImageName
    )

    Process {
        # returns empty with generic tag 0.0.2.3 or earlier
        $inspect = docker inspect $containerOrImageName | ConvertFrom-Json
        return "$($inspect.Config.Labels.osversion)"
    }
}
Export-ModuleMember -function Get-NavContainerOsVersion

<#
 .Synopsis
  Get the Legal Link for for a Nav container or a Nav container image
 .Description
  Returns the Legal link for the version of Nav in the Nav container or Nav containerImage
  This is the Eula, which you accept when running the Nav Container using -e accept_eula=Y
 .Parameter containerOrImageName
  Name of the container or container image for which you want to get the legal link
 .Example
  Get-NavContainerLegal -containerOrImageName navserver
 .Example
  Get-NavContainerLegal -containerOrImageName navdocker.azurecr.io/dynamics-nav:2017
#>

function Get-NavContainerLegal {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerOrImageName
    )

    Process {
        $inspect = docker inspect $containerOrImageName | ConvertFrom-Json
        return "$($inspect.Config.Labels.legal)"
    }
}
Export-ModuleMember -function Get-NavContainerLegal

<#
 .Synopsis
  Get the country version of Nav for a Nav container or a Nav container image
 .Description
  Returns the country version (localization) for the version of Nav in the Nav container or Nav containerImage
  Financials versions of Nav will be preceeded by 'fin', like finus, finca, fingb.
 .Parameter containerOrImageName
  Name of the container or container image for which you want to get the country version
 .Example
  Get-NavContainerCountry -containerOrImageName navserver
 .Example
  Get-NavContainerCountry -containerOrImageName navdocker.azurecr.io/dynamics-nav:2017
#>

function Get-NavContainerCountry {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerOrImageName
    )

    Process {
        $inspect = docker inspect $containerOrImageName | ConvertFrom-Json
        return "$($inspect.Config.Labels.country)"
    }
}
Export-ModuleMember -function Get-NavContainerCountry
<#
 .Synopsis
  Get the IP Address of a Nav container
 .Description
  Inspect the Nav Container and return the IP Address of the first network.
 .Parameter containerName
  Name of the container for which you want to get the IP Address
 .Example
  Get-NavContainerIpAddress -containerName navserver
#>

function Get-NavContainerIpAddress {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $inspect = docker inspect $containerName | ConvertFrom-Json
        $networks = $inspect.NetworkSettings.Networks
        $network = ($networks | get-member -MemberType NoteProperty | select Name).Name
        return ($networks | Select-Object -ExpandProperty $network).IPAddress
    }
}
Export-ModuleMember -function Get-NavContainerIpAddress

<#
 .Synopsis
  Get a list of folders shared with a Nav container
 .Description
  Returns a hastable of folders shared with the container.
  The name in the hashtable is the local folder, the value is the folder inside the container
 .Parameter containerName
  Name of the container for which you want to get the shared folder list
 .Example
  Get-NavContainerSharedFolders -containerName navserver
 .Example
  (Get-NavContainerSharedFolders -containerName navserver)["c:\demo"]
 .Example
  ((Get-NavContainerSharedFolders -containerName navserver).GetEnumerator() | Where-Object { $_.Value -eq "c:\run\my" }).Key
#>

function Get-NavContainerSharedFolders {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $inspect = docker inspect $containerName | ConvertFrom-Json
        $sharedFolders = @{}
        if ($inspect.HostConfig.Binds) {
            $inspect.HostConfig.Binds | % {
                $idx = $_.IndexOf(':', $_.IndexOf(':') + 1)
                $sharedFolders += @{$_.Substring(0, $idx) = $_.SubString($idx+1) }
            }
        }
        return $sharedFolders
    }
}
Export-ModuleMember -function Get-NavContainerSharedFolders

<#
 .Synopsis
  Get the container file system path of a host file
 .Description
  Enumerates the shared folders with the container and returns the container file system path for a file shared with the container.
 .Parameter containerName
  Name of the container for which you want to find the filepath
 .Parameter path
  Path of a file in the host file system
 .Example
  $containerPath = Get-NavContainerPath -containerName navserver -path c:\demo\extensions\test2\my
#>

function Get-NavContainerPath {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName,
        [Parameter(Mandatory=$true)]
        [string]$path,
        [switch]$throw
    )

    Process {
        $containerPath = ""
        $sharedFolders = Get-NavContainerSharedFolders -containerName $containerName
        $sharedFolders.GetEnumerator() | % {
            if ($containerPath -eq "" -and ($path -eq $_.Name -or $path.StartsWith($_.Name+"\", "OrdinalIgnoreCase"))) {
                $containerPath = ($_.Value + $path.Substring($_.Name.Length))
            }
        }
        if ($throw -and "$containerPath" -eq "") {
            throw "The folder $path is not shared with the container $containerName (nor is any of it's parent folders)"
        }
        return $containerPath
    }
}
Export-ModuleMember -function Get-NavContainerPath

<#
 .Synopsis
  Get the name of a Nav container
 .Description
  Returns the name of a Nav container based on the container Id
  You need to specify enought characters of the Id to make it unambiguous
 .Parameter containerId
  Id (or part of the Id) of the container for which you want to get the name
 .Example
  Get-NavContainerName -containerId 7d
#>

function Get-NavContainerName {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerId
    )

    docker ps --format='{{.Names}}' -a --filter "id=$containerId"
}
Export-ModuleMember -function Get-NavContainerName

<#
 .Synopsis
  Test whether a Nav container exists
 .Description
  Returns $true if the Nav container with the specified name exists
 .Parameter containerName
  Name of the container which you want to check for existence
 .Example
  if (Test-NavContainer -containerName devcontainer) { dosomething }
#>

function Test-NavContainer {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )
    Process {
        $exist = $false
        docker ps --filter name="$containerName" -a -q --no-trunc | % {
            $name = Get-NavContainerName -containerId $_
            if ($name -eq $containerName) {
                $exist = $true
            }
        }
        $exist
    }
}
Export-ModuleMember -function Test-NavContainer

<#
 .Synopsis
  Get the Id of a Nav container
 .Description
  Returns the Id of a Nav container based on the container name
  The Id returned is the full 64 digit container Id and the name must match
 .Parameter containerName
  Name of the container for which you want the Id
 .Example
  Get-NavContainerId -containerId navserver
#>

function Get-NavContainerId {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        $id = ""
        docker ps --filter name="$containerName" -a -q --no-trunc | % {
            # filter only filters on the start of the name
            $name = Get-NavContainerName -containerId $_
            if ($name -eq $containerName) {
                $id = $_
            }
        }
        $id
    }
}
Export-ModuleMember -function Get-NavContainerId

<#
 .Synopsis
  Create or refresh a CSide Development container
 .Description
  Creates a new container based on a Nav Docker Image
  Adds shortcut on the desktop for CSIDE, Windows Client, Web Client and Container PowerShell prompt.
  The command also exports all objects to a baseline folder to be used for delta creation
 .Parameter accept_eula
  Switch, which you need to specify if you accept the eula for running Nav on Docker containers (See https://go.microsoft.com/fwlink/?linkid=861843)
 .Parameter containerName
  Name of the new CSide Development container (if the container already exists it will be replaced)
 .Parameter devImageName
  Name of the image you want to use for your CSide Development container (default is to grab the imagename from the navserver container)
 .Parameter licenseFile
  Path or Secure Url of the licenseFile you want to use (default c:\demo\license.flf)
 .Parameter vmAdminUsername
  Name of the administrator user you want to add to the container
 .Parameter adminPassword
  Password of the administrator user you want to add to the container
 .Parameter memoryLimit
  Memory limit for the container (default 4G)
 .Parameter updateHosts
  Include this switch if you want to update the hosts file with the IP address of the container
 .Parameter useSSL
  Include this switch if you want to use SSL (https) with a self-signed certificate
 .Parameter auth
  Set auth to Windows or NavUserPassword depending on which authentication mechanism your container should use
 .Parameter additionalParameters
  This allows you to transfer an additional number of parameters to the docker run
 .Parameter myscripts
  This allows you to specify a number of scripts you want to copy to the c:\run\my folder in the container (override functionality)
 .Example
  New-CSideDevContainer -containerName test
 .Example
  New-SideDevContainer -containerName test -memoryLimit 3G -devImageName "navdocker.azurecr.io/dynamics-nav:2017" -updateHosts
 .Example
  New-CSideDevContainer -containerName test -adminPassword <mypassword> -licenseFile "https://www.dropbox.com/s/fhwfwjfjwhff/license.flf?dl=1" -devImageName "navdocker.azurecr.io/dynamics-nav:devpreview-finus"
#>

function New-CSideDevContainer {
    Param(
        [switch]$accept_eula,
        [switch]$accept_outdated,
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [string]$devImageName = "", 
        [string]$licenseFile = "",
        [string]$vmAdminUsername = (Get-DefaultVmAdminUsername), 
        [SecureString]$adminPassword = (Get-DefaultAdminPassword),
        [string]$memoryLimit = "4G",
        [switch]$updateHosts,
        [switch]$useSSL,
        [ValidateSet('Windows','NavUserPassword')]
        [string]$auth='Windows',
        [string[]]$additionalParameters = @(),
        [string[]]$myScripts = @()
    )

    New-NavContainer -accept_eula:$accept_eula `
                     -accept_outdated:$accept_outdated `
                     -containerName $containerName `
                     -imageName $devImageName `
                     -licenseFile $licenseFile `
                     -vmAdminUsername $vmAdminUsername `
                     -adminPassword $adminPassword `
                     -memoryLimit $memoryLimit `
                     -includeCSide `
                     -updateHosts:$updateHosts `
                     -useSSL:$useSSL `
                     -auth $auth `
                     -additionalParameters $additionalParameters `
                     -myScripts $myScripts
}
Export-ModuleMember -function New-CSideDevContainer

<#
 .Synopsis
  Create or refresh a Nav container
 .Description
  Creates a new Nav container based on a Nav Docker Image
  Adds shortcut on the desktop for Web Client and Container PowerShell prompt
 .Parameter accept_eula
  Switch, which you need to specify if you accept the eula for running Nav on Docker containers (See https://go.microsoft.com/fwlink/?linkid=861843)
 .Parameter containerName
  Name of the new Nav container (if the container already exists it will be replaced)
 .Parameter devImageName
  Name of the image you want to use for your Nav container (default is to grab the imagename from the navserver container)
 .Parameter licenseFile
  Path or Secure Url of the licenseFile you want to use (default c:\demo\license.flf)
 .Parameter vmAdminUsername
  Name of the administrator user you want to add to the container
 .Parameter adminPassword
  Password of the administrator user you want to add to the container
 .Parameter memoryLimit
  Memory limit for the container (default 4G)
 .Parameter updateHosts
  Include this switch if you want to update the hosts file with the IP address of the container
 .Parameter useSSL
  Include this switch if you want to use SSL (https) with a self-signed certificate
 .Parameter includeCSide
  Include this switch if you want to have Windows Client and CSide development environment available on the host
 .Parameter auth
  Set auth to Windows or NavUserPassword depending on which authentication mechanism your container should use
 .Parameter additionalParameters
  This allows you to transfer an additional number of parameters to the docker run
 .Parameter myscripts
  This allows you to specify a number of scripts you want to copy to the c:\run\my folder in the container (override functionality)
 .Example
  New-NavContainer -containerName test
 .Example
  New-NavContainer -containerName test -memoryLimit 3G -imageName "navdocker.azurecr.io/dynamics-nav:2017" -updateHosts
 .Example
  New-NavContainer -containerName test -imageName "navdocker.azurecr.io/dynamics-nav:2017" -myScripts @("c:\temp\AdditionalSetup.ps1") -AdditionalParameters @("-v c:\hostfolder:c:\containerfolder")
 .Example
  New-NavContainer -containerName test -adminPassword <mypassword> -licenseFile "https://www.dropbox.com/s/fhwfwjfjwhff/license.flf?dl=1" -imageName "navdocker.azurecr.io/dynamics-nav:devpreview-finus"
#>

function New-NavContainer {
    Param(
        [switch]$accept_eula,
        [switch]$accept_outdated,
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [string]$imageName = "", 
        [string]$licenseFile = "",
        [string]$vmAdminUsername = (Get-DefaultVmAdminUsername),
        [SecureString]$adminPassword = (Get-DefaultAdminPassword),
        [string]$memoryLimit = "4G",
        [switch]$updateHosts,
        [switch]$useSSL,
        [switch]$includeCSide,
        [ValidateSet('Windows','NavUserPassword')]
        [string]$auth='Windows',
        [string[]]$additionalParameters = @(),
        [string[]]$myScripts = @()
    )

    if (!$accept_eula) {
        throw "You have to accept the eula (See https://go.microsoft.com/fwlink/?linkid=861843) by specifying the -accept_eula switch to the function"
    }

    if ($containerName -eq "navserver") {
        throw "You cannot create a Nav container called navserver. Use Replace-NavServerContainer to replace the navserver container."
    }

    if ($includeCSide) {  
        if ($licenseFile -eq "") {
            $licenseFile = "C:\DEMO\license.flf"
            if (!(Test-Path -Path $licenseFile)) {
                throw "You must specify a license file to use for the CSide Development container."
            }
        } elseif ($licensefile.StartsWith("https://", "OrdinalIgnoreCase") -or $licensefile.StartsWith("http://", "OrdinalIgnoreCase")) {
        } elseif (!(Test-Path $licenseFile)) {
            throw "License file '$licenseFile' must exist in order to create a Developer Server Container."
        }
    }

    $myScripts | % {
        if (!(Test-Path $_ -PathType Leaf)) {
            throw "Script file $_ does not exist"
        }
    }

    if ($imageName -eq "") {
        if (!(Test-NavContainer -containerName navserver)) {
            throw "You need to specify the name of the docker image you want to use for your Nav container."
        }
        $imageName = Get-NavContainerImageName -containerName navserver
        $devCountry = Get-NavContainerCountry -containerOrImageName navserver
    } else {
        $imageId = docker images -q $imageName
        if (!($imageId)) {
            Write-Host "Pulling docker Image $imageName"
            docker pull $imageName
        }
        $devCountry = Get-NavContainerCountry -containerOrImageName $imageName
    }

    Write-Host "Creating Nav container $containerName"
    Write-Host "Using image $imageName"
    Write-Host "Using license file $licenseFile"
    $navversion = Get-NavContainerNavversion -containerOrImageName $imageName
    Write-Host "NAV Version: $navversion"
    $genericTag = Get-NavContainerGenericTag -containerOrImageName $imageName
    Write-Host "Generic Tag: $genericTag"
    $locale = Get-LocaleFromCountry $devCountry

    if (Test-NavContainer -containerName $containerName) {
        Remove-NavContainer $containerName -UpdateHosts:$UpdateHosts
    }

    $containerFolder = Join-Path $ExtensionsFolder $containerName
    New-Item -Path $containerFolder -ItemType Directory -ErrorAction Ignore | Out-Null
    $myFolder = Join-Path $containerFolder "my"
    New-Item -Path $myFolder -ItemType Directory -ErrorAction Ignore | Out-Null

    $myScripts | % {
        Copy-Item -Path $_ -Destination $myFolder -Force
    }

    if ("$licensefile" -eq "" -or $licensefile.StartsWith("https://", "OrdinalIgnoreCase") -or $licensefile.StartsWith("http://", "OrdinalIgnoreCase")) {
        $containerLicenseFile = $licenseFile
    } else {
        Copy-Item -Path $licenseFile -Destination "$myFolder\license.flf" -Force
        $containerLicenseFile = "c:\run\my\license.flf"
    }

    if ($includeCSide) {
        $programFilesFolder = Join-Path $containerFolder "Program Files"
        New-Item -Path $programFilesFolder -ItemType Directory -ErrorAction Ignore | Out-Null

        'sqlcmd -d $DatabaseName -Q "update [dbo].[Object] SET [Modified] = 0"
        '
 | Add-Content -Path "$myfolder\AdditionalSetup.ps1"
        
        if (Test-Path $programFilesFolder) {
            Remove-Item $programFilesFolder -Force -Recurse -ErrorAction Ignore
        }
        New-Item $programFilesFolder -ItemType Directory -ErrorAction Ignore | Out-Null
        
        ('Copy-Item -Path "C:\Program Files (x86)\Microsoft Dynamics NAV\*" -Destination "c:\navpfiles" -Recurse -Force -ErrorAction Ignore
        $destFolder = (Get-Item "c:\navpfiles\*\RoleTailored Client").FullName
        $ClientUserSettingsFileName = "$runPath\ClientUserSettings.config"
        [xml]$ClientUserSettings = Get-Content $clientUserSettingsFileName
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""Server""]").value = "'
+$containerName+'"
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""ServerInstance""]").value="NAV"
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""ServicesCertificateValidationEnabled""]").value="false"
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""ClientServicesPort""]").value="$publicWinClientPort"
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""ACSUri""]").value = ""
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""DnsIdentity""]").value = "$dnsIdentity"
        $clientUserSettings.SelectSingleNode("//configuration/appSettings/add[@key=""ClientServicesCredentialType""]").value = "$Auth"
        $clientUserSettings.Save("$destFolder\ClientUserSettings.config")
        '
) | Add-Content -Path "$myfolder\AdditionalSetup.ps1"
    }

    Write-Host "Creating container $containerName from image $imageName"

    $parameters = @(
                    "--name $containerName",
                    "--hostname $containerName",
                    "--env auth=$auth"
                    "--env username=$vmAdminUsername",
                    "--env ExitOnError=N",
                    "--env locale=$locale",
                    "--env licenseFile=""$containerLicenseFile""",
                    "--memory $memoryLimit",
                    "--volume ""${demoFolder}:$containerDemoFolder""",
                    "--volume ""${myFolder}:C:\Run\my""",
                    "--restart always"
                   )

    if ($useSSL) {
        $parameters += "--env useSSL=Y"
    } else {
        $parameters += "--env useSSL=N"
    }

    if ($includeCSide) {
        $parameters += "--volume ""${programFilesFolder}:C:\navpfiles"""
    }

    if ([System.Version]$genericTag -ge [System.Version]"0.0.3.0") {
        $passwordKeyFile = "$myfolder\aes.key"
        $passwordKey = New-Object Byte[] 16
        [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($passwordKey)
        try {
            Set-Content -Path $passwordKeyFile -Value $passwordKey
            $encPassword = ConvertFrom-SecureString -SecureString $adminPassword -Key $passwordKey
            
            $parameters += @(
                             "--env securePassword=$encPassword",
                             "--env passwordKeyFile=""$passwordKeyFile""",
                             "--env removePasswordKeyFile=Y"
                            )
            
            $parameters += $additionalParameters
        
            $id = DockerRun -accept_eula -accept_outdated:$accept_outdated -imageName $imageName -parameters $parameters
            Wait-NavContainerReady $containerName
        } finally {
            Remove-Item -Path $passwordKeyFile -Force -ErrorAction Ignore
        }
    } else {
        $plainPassword = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($adminPassword)))
        $parameters += "--env password=""$plainPassword"""
        $parameters += $additionalParameters
        $id = DockerRun -accept_eula -accept_outdated:$accept_outdated -imageName $imageName -parameters $parameters
        Wait-NavContainerReady $containerName
    }

    if ($UpdateHosts) {
        $ip = Get-NavContainerIpAddress -containerName $containerName
        Write-Host "Add $ip $containerName to hosts"
        Update-Hosts -hostName $containerName -ip $ip
    }

    Write-Host "Create Desktop Shortcuts for $containerName"

    if ($useSSL) {
        $protocol = "https://"
    } else {
        $protocol = "http://"
    }
    New-DesktopShortcut -Name "$containerName Web Client" -TargetPath "$protocol${containerName}/NAV/" -IconLocation "C:\Program Files\Internet Explorer\iexplore.exe, 3"
    New-DesktopShortcut -Name "$containerName Command Prompt" -TargetPath "CMD.EXE" -IconLocation "C:\Program Files\Docker\docker.exe, 0" -Arguments "/C docker.exe exec -it $containerName cmd"
    New-DesktopShortcut -Name "$containerName PowerShell Prompt" -TargetPath "CMD.EXE" -IconLocation "C:\Program Files\Docker\docker.exe, 0" -Arguments "/C docker.exe exec -it $containerName powershell -noexit c:\run\prompt.ps1"

    if ($includeCSide) {
        $winClientFolder = (Get-Item "$programFilesFolder\*\RoleTailored Client").FullName
        $ps = '$customConfigFile = Join-Path (Get-Item ''C:\Program Files\Microsoft Dynamics NAV\*\Service'').FullName "CustomSettings.config"
        [System.IO.File]::ReadAllText($customConfigFile)'

        [xml]$customConfig = docker exec $containerName powershell $ps
        $databaseInstance = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseInstance']").Value
        $databaseName = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseName']").Value
        $databaseServer = "$containerName"
        if ($databaseInstance) { $databaseServer += "\$databaseInstance" }
        New-DesktopShortcut -Name "$containerName Windows Client" -TargetPath "$WinClientFolder\Microsoft.Dynamics.Nav.Client.exe"
        New-DesktopShortcut -Name "$containerName CSIDE" -TargetPath "$WinClientFolder\finsql.exe" -Arguments "servername=$databaseServer, Database=$databaseName, ntauthentication=yes"

        $false, $true | % {
            $newSyntax = $_
            $suffix = ""
            if ($newSyntax) { $suffix = "-newsyntax" }
            $originalFolder   = Join-Path $ExtensionsFolder "Original-$navversion$suffix"
            if (!(Test-Path $originalFolder)) {
                # Export base objects
                Export-NavContainerObjects -containerName $containerName `
                                           -objectsFolder $originalFolder `
                                           -filter "" `
                                           -adminPassword $adminPassword `
                                           -ExportToNewSyntax:$newSyntax
            }
        }
    }
    Write-Host -ForegroundColor Green "Nav container $containerName successfully created"
}
Export-ModuleMember -function New-NavContainer

<#
 .Synopsis
  Remove Nav container
 .Description
  Remove container, Session, Shortcuts, temp. files and entries in the hosts file,
 .Parameter containerName
  Name of the container for which you want to enter a session
 .Parameter updateHosts
  Include this switch if you want to update the hosts file and remove the container entry
 .Example
  Remove-NavContainer -containerName devServer
 .Example
  Remove-NavContainer -containerName test -updateHosts
#>

function Remove-NavContainer {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName,
        [switch]$UpdateHosts
    )

    Process {
        if ($containerName -eq "navserver") {
            throw "You should not remove the navserver container. Use Replace-NavServerContainer to replace the navserver container."
        }

        if (Test-NavContainer -containerName $containerName) {
            Remove-NavContainerSession $containerName
            $containerId = Get-NavContainerId -containerName $containerName
            Write-Host "Removing container $containerName"
            docker rm $containerId -f | Out-Null
            $containerFolder = Join-Path $ExtensionsFolder $containerName
            Remove-Item -Path $containerFolder -Force -Recurse -ErrorAction Ignore
            Write-Host "Removing Desktop Shortcuts for container $containerName"
            Remove-DesktopShortcut -Name "$containerName Web Client"
            Remove-DesktopShortcut -Name "$containerName Windows Client"
            Remove-DesktopShortcut -Name "$containerName CSIDE"
            Remove-DesktopShortcut -Name "$containerName Command Prompt"
            Remove-DesktopShortcut -Name "$containerName PowerShell Prompt"
            if ($UpdateHosts) {
                Write-Host "Remove $containerName from hosts"
                Update-Hosts -hostName $containerName -ip ""
            }
            Write-Host -ForegroundColor Green "Successfully removed container $containerName"
        }
    }
}
Export-ModuleMember -function Remove-NavContainer

<#
 .Synopsis
  Wait for Nav container to become ready
 .Description
  Wait for Nav container to log "Ready for connections!"
  If the container experiences an error, the function will throw an exception
 .Parameter containerName
  Name of the container for which you want to wait
 .Example
  Wait-NavContainerReady -containerName navserver
#>

function Wait-NavContainerReady {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$containerName
    )

    Process {
        Write-Host "Waiting for container $containerName to be ready, this shouldn't take more than a few minutes"
        Write-Host "Time: ½ 1 ½ 2"
        $cnt = 150
        $log = ""
        do {
            Write-Host -NoNewline "."
            Start-Sleep -Seconds 2
            $logs = docker logs $containerName
            if ($logs) { $log = [string]::Join("`r`n",$logs) }
            if ($cnt-- -eq 0 -or $log.Contains("<ScriptBlock>")) { 
                Write-Host "Error"
                Write-Host $log
                throw "Initialization of container $containerName failed"
            }
        } while (!($log.Contains("Ready for connections!")))
        Write-Host "Ready"
    }
}
Export-ModuleMember -function Wait-NavContainerReady

<#
 .Synopsis
  Export objects from a Nav container
 .Description
  Creates a session to the Nav container and launch the Export-NavApplicationObjects Cmdlet to export object
 .Parameter containerName
  Name of the container for which you want to enter a session
 .Parameter objectsFolder
  The folder to which the objects are exported (needs to be shared with the container)
 .Parameter vmadminUsername
  Username of the administrator user in the container (defaults to sa)
 .Parameter adminPassword
  The admin password for the container (if using NavUserPassword authentication)
 .Parameter filter
  Specifies which objects to export (default is modified=Yes)
 .Parameter exportToNewSyntax
  Specifies whether or not to export objects in new syntax (default is true)
 .Example
  Export-NavContainerObject -containerName test -objectsFolder c:\demo\objects
 .Example
  Export-NavContainerObject -containerName test -objectsFolder c:\demo\objects -adminPassword <adminPassword> -filter ""
#>

function Export-NavContainerObjects {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [Parameter(Mandatory=$true)]
        [string]$objectsFolder, 
        [string]$vmadminUsername = 'sa',
        [SecureString]$adminPassword = $null, 
        [string]$filter = "modified=Yes", 
        [switch]$exportToNewSyntax = $true
    )

    $containerAuth = Get-NavContainerAuth -containerName $containerName
    if ($containerAuth -eq "NavUserPassword" -and !($adminPassword)) {
        $adminPassword = Get-DefaultAdminPassword
    }

    $containerObjectsFolder = Get-NavContainerPath -containerName $containerName -path $objectsFolder -throw

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($filter, $objectsFolder, $vmadminUsername, $adminPassword, $exportToNewSyntax)

        $objectsFile = "$objectsFolder.txt"
        Remove-Item -Path $objectsFile -Force -ErrorAction Ignore
        Remove-Item -Path $objectsFolder -Force -Recurse -ErrorAction Ignore
        $filterStr = ""
        if ($filter) {
            $filterStr = " with filter '$filter'"
        }
        if ($exportToNewSyntax) {
            Write-Host "Export Objects$filterStr (new syntax) to $objectsFile"
        } else {
            Write-Host "Export Objects$filterStr to $objectsFile"
        }

        $customConfigFile = Join-Path (Get-Item "C:\Program Files\Microsoft Dynamics NAV\*\Service").FullName "CustomSettings.config"
        [xml]$customConfig = [System.IO.File]::ReadAllText($customConfigFile)
        $databaseServer = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseServer']").Value
        $databaseInstance = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseInstance']").Value
        $databaseName = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseName']").Value
        if ($databaseInstance) { $databaseServer += "\$databaseInstance" }

        $creds = @{}
        if ($adminPassword) {
            $creds = @{ 'Username' = $vmadminUsername; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($adminPassword))) }
        }

        Export-NAVApplicationObject @creds -DatabaseName $databaseName `
                                    -Path $objectsFile `
                                    -DatabaseServer $databaseServer `
                                    -Force `
                                    -Filter "$filter" `
                                    -ExportToNewSyntax:$ExportToNewSyntax | Out-Null

        Write-Host "Split $objectsFile to $objectsFolder"
        New-Item -Path $objectsFolder -ItemType Directory -Force -ErrorAction Ignore | Out-Null
        Split-NAVApplicationObjectFile -Source $objectsFile `
                                       -Destination $objectsFolder
        Remove-Item -Path $objectsFile -Force -ErrorAction Ignore
    
    }  -ArgumentList $filter, $containerObjectsFolder, $vmadminUsername, $adminPassword, $exportToNewSyntax
}
Export-ModuleMember -function Export-NavContainerObjects

<#
 .Synopsis
  Creates a folder with modified base objects
 .Description
  Compares files from the modifiedFolder with files in the originalFolder to identify which base objects have been changed.
  All changed base objects are copied to the myoriginalFolder, which allows the Create-MyDeltaFolder to identify new and modified objects.
 .Parameter $originalFolder,
  Folder containig the original base objects
 .Parameter $modifiedFolder,
  Folder containing your modified objects
 .Parameter $myoriginalFolder
  Folder in which the original objects for your modified objects are copied to
 .Example
  Create-MyOriginalFolder -originalFolder c:\demo\baseobjects -modifiedFolder c:\demo\myobjects -myoriginalFolder c:\demo\mybaseobjects
#>

function Create-MyOriginalFolder {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$originalFolder, 
        [Parameter(Mandatory=$true)]
        [string]$modifiedFolder, 
        [Parameter(Mandatory=$true)]
        [string]$myoriginalFolder
    )

    Write-Host "Copy original objects to $myoriginalFolder for all objects that are modified"
    Remove-Item -Path $myoriginalFolder -Recurse -Force -ErrorAction Ignore
    New-Item -Path $myoriginalFolder -ItemType Directory | Out-Null
    Get-ChildItem $modifiedFolder | % {
        $Name = ($_.BaseName+".txt")
        $OrgName = Join-Path $myOriginalFolder $Name
        $TxtFile = Join-Path $originalFolder $Name
        if (Test-Path -Path $TxtFile) {
            Copy-Item -Path $TxtFile -Destination $OrgName
        }
    }
}
Export-ModuleMember -function Create-MyOriginalFolder

<#
 .Synopsis
  Create folder with delta files for my objects
 .Description
  Compare my objects with my base objects and create a folder with delta files.
  Modified objects will be stored as .delta files, new objects will be .txt files.
 .Parameter containerName
  Name of the container in which the Nav Development Cmdlets are to be executed
 .Parameter modifiedFolder
  Folder containing your modified objects
 .Parameter $myoriginalFolder
  Folder containing the original objects for your modified objects
 .Parameter myDeltaFolder
  Folder in which the delta files are created
 .Example
  Create-MyDeltaFolder -containerName test -modifiedFolder c:\demo\myobjects -myoriginalFolder c:\demo\myoriginalobjects -mydeltaFolder c:\demo\mydeltafiles
#>

function Create-MyDeltaFolder {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [Parameter(Mandatory=$true)]
        [string]$modifiedFolder, 
        [Parameter(Mandatory=$true)]
        [string]$myOriginalFolder, 
        [Parameter(Mandatory=$true)]
        [string]$myDeltaFolder
    )

    $containerModifiedFolder = Get-NavContainerPath -containerName $containerName -path $modifiedFolder -throw
    $containerMyOriginalFolder = Get-NavContainerPath -containerName $containerName -path $myOriginalFolder -throw
    $containerMyDeltaFolder = Get-NavContainerPath -containerName $containerName -path $myDeltaFolder -throw

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($modifiedFolder, $myOriginalFolder, $myDeltaFolder)

        Write-Host "Compare modified objects with original objects in $myOriginalFolder and create Deltas in $myDeltaFolder"
        Remove-Item -Path $myDeltaFolder -Recurse -Force -ErrorAction Ignore
        New-Item -Path $myDeltaFolder -ItemType Directory | Out-Null
        Compare-NAVApplicationObject -OriginalPath $myOriginalFolder -ModifiedPath $modifiedFolder -DeltaPath $myDeltaFolder | Out-Null

        Write-Host "Rename new objects to .TXT"
        Get-ChildItem $myDeltaFolder | % {
            $Name = $_.Name
            if ($Name.ToLowerInvariant().EndsWith(".delta")) {
                $BaseName = $_.BaseName
                $OrgName = Join-Path $myOriginalFolder "${BaseName}.TXT"
                if (!(Test-Path -Path $OrgName)) {
                    Rename-Item -Path $_.FullName -NewName "${BaseName}.TXT"
                }
            }
        }
    } -ArgumentList $containerModifiedFolder, $containerMyOriginalFolder, $containerMyDeltaFolder
}
Export-ModuleMember -function Create-MyDeltaFolder

<#
 .Synopsis
  Convert txt and delta files to AL
 .Description
  Convert objects in myDeltaFolder to AL. Page and Table extensions are created as new objects using the startId as object Id offset.
  Code modifications and other things not supported in extensions will not be converted to AL.
  Manual modifications are required after the conversion.
 .Parameter containerName
  Name of the container in which the txt2al tool will be executed
 .Parameter myDeltaFolder
  Folder containing delta files
 .Parameter myAlFolder
  Folder in which the AL files are created
 .Parameter startId
  Starting offset for objects created by the tool (table and page extensions)
 .Example
  Convert-Txt2Al -containerName test -mydeltaFolder c:\demo\mydeltafiles -myAlFolder c:\demo\myAlFiles -startId 50100
#>

function Convert-Txt2Al {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [Parameter(Mandatory=$true)]
        [string]$myDeltaFolder, 
        [Parameter(Mandatory=$true)]
        [string]$myAlFolder, 
        [int]$startId=50100
    )

    $containerMyDeltaFolder = Get-NavContainerPath -containerName $containerName -path $myDeltaFolder -throw
    $containerMyAlFolder = Get-NavContainerPath -containerName $containerName -path $myAlFolder -throw

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($myDeltaFolder, $myAlFolder, $startId)

        if (!($txt2al)) {
            throw "You cannot run Convert-Txt2Al on this Nav Container"
        }
        Write-Host "Converting files in $myDeltaFolder to .al files in $myAlFolder with startId $startId"
        Remove-Item -Path $myAlFolder -Recurse -Force -ErrorAction Ignore
        New-Item -Path $myAlFolder -ItemType Directory -ErrorAction Ignore | Out-Null
        Start-Process -FilePath $txt2al -ArgumentList "--source=""$myDeltaFolder"" --target=""$myAlFolder"" --rename --extensionStartId=$startId" -Wait -NoNewWindow
    
    } -ArgumentList $containerMyDeltaFolder, $containerMyAlFolder, $startId
}
Export-ModuleMember -function Convert-Txt2Al

<#
 .Synopsis
  Convert modified objects in a Nav container to AL
 .Description
  This command will invoke the 4 commands in order to export modified objects and convert them to AL:
  1. Export-NavContainerObjects
  2. Create-MyOriginalFolder
  3. Create-MyDeltaFolder
  4. Convert-Txt2Al
  A folder with the name of the container is created underneath c:\demo\extensions for holding all the temp and the final output.
  The command will open a windows explorer window with the output
 .Parameter containerName
  Name of the container for which you want to export and convert objects
 .Parameter vmadminUsername
  Username of the administrator user in the container (defaults to sa)
 .Parameter adminPassword
  The admin password for the container (if using NavUserPassword authentication)
 .Parameter startId
  Starting offset for objects created by the tool (table and page extensions)
 .Parameter openFolder
  Switch telling the function to open the result folder in Windows Explorer when done
 .Example
  Convert-ModifiedObjectsToAl -containerName test
 .Example
  Convert-ModifiedObjectsToAl -containerName test -adminPassword <adminPassword> -startId 881200
#>

function Convert-ModifiedObjectsToAl {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [string]$vmadminUsername = 'sa',
        [SecureString]$adminPassword = $null, 
        [int]$startId = 50100,
        [switch]$openFolder = $true
    )

    $session = Get-NavContainerSession -containerName $containerName
    $txt2al = Invoke-Command -Session $session -ScriptBlock { $txt2al }
    if (!($txt2al)) {
        throw "You cannot run Convert-ModifiedObjectsToAl on this Nav Container, the txt2al tool is not present."
    }

    Export-ModifiedObjectsAsDeltas -containerName $containerName -vmadminUsername $vmadminUsername -adminPassword $adminPassword -openFolder:$false -useNewSyntax

    $suffix = "-newsyntax"

    $myDeltaFolder    = Join-Path $ExtensionsFolder "$containerName\delta$suffix"
    $myAlFolder       = Join-Path $ExtensionsFolder "$containerName\al$suffix"

    Convert-Txt2Al -containerName $containerName `
                   -myDeltaFolder $myDeltaFolder `
                   -myAlFolder $myAlFolder `
                   -startId $startId

    if ($openFolder) {
        Start-Process $myAlFolder
        Write-Host "al files created in $myAlFolder"
    }
}
Export-ModuleMember -Function Convert-ModifiedObjectsToAl

<#
 .Synopsis
  Export modified objects in a Nav container as DELTA files
 .Description
  This command will invoke the 3 commands in order to export modified objects and convert them to DELTA files:
  1. Export-NavContainerObjects
  2. Create-MyOriginalFolder
  3. Create-MyDeltaFolder
  A folder with the name of the container is created underneath c:\demo\extensions for holding all the temp and the final output.
  The command will open a windows explorer window with the output
 .Parameter containerName
  Name of the container for which you want to export and convert objects
 .Parameter vmadminUsername
  Username of the administrator user in the container (defaults to sa)
 .Parameter adminPassword
  The admin password for the container (if using NavUserPassword authentication)
 .Parameter startId
  Starting offset for objects created by the tool (table and page extensions)
 .Parameter openFolder
  Switch telling the function to open the result folder in Windows Explorer when done
 .Example
  Export-ModifiedObjectsAsDeltas -containerName test
 .Example
  Export-ModifiedObjectsAsDeltas -containerName test -adminPassword <adminPassword>
#>

function Export-ModifiedObjectsAsDeltas {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [string]$vmadminUsername = 'sa',
        [SecureString]$adminPassword = $null, 
        [switch]$useNewSyntax = $false,
        [switch]$openFolder = $true
    )

    $containerAuth = Get-NavContainerAuth -containerName $containerName
    if ($containerAuth -eq "NavUserPassword" -and !($adminPassword)) {
        $adminPassword = Get-DefaultAdminPassword
    }

    if ((Get-NavContainerSharedFolders -containerName $containerName)[$demoFolder] -ne $containerDemoFolder) {
        throw "In order to run Export-ModifiedObjectsAsDeltas you need to have shared $demoFolder to $containerDemoFolder in the container (docker run ... -v ${demoFolder}:$containerDemoFolder ... <image>)."
    }

    $suffix = ""
    if ($useNewSyntax) {
        $suffix = "-newsyntax"
    }
    $navversion = Get-NavContainerNavversion -containerOrImageName $containerName
    $originalFolder   = Join-Path $ExtensionsFolder "Original-$navversion$suffix"

    if (!(Test-Path $originalFolder)) {
        throw "Folder $originalFolder must contain all Nav base objects (original). You can use Export-NavContainerObjects on a fresh container or create your development container using New-CSideDevContainer, which does this automatically."
    }

    $modifiedFolder   = Join-Path $ExtensionsFolder "$containerName\modified$suffix"
    $myOriginalFolder = Join-Path $ExtensionsFolder "$containerName\original$suffix"
    $myDeltaFolder    = Join-Path $ExtensionsFolder "$containerName\delta$suffix"

    # Export my objects
    Export-NavContainerObjects -containerName $containerName `
                               -objectsFolder $modifiedFolder `
                               -filter "modified=Yes" `
                               -vmadminUsername $vmadminUsername `
                               -adminPassword $adminPassword `
                               -exportToNewSyntax:$useNewSyntax

    Create-MyOriginalFolder -originalFolder $originalFolder `
                            -modifiedFolder $modifiedFolder `
                            -myOriginalFolder $myOriginalFolder

    Create-MyDeltaFolder -containerName $containerName `
                         -modifiedFolder $modifiedFolder `
                         -myOriginalFolder $myOriginalFolder `
                         -myDeltaFolder $myDeltaFolder

    if ($openFolder) {
        Start-Process $myDeltaFolder
        Write-Host "delta files created in $myDeltaFolder"
    }
}
Export-ModuleMember -Function Export-ModifiedObjectsAsDeltas

<#
 .Synopsis
  Import Objects to Nav Container
 .Description
  Copy the object file to the Nav container if necessary.
  Create a session to a Nav container and run Import-NavApplicationObject
 .Parameter containerName
  Name of the container for which you want to enter a session
 .Parameter objectsFile
  Path of the objects file you want to import
 .Parameter vmadminUsername
  Username of the administrator user in the container (defaults to sa)
 .Parameter adminPassword
  The admin password for the container (if using NavUserPassword authentication)
 .Example
  Import-ObjectsToNavContainer -containerName test2 -objectsFile c:\temp\objects.txt -adminPassword <adminpassword>
#>

function Import-ObjectsToNavContainer {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [Parameter(Mandatory=$true)]
        [string]$objectsFile,
        [string]$vmadminUsername = 'sa',
        [SecureString]$adminPassword = $null
    )

    $containerAuth = Get-NavContainerAuth -containerName $containerName
    if ($containerAuth -eq "NavUserPassword" -and !($adminPassword)) {
        $adminPassword = Get-DefaultAdminPassword
    }

    $containerObjectsFile = Get-NavContainerPath -containerName $containerName -path $objectsFile
    $copied = $false
    if ("$containerObjectsFile" -eq "") {
        $containerObjectsFile = Join-Path "c:\run" ([System.IO.Path]::GetFileName($objectsFile))
        Copy-FileToNavContainer -containerName $containerName -localPath $objectsFile -containerPath $containerObjectsFile
        $copied = $true
    }

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($objectsFile, $vmadminUsername, $adminPassword, $copied)
    
        $customConfigFile = Join-Path (Get-Item "C:\Program Files\Microsoft Dynamics NAV\*\Service").FullName "CustomSettings.config"
        [xml]$customConfig = [System.IO.File]::ReadAllText($customConfigFile)
        $databaseServer = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseServer']").Value
        $databaseInstance = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseInstance']").Value
        $databaseName = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseName']").Value
        if ($databaseInstance) { $databaseServer += "\$databaseInstance" }
    
        $creds = @{}
        if ($adminPassword) {
            $creds = @{ 'Username' = $vmadminUsername; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($adminPassword))) }
        }
        Write-Host "Importing Objects from $objectsFile"
        Import-NAVApplicationObject @creds -Path $objectsFile `
                                    -DatabaseName $databaseName `
                                    -DatabaseServer $databaseServer `
                                    -ImportAction Overwrite `
                                    -SynchronizeSchemaChanges Force `
                                    -NavServerName localhost `
                                    -NavServerInstance NAV `
                                    -NavServerManagementPort 7045 `
                                    -Confirm:$false

        if ($copied) {
            Remove-Item -Path $objectsFile -Force
        }
    
    } -ArgumentList $containerObjectsFile, $vmadminUsername, $adminPassword, $copied
    Write-Host -ForegroundColor Green "Objects successfully imported"
}
Export-ModuleMember -Function Import-ObjectsToNavContainer

<#
 .Synopsis
  Merge deltas and import Objects to Nav Container
 .Description
  Create a session to a Nav Container and run Update-NavApplicationObject,
  merginge deltas with original objects from that container and create object file
  Import object file using Import-NavApplicationObject
 .Parameter containerName
  Name of the container for which you want to enter a session
 .Parameter deltaFolder
  Path of the folder containing the delta files you want to import
 .Parameter vmadminUsername
  Username of the administrator user in the container (defaults to sa)
 .Parameter adminPassword
  The admin password for the container (if using NavUserPassword authentication)
 .Example
  Import-DeltasToNavContainer -containerName test2 -deltaFolder c:\temp\mydeltas
#>

function Import-DeltasToNavContainer {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [Parameter(Mandatory=$true)]
        [string]$deltaFolder,
        [string]$vmadminUsername = 'sa',
        [SecureString]$adminPassword = $null
    )

    $containerAuth = Get-NavContainerAuth -containerName $containerName
    if ($containerAuth -eq "NavUserPassword" -and !($adminPassword)) {
        $adminPassword = Get-DefaultAdminPassword
    }

    $containerDeltaFolder = Get-NavContainerPath -containerName $containerName -path $deltaFolder
    if ("$containerDeltaFolder" -eq "") {
        throw "The deltaFolder ($deltaFolder) is not shared with the container."
    }

    $navversion = Get-NavContainerNavversion -containerOrImageName $containerName
    $originalFolder   = Join-Path $ExtensionsFolder "Original-$navversion"
    $mergeResultFile  = Join-Path $ExtensionsFolder "$containerName\mergeresult.txt"
    Remove-Item $mergeResultFile -Force -ErrorAction Ignore
    $mergedObjectsFile  = Join-Path $ExtensionsFolder "$containerName\mergedobjects.txt"
    Remove-Item $mergedObjectsFile -Force -ErrorAction Ignore
    $myOriginalFolder = Join-Path $ExtensionsFolder "$containerName\original"
    Remove-Item $myOriginalFolder -Force -Recurse -ErrorAction Ignore

    Create-MyOriginalFolder -originalFolder $originalFolder `
                            -modifiedFolder $deltaFolder `
                            -myOriginalFolder $myOriginalFolder

    $containerMyOriginalFolder = Get-NavContainerPath -containerName $containerName -path $myOriginalFolder -throw
    $containerMergeResultFile = Get-NavContainerPath -containerName $containerName -path $mergeResultFile -throw
    $containerMergedObjectsFile = Get-NavContainerPath -containerName $containerName -path $mergedObjectsFile -throw

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($deltaFolder, $originalFolder, $mergedObjectsFile, $mergeResultFile, $vmadminUsername, $adminPassword)
    
        $creds = @{}
        if ($adminPassword) {
            $creds = @{ 'Username' = $vmadminUsername; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($adminPassword))) }
        }

        Write-Host "Merging Deltas from $deltaFolder"
        Update-NAVApplicationObject -TargetPath $originalFolder `
                                    -DeltaPath $deltaFolder `
                                    -ResultPath $mergedObjectsFile `
                                    -ModifiedProperty Yes `
                                    -VersionListProperty FromModified `
                                    -DateTimeProperty FromModified | Set-Content $mergeResultFile

    } -ArgumentList $containerDeltaFolder, $containerMyOriginalFolder, $containerMergedObjectsFile, $containerMergeResultFile, $vmadminUsername, $adminPassword

    if (Test-Path $mergedObjectsFile) {
        Import-ObjectsToNavContainer -containerName $containerName `
                                     -objectsFile $mergedObjectsFile `
                                     -vmadminUsername $vmadminUsername `
                                     -adminPassword $adminPassword
    }
}
Export-ModuleMember -Function Import-DeltasToNavContainer


<#
 .Synopsis
  Compile Objects to Nav Container
 .Description
  Create a session to a Nav container and run Compile-NavApplicationObject
 .Parameter containerName
  Name of the container for which you want to enter a session
 .Parameter filter
  filter of the objects you want to compile (default is modified=Yes)
 .Parameter vmadminUsername
  Username of the administrator user in the container (defaults to sa)
 .Parameter adminPassword
  Password of the administrator user in the container (if using NavUserPassword authentication)
 .Example
  Compile-ObjectsToNavContainer -containerName test2 -adminPassword <adminpassword>
#>

function Compile-ObjectsInNavContainer {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName, 
        [string]$filter = "modified=Yes", 
        [string]$vmadminUsername = 'sa',
        [SecureString]$adminPassword = $null
    )

    $containerAuth = Get-NavContainerAuth -containerName $containerName
    if ($containerAuth -eq "NavUserPassword" -and !($adminPassword)) {
        $adminPassword = Get-DefaultAdminPassword
    }

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($filter, $vmadminUsername, $adminPassword)

        $customConfigFile = Join-Path (Get-Item "C:\Program Files\Microsoft Dynamics NAV\*\Service").FullName "CustomSettings.config"
        [xml]$customConfig = [System.IO.File]::ReadAllText($customConfigFile)
        $databaseServer = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseServer']").Value
        $databaseInstance = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseInstance']").Value
        $databaseName = $customConfig.SelectSingleNode("//appSettings/add[@key='DatabaseName']").Value
        if ($databaseInstance) { $databaseServer += "\$databaseInstance" }

        $creds = @{}
        if ($adminPassword) {
            $creds = @{ 'Username' = $vmadminUsername; 'Password' = ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($adminPassword))) }
        }
        Write-Host "Compiling objects"
        Compile-NAVApplicationObject @creds -Filter $filter `
                                     -DatabaseName $databaseName `
                                     -DatabaseServer $databaseServer `
                                     -Recompile `
                                     -SynchronizeSchemaChanges Force `
                                     -NavServerName localhost `
                                     -NavServerInstance NAV `
                                     -NavServerManagementPort 7045

    } -ArgumentList $filter, $vmadminUsername, $adminPassword
    Write-Host -ForegroundColor Green "Objects successfully compiled"
}
Export-ModuleMember -Function Compile-ObjectsInNavContainer

<#
 .Synopsis
  Publish Nav App to a Nav container
 .Description
  Copies the appFile to the container if necessary
  Creates a session to the Nav container and runs the Nav CmdLet Publish-NavApp in the container
 .Parameter containerName
  Name of the container in which you want to publish an app (default is navserver)
 .Parameter appFile
  Path of the app you want to publish
 .Parameter skipVerification
  Include this parameter if the app you want to publish is not signed
 .Example
  Publish-NavContainerApp -appFile c:\temp\myapp.app
 .Example
  Publish-NavContainerApp -containerName test2 -appFile c:\temp\myapp.app -skipVerification
#>

function Publish-NavContainerApp {
    Param(
        [string]$containerName = "navserver",
        [Parameter(Mandatory=$true)]
        [string]$appFile,
        [switch]$skipVerification
    )

    $containerAppFile = Get-NavContainerPath -containerName $containerName -path $appFile
    $copied = $false
    if ("$containerAppFile" -eq "") {
        $containerAppFile = Join-Path "c:\run" ([System.IO.Path]::GetFileName($appFile))
        Copy-FileToNavContainer -containerName $containerName -localPath $appFile -containerPath $containerAppFile
        $copied = $true
    }
    
    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($appFile, $skipVerification, $copied)
        Write-Host "Publishing app $appFile"
        Publish-NavApp -ServerInstance NAV -Path $appFile -SkipVerification:$SkipVerification
        if ($copied) { 
            Remove-Item $appFile -Force
        }
    } -ArgumentList $containerAppFile, $skipVerification, $copied
    Write-Host -ForegroundColor Green "App successfully published"
}
Export-ModuleMember -Function Publish-NavContainerApp

<#
 .Synopsis
  Sync Nav App in Nav container
 .Description
  Creates a session to the Nav container and runs the Nav CmdLet Sync-NavApp in the container
 .Parameter containerName
  Name of the container in which you want to install the app (default navserver)
 .Parameter appName
  Name of app you want to install in the container
 .Example
  Install-NavApp -containerName test2 -appName myapp
#>

function Sync-NavContainerApp {
    Param(
        [string]$containerName = "navserver",
        [Parameter(Mandatory=$true)]
        [string]$appName
    )
    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($appName)
        Write-Host "Synchronizing app $appFile"
        Sync-NavTenant -ServerInstance NAV -Tenant default -Force
        Sync-NavApp -ServerInstance NAV -Name $appName
    } -ArgumentList $appName
    Write-Host -ForegroundColor Green "App successfully synchronized"
}
Export-ModuleMember -Function Sync-NavContainerApp

<#
 .Synopsis
  Install Nav App in Nav container
 .Description
  Creates a session to the Nav container and runs the Nav CmdLet Install-NavApp in the container
 .Parameter containerName
  Name of the container in which you want to install the app (default navserver)
 .Parameter appName
  Name of app you want to install in the container
 .Example
  Install-NavApp -containerName test2 -appName myapp
#>

function Install-NavContainerApp {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$appName,
        [string]$containerName = "navserver"
    )

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($appName)
        Write-Host "Installing app $appName"
        Install-NavApp -ServerInstance NAV -Name $appName
    } -ArgumentList $appName
    Write-Host -ForegroundColor Green "App successfully installed"
}
Export-ModuleMember -Function Install-NavContainerApp

<#
 .Synopsis
  Uninstall Nav App in Nav container
 .Description
  Creates a session to the Nav container and runs the Nav CmdLet Uninstall-NavApp in the container
 .Parameter containerName
  Name of the container in which you want to uninstall the app (default navserver)
 .Parameter appName
  Name of app you want to uninstall in the container
 .Example
  Uninstall-NavApp -containerName test2 -appName myapp
#>

function UnInstall-NavContainerApp {
    Param(
        [string]$containerName = "navserver",
        [Parameter(Mandatory=$true)]
        [string]$appName
    )

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($appName)
        Write-Host "Uninstalling app $appName"
        Uninstall-NavApp -ServerInstance NAV -Name $appName
    } -ArgumentList $appName
    Write-Host -ForegroundColor Green "App successfully uninstalled"
}
Export-ModuleMember -Function UnInstall-NavContainerApp

<#
 .Synopsis
  Unpublish Nav App in Nav container
 .Description
  Creates a session to the Nav container and runs the Nav CmdLet Unpublish-NavApp in the container
 .Parameter containerName
  Name of the container in which you want to unpublish the app (default navserver)
 .Parameter appName
  Name of app you want to unpublish in the container
 .Example
  Unpublish-NavApp -containerName test2 -appName myapp
#>

function UnPublish-NavContainerApp {
    Param(
        [string]$containerName = "navserver",
        [Parameter(Mandatory=$true)]
        [string]$appName
    )

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { Param($appName)
        Write-Host "Unpublishing app $appName"
        Unpublish-NavApp -ServerInstance NAV -Name $appName
    } -ArgumentList $appName
    Write-Host -ForegroundColor Green "App successfully unpublished"
}
Export-ModuleMember -Function UnPublish-NavContainerApp

<#
 .Synopsis
  Get Nav App Info from Nav container
 .Description
  Creates a session to the Nav container and runs the Nav CmdLet Get-NavAppInfo in the container
 .Parameter containerName
  Name of the container in which you want to enumerate apps (default navserver)
 .Example
  Get-NavContainerAppInfo -containerName test2
#>

function Get-NavContainerAppInfo {
    Param(
        [string]$containerName = "navserver"
    )

    $session = Get-NavContainerSession -containerName $containerName
    Invoke-Command -Session $session -ScriptBlock { 
        Get-NavAppInfo -ServerInstance NAV
    } 
}
Export-ModuleMember -Function Get-NavContainerAppInfo

<#
 .Synopsis
  Copy the NavSip.dll Crypto Provider from a Container and install it locally
 .Description
  The NavSip crypto provider is used when signing extensions
  Extensions cannot be signed inside the container, they need to be signed on the host.
  Beside the NavSip.dll you also need the SignTool.exe which you get with Visual Studio.
 .Parameter containerName
  Name of the container from which you want to copy and install the NavSip.dll (default is navserver)
 .Example
  Install-NAVSipCryptoProviderFromNavContainer
#>

function Install-NAVSipCryptoProviderFromNavContainer {
    Param(
        [string]$containerName = "navserver"
    )

    $msvcr120Path = "C:\Windows\System32\msvcr120.dll"
    if (!(Test-Path $msvcr120Path)) {
        Copy-FileFromNavContainer -containerName $containerName -ContainerPath $msvcr120Path
    }

    $navSip64Path = "C:\Windows\System32\NavSip.dll"
    $navSip32Path = "C:\Windows\SysWow64\NavSip.dll"

    RegSvr32 /u /s $navSip64Path
    RegSvr32 /u /s $navSip32Path

    Log "Copy NAV SIP crypto provider from container $containerName"
    Copy-FileFromNavContainer -containerName $containerName -ContainerPath $navSip64Path
    Copy-FileFromNavContainer -containerName $containerName -ContainerPath $navSip32Path

    RegSvr32 /s $navSip32Path
    RegSvr32 /s $navSip64Path
}
Export-ModuleMember -Function Install-NAVSipCryptoProviderFromNavContainer

<#
 .Synopsis
  Replace navserver container with a different image
 .Description
  This command is designed to be used in the Azure VMs, where the main container (mapped to public ip) is called navserver.
  Running this command will replace the container with a new container with a different (or the same) image.
 .Parameter imageName
  imageName you want to use to replace the navserver container
 .Parameter certificatePfxUrl
  Secure Url to certificate Pfx file to be used with the container (leave empty to create a self-signed certificate)
 .Parameter certificatePfxPassword
  Password for certificate Pfx file to be used with the container (leave empty to create a self-signed certificate)
 .Parameter publicDnsName
  Public Dns name (CNAME record) pointing to the host machine
 .Example
  Replace-NavServerContainer -imageName navdocker.azurecr.io/dynamics-nav:devpreview-september-finus
 .Example
  Replace-NavServerContainer -imageName navdocker.azurecr.io/dynamics-nav:devpreview-september-fingb -certificatePfxUrl <secureurl> -certificatePfxPassword <password> -publicDnsName myhost.navdemo.net
#>

function Replace-NavServerContainer {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$imageName, 
        [string]$certificatePfxUrl = "", 
        [string]$certificatePfxPassword = "", 
        [string]$publicDnsName = ""
    )

    $SetupNavContainerScript = "c:\demo\SetupNavContainer.ps1"
    $setupDesktopScript = "c:\demo\SetupDesktop.ps1"

    if (!((Test-Path $SetupNavContainerScript) -and (Test-Path $setupDesktopScript))) {
        throw "The Replace-NavServerContainer is designed to work inside the Nav on Azure DEMO VMs"
    }

    $newImageName = $imageName
    $newCertificatePfxUrl = $certificatePfxUrl
    $newCertificatePfxPassword = $certificatePfxPassword
    $newPublicDnsName = $publicDnsName

    . C:\DEMO\Settings.ps1

    if ($newCertificatePfxUrl -ne "" -and $newCertificatePfxPassword -ne "" -and $newPublicDnsName -ne "") {
        Download-File -sourceUrl $newCertificatePfxUrl -destinationFile "c:\demo\certificate.pfx"
    
        ('$certificatePfxPassword = "'+$newCertificatePfxPassword+'"
        $certificatePfxFile = "c:\demo\certificate.pfx"
        $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certificatePfxFile, $certificatePfxPassword)
        $certificateThumbprint = $cert.Thumbprint
        Write-Host "Certificate File Thumbprint $certificateThumbprint"
        if (!(Get-Item Cert:\LocalMachine\my\$certificateThumbprint -ErrorAction SilentlyContinue)) {
            Write-Host "Import Certificate to LocalMachine\my"
            Import-PfxCertificate -FilePath $certificatePfxFile -CertStoreLocation cert:\localMachine\my -Password (ConvertTo-SecureString -String $certificatePfxPassword -AsPlainText -Force) | Out-Null
        }
        $dnsidentity = $cert.GetNameInfo("SimpleName",$false)
        if ($dnsidentity.StartsWith("*")) {
            $dnsidentity = $dnsidentity.Substring($dnsidentity.IndexOf(".")+1)
        }
        Remove-Item $certificatePfxFile -force
        Remove-Item "c:\run\my\SetupCertificate.ps1" -force
        '
) | Add-Content "c:\myfolder\SetupCertificate.ps1"
    } else {
        # Self signed cert. - use hostname as publicDnsName
        $newPublicDnsName = $hostname
    }

    $imageId = docker images -q $newImageName
    if (!($imageId)) {
        Write-Host "pulling $newImageName"
        docker pull $newImageName
    }
    $country = Get-NavContainerCountry -containerOrImageName $newImageName

    if (Test-NavContainer -containerName navserver) {
        Write-Host "Remove container navserver"
        Remove-NavContainerSession -containerName $containerName
        $containerId = Get-NavContainerId -containerName $containerName
        docker rm $containerId -f | Out-Null
    }
    
    $settingsScript = "c:\demo\settings.ps1"
    $settings = Get-Content -Path  $settingsScript
    0..($settings.Count-1) | % { if ($settings[$_].StartsWith('$navDockerImage = ', "OrdinalIgnoreCase")) { $settings[$_] = ('$navDockerImage = "'+$newImageName + '"') } }
    Set-Content -Path $settingsScript -Value $settings

    Write-Host -ForegroundColor Green "Setup new Nav container"
    . $SetupNavContainerScript
    . $setupDesktopScript
}
Export-ModuleMember -Function Replace-NavServerContainer

<#
 .Synopsis
  Replace navserver container with the same image
 .Description
  This command is designed to be used in the Azure VMs, where the main container (mapped to public ip) is called navserver.
  Running this command will replace the container with a new container using the same image - recreateing or refreshing the container.
 .Parameter certificatePfxUrl
  Secure Url to certificate Pfx file to be used with the container (leave empty to create a self-signed certificate)
 .Parameter certificatePfxPassword
  Password for certificate Pfx file to be used with the container (leave empty to create a self-signed certificate)
 .Parameter publicDnsName
  Public Dns name (CNAME record) pointing to the host machine
 .Example
  Recreate-NavServerContainer
 .Example
  Recreate-NavServerContainer -certificatePfxUrl <secureurl> -certificatePfxPassword <password> -publicDnsName myhost.navdemo.net
#>

function Recreate-NavServerContainer {
    Param(
        [string]$certificatePfxUrl = "", 
        [string]$certificatePfxPassword = "", 
        [string]$publicDnsName = ""
    )

    $imageName = Get-NavContainerImageName -containerName navserver
    Replace-NavServerContainer -imageName $imageName -certificatePfxUrl $certificatePfxUrl -certificatePfxPassword $certificatePfxPassword -publicDnsName $publicDnsName
}
Export-ModuleMember -Function Recreate-NavServerContainer

function New-DesktopShortcut {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$Name, 
        [Parameter(Mandatory=$true)]
        [string]$TargetPath, 
        [string]$WorkingDirectory = "", 
        [string]$IconLocation = "", 
        [string]$Arguments = "",
        [string]$FolderName = "Desktop",
        [switch]$RunAsAdministrator = $true
    )
    $filename = Join-Path ([Environment]::GetFolderPath($FolderName)) "$Name.lnk"
    if (Test-Path -Path $filename) {
        Remove-Item $filename -force
    }

    $Shell =  New-object -comobject WScript.Shell
    $Shortcut = $Shell.CreateShortcut($filename)
    $Shortcut.TargetPath = $TargetPath
    if (!$WorkingDirectory) {
        $WorkingDirectory = Split-Path $TargetPath
    }
    $Shortcut.WorkingDirectory = $WorkingDirectory
    if ($Arguments) {
        $Shortcut.Arguments = $Arguments
    }
    if ($IconLocation) {
        $Shortcut.IconLocation = $IconLocation
    }
    $Shortcut.save()
    if ($RunAsAdministrator) {
        $bytes = [System.IO.File]::ReadAllBytes($filename)
        $bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
        [System.IO.File]::WriteAllBytes($filename, $bytes)
    }
}
Export-ModuleMember New-DesktopShortcut

function Remove-DesktopShortcut {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$Name,
        [string]$FolderName = "Desktop"
    )
    $filename = Join-Path ([Environment]::GetFolderPath($FolderName)) "$Name.lnk"
    if (Test-Path -Path $filename) {
        Remove-Item $filename -force
    }
}
Export-ModuleMember Remove-DesktopShortcut

function Write-NavContainerHelperWelcomeText {
    clear
    Write-Host -ForegroundColor Yellow "Welcome to the Nav Container Helper PowerShell Prompt"
    Write-Host
    Write-Host -ForegroundColor Yellow "Container info functions"
    Write-Host "Get-NavContainerNavVersion Get Nav version from Nav Container"
    Write-Host "Get-NavContainerImageName Get ImageName from Nav container"
    Write-Host "Get-NavContainerGenericTag Get Nav generic image tag from Nav container"
    Write-Host "Get-NavContainerOsVersion Get OS version from Nav container"
    Write-Host "Get-NavContainerLegal Get Legal link from Nav container"
    Write-Host "Get-NavContainerCountry Get Localization version from Nav Container"
    Write-Host "Get-NavContainerIpAddress Get IP Address to a Nav container"
    Write-Host "Get-NavContainerSharedFolders Get Shared Folders from a Nav container"
    Write-Host "Get-NavContainerPath Get the path inside a Nav container to a shared file"
    Write-Host "Get-NavContainerName Get the name of a Nav container"
    Write-Host "Get-NavContainerId Get the Id of a Nav container"
    Write-Host "Test-NavContainer Test whether a Nav container exists"
    Write-Host
    Write-Host -ForegroundColor Yellow "Container handling functions"
    Write-Host "New-NavContainer Create new Nav container"
    Write-Host "New-CSideDevContainer Create new C/SIDE development container"
    Write-Host "Remove-NavContainer Remove Nav container"
    Write-Host "Get-NavContainerSession Create new session to a Nav container"
    Write-Host "Remove-NavContainerSession Remove Nav container session"
    Write-Host "Enter-NavContainer Enter Nav container session"
    Write-Host "Open-NavContainer Open Nav container in new window"
    Write-Host "Wait-NavContainerReady Wait for Nav Container to become ready"
    Write-Host
    Write-Host -ForegroundColor Yellow "Object handling functions"
    Write-Host "Import-ObjectsToNavContainer Import objects from .txt or .fob file"
    Write-Host "Import-DeltasToNavContainer Merge delta files and Import objects"
    Write-Host "Compile-ObjectsInNavContainer Compile objects"
    Write-Host "Export-NavContainerObjects Export objects from Nav container"
    Write-Host "Create-MyOriginalFolder Create folder with the original objects for modified objects"
    Write-Host "Create-MyDeltaFolder Create folder with deltas for modified objects"
    Write-Host "Convert-Txt2Al Convert deltas folder to al folder"
    Write-Host "Export-ModifiedObjectsAsDeltas Export objects, create baseline and create deltas"
    Write-Host "Convert-ModifiedObjectsToAl Export objects, create baseline, create deltas and convert to .al files"
    Write-Host
    Write-Host -ForegroundColor Yellow "App handling functions"
    Write-Host "Publish-NavContainerApp Publish App to Nav container"
    Write-Host "Sync-NavContainerApp Sync App in Nav container"
    Write-Host "Install-NavContainerApp Install App in Nav container"
    Write-Host "Uninstall-NavContainerApp Uninstall App from Nav container"
    Write-Host "Unpublish-NavContainerApp Unpublish App from Nav container"
    Write-Host "Get-NavContainerAppInfo Get info about installed apps from Nav Container"
    Write-Host "Install-NAVSipCryptoProviderFromNavContainer Install Nav Sip Crypto Provider locally from container to sign extensions"
    Write-Host
    Write-Host -ForegroundColor Yellow "Azure VM specific functions"
    Write-Host "Replace-NavServerContainer Replace navserver (primary) container"
    Write-Host "Recreate-NavServerContainer Recreate navserver (primary) container"
    Write-Host
    Write-Host -ForegroundColor White "Note: The Nav Container Helper is an open source project from http://www.github.com/microsoft/navcontainerhelper."
    Write-Host -ForegroundColor White "The project is released as-is, no warranty! Contributions are welcome, study the github repository for usage."
    Write-Host -ForegroundColor White "Report issues on http://www.github.com/microsoft/navcontainerhelper/issues."
    Write-Host
}
Export-ModuleMember Write-NavContainerHelperWelcomeText

function Download-File {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$sourceUrl,
        [Parameter(Mandatory=$true)]
        [string]$destinationFile
    )

    Write-Host "Downloading $destinationFile"
    Remove-Item -Path $destinationFile -Force -ErrorAction Ignore
    (New-Object System.Net.WebClient).DownloadFile($sourceUrl, $destinationFile)
}
Export-ModuleMember Download-File

function Get-LocaleFromCountry {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$country
    )

    $locales = @{
        "finus" = "en-US"
        "finca" = "en-CA"
        "fingb" = "en-GB"
        "findk" = "da-DK"
        "at"    = "de-AT"
        "au"    = "en-AU" 
        "be"    = "nl-BE"
        "ch"    = "de-CH"
        "cz"    = "cs-CZ"
        "de"    = "de-DE"
        "dk"    = "da-DK"
        "es"    = "es-ES"
        "fi"    = "fi-FI"
        "fr"    = "fr-FR"
        "gb"    = "en-GB"
        "in"    = "en-IN"
        "is"    = "is-IS"
        "it"    = "it-IT"
        "na"    = "en-US"
        "nl"    = "nl-NL"
        "no"    = "nb-NO"
        "nz"    = "en-NZ"
        "ru"    = "ru-RU"
        "se"    = "sv-SE"
        "w1"    = "en-US"
        "us"    = "en-US"
        "mx"    = "es-MX"
        "ca"    = "en-CA"
        "dech"  = "de-CH"
        "frbe"  = "fr-BE"
        "frca"  = "fr-CA"
        "frch"  = "fr-CH"
        "itch"  = "it-CH"
        "nlbe"  = "nl-BE"
    }

    return $locales[$country]
}
Export-ModuleMember Get-LocaleFromCountry

function Copy-FileFromNavContainer {

    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName,
        [Parameter(Mandatory=$true)]
        [string]$containerPath,
        [Parameter(Mandatory=$false)]
        [string]$localPath = $containerPath
    )

    Process {
        if (!(Test-NavContainer -containerName $containerName)) {
            throw "Container $containerName does not exist"
        }
        Log "Copy from container $containerName ($containerPath) to $localPath"
        $id = Get-NavContainerId -containerName $containerName 
        docker cp ${id}:$containerPath $localPath
    }
}
Export-ModuleMember Copy-FileFromNavContainer

function Copy-FileToNavContainer {

    Param(
        [Parameter(Mandatory=$true)]
        [string]$containerName,
        [Parameter(Mandatory=$true)]
        [string]$localPath,
        [Parameter(Mandatory=$false)]
        [string]$containerPath = $localPath
    )

    Process {
        if (!(Test-NavContainer -containerName $containerName)) {
            throw "Container $containerName does not exist"
        }
        Log "Copy $localPath to container ${containerName} ($containerPath)"
        $id = Get-NavContainerId -containerName $containerName 
        docker cp $localPath ${id}:$containerPath
    }
}
Export-ModuleMember Copy-FileToNavContainer