Skip to content

Import hardware from Excel

Introduction

The Export-VmsHardware and Import-VmsHardware cmdlets in MilestonePSTools offer a way to export your camera/device configuration to a generic CSV file format, and import cameras into your VMS from CSV. However, there are a lot of configuration options available on any given device, and it's difficult to represent all the settings available in a single CSV file structure.

This guide introduces an alternative using Doug Finke's ImportExcel module which makes exporting and importing data using the .XLSX file format as easy as piping your data to Export-Excel and Import-Excel. Even if you don't have Excel installed on the machine from which you're running PowerShell!

Download VmsImportHardwareExcel.psm1 script module from the link below and read on for more information about this import/export script and how to use it.

Download script

Sample worksheet

Hardware worksheet

HardwareGeneralSettings worksheet

Cameras worksheet

CameraGeneralSettings worksheet

CameraStreams worksheet

CameraStreamSettings worksheet

CameraEvents worksheet

Microphones worksheet

MicrophoneGeneralSettings worksheet

MicrophoneEvents worksheet

Speakers worksheet

SpeakerGeneralSettings worksheet

Metadata worksheet

MetadataGeneralSettings worksheet

Inputs worksheet

InputGeneralSettings worksheet

InputEvents worksheet

Outputs worksheet

Download sample

Usage

Download the script module

To use this script module, download it from the link above and save it to C:\Users\<user>\Documents\WindowsPowerShell\Modules\VmsImportHardwareExcel\VmsImportHardwareExcel.psm1 for the current user, or C:\Program Files\WindowsPowerShell\Modules\VmsImportHardwareExcel\VmsImportHardwareExcel.psm1 to make it available to all users.

Technically you can save it anywhere you like, but if you place it in one of the paths PowerShell uses to automatically import modules, it'll save you from having to manually call Import-Module with the full path to the file later.

Install ImportExcel

Since this script module is not published to, and installed from PowerShell Gallery, the ImportExcel module will not be installed automatically. To install it, use the command below and I encourage you to check out the ImportExcel GitHub repository for more information about this Excel-lent module!

Install-Module ImportExcel -Scope CurrentUser -Force

Get-Help

The two cmdlets exported by this script module include comment-based help. Use Get-Help Export-VmsHardwareExcel -Full and Get-Help Export-VmsHardwareExcel -Full to see descriptions of the parameters, and examples.

Export existing hardware

To export all enabled hardware and devices, you can run the following in PowerShell and you should end up with a file named something like hardware_2023-02-18_10-30-22.xlsx on your desktop.

Connect-ManagementServer -ShowDialog -AcceptEula -Force
$timestamp = Get-Date -Format 'yyyy-MM-dd_HH-mm-ss'
Export-VmsHardwareExcel -Path "~\Desktop\hardware_$timestamp.xlsx" -IncludedDevices Cameras, Microphones, Speakers, Inputs, Outputs, Metadata -Verbose

Import changes

Note

You should perform a configuration (SQL) backup before using any tools like this in a production environment. When possible, you should also test this in a test environment.

Open the exported .XLSX file from the previous step and make a change to a setting. For example, change the frame rate of a camera, add coordinates, or adjust the prebuffer time.

If you change the names of any devices, it's important that you find and replace all references to the old name. The reason is that the parent device names are included in each worksheet to help the import script figure out with which recording server and hardware the camera row is associated. The CameraStreams worksheet references the parent camera, hardware, and recording server for instance.

Next, you can try importing those changes.

Import-VmsHardwareExcel -UpdateExisting -Verbose

Since the -Path parameter was not provided, an open-file dialog will be displayed allowing you to locate the file you exported in the previous step.

Adding new hardware

New hardware can be added using an Excel file with a single worksheet named "Hardware", if all you care about is getting the hardware added to a recording server so that you can configure it later. In fact, if you do it this way you can do an export afterward, modify the settings in the export, and then import the changes. This would save you from trying to construct all of the worksheets with their columns and values yourself.

The columns can be in any order, and are case-insensitive. The minimum required columns on the Hardware worksheet are:

  • Name
  • The display name to give the hardware after it is added.
  • Address
  • The hardware address in URL form. For example, http://10.10.10.100/
  • UserName
  • Password
  • RecordingServer
  • This should be the display name of the recording server on which to add the hardware.

Additional, optional columns include:

  • Enabled
  • Values: True | False
  • Description
  • DriverNumber
  • Adding hardware goes a lot faster if you know the driver number. This number is shown in the supported hardware list on milestonesys.com
  • DriverGroup
  • This is the name of a group of cameras seen in Management Client when adding cameras. Some examples of known group names include "AXIS", "Bosch", "Hanwha", "Milestone", and "ONVIF". If you don't know the DriverNumber, you can provide DriverGroup instead, and the recording server will attempt to discover the correct driver from the list of drivers under that group.

With your Excel file prepared, you can import new hardware by calling the Import-VmsHardwareExcel command with or without any parameters. If you're not logged in the the VMS yet, you will be prompted with a login dialog. And if you do not provide a value for -Path, an open-file dialog will be displayed.

Notes

The standalone VmsImportHardwareExcel.psm1 script module provided in this guide is not a part of the MilestonePSTools module, but it does depend on it, along with the ImportExcel module. The script module is provided separately for a couple important reasons.

Limited testing

These import/export functions have undergone some limited internal testing, and while they have proven useful in a few professional services projects, we don't consider them "complete", or ready for the broader community to rely on.

Opinionated

This script takes an opinionated approach to getting hardware configuration in, and out of the XProtect VMS. Our goal for MilestonePSTools is to provide a PowerShell-friendly interface to the MIP SDK, making it possible for you to build tools, applications, and services around your needs rather than imposing our opinions and making assumptions about what you want.

Building out tools like this script requires a lot of time and testing, and once features are added to the MilestonePSTools module there is an implicit expectation that the feature always works, and will be supported the same as any other feature of the module. We're not ready to commit to that, but we do want to make the tool available for those who can benefit from it and accept the risk of using a "beta" tool.

Script

VmsImportHardwareExcel.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
#Requires -Module @{ ModuleName="ImportExcel"; ModuleVersion="7.8" }, @{ ModuleName="MilestonePSTools"; ModuleVersion="22.3.1" }

#region private

function Show-FileDialog {
    [CmdletBinding(DefaultParameterSetName = 'OpenFile')]
    param (
        [Parameter(ParameterSetName = 'OpenFile')]
        [switch]
        $OpenFile,

        [Parameter(Mandatory, ParameterSetName = 'SaveFile')]
        [switch]
        $SaveFile
    )

    process {
        $params = @{
            Title            = 'ImportVmsHardwareExcel'
            Filter           = 'Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*'
            DefaultExt       = '.xlsx'
            RestoreDirectory = $true
            AddExtension     = $true
        }
        switch ($PSCmdlet.ParameterSetName) {
            'OpenFile' {
                $dialog = [System.Windows.Forms.OpenFileDialog]$params
            }
            'SaveFile' {
                $params.FileName = 'Hardware_{0}.xlsx' -f (Get-Date -Format 'yyyy-MM-dd_HH-mm-ss')
                $dialog = [System.Windows.Forms.SaveFileDialog]$params
            }
            Default {
                throw "ParameterSetName '$_' not implemented."
            }
        }

        try {
            $form = [system.windows.forms.form]@{
                TopMost = $true
            }
            if ($dialog.ShowDialog($form) -eq 'OK') {
                $dialog.FileName
            } else {
                throw "$($PSCmdlet.ParameterSetName) aborted."
            }
        } finally {
            if ($dialog) {
                $dialog.Dispose()
            }
            if ($form) {
                $form.Dispose()
            }
        }
    }
}

function Resolve-Path2 {
    <#
    .SYNOPSIS
    Resolves paths like the PowerShell-native `Resolve-Path` cmdlet, even for
    paths that don't exist yet.

    .DESCRIPTION
    Long description

    .PARAMETER Path
    Parameter description

    .PARAMETER LiteralPath
    Parameter description

    .PARAMETER Relative
    Parameter description

    .PARAMETER NoValidation
    If the path does not exist, return the resolved path anyway.

    .PARAMETER ExpandEnvironmentVariables
    If a path contains CMD-style variables like "%appdata%\Roaming"

    .EXAMPLE
    An example

    .NOTES
    Inspired by a [blog post](http://devhawk.net/blog/2010/1/22/fixing-powershells-busted-resolve-path-cmdlet)
    by DevHawk, aka Harry Pierson, linked to by joshuapoehls on [stackoverflow.com](https://stackoverflow.com/a/12605755/3736007).
    #>
    [CmdletBinding(DefaultParameterSetName = 'Path')]
    [OutputType([string])]
    param (
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0, ParameterSetName = 'Path')]
        [SupportsWildcards()]
        [string[]]
        $Path,

        [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'LiteralPath')]
        [string[]]
        $LiteralPath,

        [Parameter()]
        [switch]
        $Relative,

        [Parameter()]
        [switch]
        $NoValidation,

        [Parameter(ParameterSetName = 'Path')]
        [switch]
        $ExpandEnvironmentVariables
    )

    process {
        foreach ($unresolvedPath in $MyInvocation.BoundParameters[$PSCmdlet.ParameterSetName]) {
            if ($ExpandEnvironmentVariables) {
                $unresolvedPath = [environment]::ExpandEnvironmentVariables($unresolvedPath)
            }
            $params = @{
                $($PSCmdlet.ParameterSetName) = $unresolvedPath
                ErrorAction                   = 'SilentlyContinue'
                ErrorVariable                 = 'resolvePathError'
            }
            $resolvedPath = Resolve-Path @params
            if ($null -eq $resolvedPath) {
                if ($NoValidation) {
                    $resolvedPath = $resolvePathError[0].TargetObject
                } elseif ($resolvePathError) {
                    Write-Error -ErrorRecord $resolvePathError[0]
                    Remove-Variable -Name resolvePathError
                    continue
                }
            }

            foreach ($pathInfo in $resolvedPath) {
                if ($Relative) {
                    $separator = [io.path]::DirectorySeparatorChar
                    $currentPathUri = [uri]::new($pwd.Path, [System.UriKind]::Absolute)
                    #$currentPathUri = [uri]::new(($pwd.Path -replace "([^$([regex]::Escape($separator))])`$", "`$1$([regex]::Escape($separator))"), [System.UriKind]::Absolute)
                    #$resolvedPathUri = [uri]::new($pathInfo.Path, [System.UriKind]::Absolute)
                    $resolvedPathUri = [uri]::new(($pathInfo.Path -replace "([^$([regex]::Escape($separator))])`$", "`$1$([regex]::Escape($separator))"), [System.UriKind]::Absolute)
                    $relativePath = $currentPathUri.MakeRelativeUri($resolvedPathUri).ToString() -replace '/', [io.path]::DirectorySeparatorChar
                    if ($relativePath -notmatch "^\.+\$([io.path]::DirectorySeparatorChar)") {
                        $relativePath = '.{0}{1}' -f [io.path]::DirectorySeparatorChar, $relativePath
                    }
                    $relativePath
                } else {
                    $pathInfo
                }
            }
        }
    }
}

function Get-DeviceEvents {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.IConfigurationItem]
        $Device
    )

    begin {
        $validDeviceTypes = @('Hardware', 'Camera', 'Microphone', 'Speaker', 'InputEvent')
    }

    process {
        $devicePath = [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($Device.Path)
        $itemType = $devicePath.ItemType
        if ($itemType -notin $validDeviceTypes) {
            Write-Error "Invalid device type for this cmdlet."
            return
        }

        $deviceEvents = (Get-ConfigurationItem -Path ('HardwareDeviceEvent[{0}]' -f $Device.Id)).Children
        foreach ($deviceEvent in $deviceEvents) {
            [pscustomobject]@{
                Event      = $deviceEvent.DisplayName
                Used       = ($deviceEvent.Properties | Where-Object Key -eq 'EventUsed').Value -eq 'True'
                Enabled    = $deviceEvent.EnableProperty.Enabled
                EventIndex = ($deviceEvent.Properties | Where-Object Key -eq 'EventIndex').Value
                IndexName  = ($deviceEvent.Properties | Where-Object Key -eq 'EventIndex').DisplayName
            }
        }
    }
}

function Get-DeviceProperties {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.IConfigurationItem]
        $Device
    )

    begin {
        $excludedProperties = 'Icon', 'ItemCategory', 'Methods', 'ServerId', 'CreatedDate', 'DisplayName', 'ParentItemPath', 'StreamDefinitions', 'StreamUsages'
        $orderPriority = 'Name', 'ShortName', 'HostName', 'WebServerUri', 'Address', 'UserName', 'Password', 'Enabled', 'Channel', 'GisPoint', 'ActiveWebServerUri', 'PublicAccessEnabled', 'PublicWebserverHostName', 'PublicWebserverPort'
        $rearOrderPriority = 'LastModified', 'Id'

        $pathNameMap = @{}
        $childToParentMap = @{}
        $recordingStorage = @{}
        Get-VmsRecordingServer -PipelineVariable rec | Get-VmsStorage | Foreach-Object {
            $recordingStorage[$_.Path] = $_
            $pathNameMap[$_.Path] = $_.Name
            $pathNameMap[$rec.Path] = $rec.Name
            $childToParentMap[$_.Path] = $rec.Path
        }

        # Use translations to take an existing device property/value, and modify the column name and value in some way.
        # For example, the GisPoint property has a name unfamiliar to most users, and the "POINT(X Y)" value is even more unfamiliar.
        # Also useful for translating a config API path like "Storage[guid]" to the name of that storage.
        $translations = @{
            'GisPoint'         = {
                @{
                    Name  = 'Coordinates'
                    Value = $_.GisPoint | ConvertFrom-GisPoint
                }
            }
            'RecordingStorage' = {
                @{
                    Name  = 'Storage'
                    Value = $recordingStorage[$_.RecordingStorage].Name
                }
            }
        }

        # Properties to be added. Keys represent the name of a property after which these new properties will be added. Each scriptblock can return one or more Name/Value pairs
        $additionalProperties = @{
            'UserName'               = {
                [pscustomobject]@{
                    Name  = 'Password'
                    Value = try { $_ | Get-HardwarePassword -ErrorAction SilentlyContinue } catch {}
                }
            }

            'RecordOnRelatedDevices' = {
                $motion = $_.MotionDetectionFolder.MotionDetections[0]
                [pscustomobject]@{ Name = 'MotionEnabled'; Value = $motion.Enabled }
                [pscustomobject]@{ Name = 'MotionManualSensitivityEnabled'; Value = $motion.ManualSensitivityEnabled }
                [pscustomobject]@{ Name = 'MotionManualSensitivity'; Value = $motion.ManualSensitivity }
                [pscustomobject]@{ Name = 'MotionThreshold'; Value = $motion.Threshold }
                [pscustomobject]@{ Name = 'MotionKeyframesOnly'; Value = $motion.KeyframesOnly }
                [pscustomobject]@{ Name = 'MotionProcessTime'; Value = $motion.ProcessTime }
                [pscustomobject]@{ Name = 'MotionDetectionMethod'; Value = $motion.DetectionMethod }
                [pscustomobject]@{ Name = 'MotionGenerateMotionMetadata'; Value = $motion.GenerateMotionMetadata }
                [pscustomobject]@{ Name = 'MotionUseExcludeRegions'; Value = $motion.UseExcludeRegions }
                [pscustomobject]@{ Name = 'MotionGridSize'; Value = $motion.GridSize }
                [pscustomobject]@{ Name = 'MotionHardwareAccelerationMode'; Value = $motion.HardwareAccelerationMode }
            }

            'Channel'                = {
                $hwId = [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.ParentItemPath).Id
                $hw = [VideoOS.Platform.Configuration]::Instance.GetItem($hwId , [VideoOS.Platform.Kind]::Hardware)
                [pscustomobject]@{
                    Name  = 'Address'
                    Value = $hw.Properties.Address
                }
                [pscustomobject]@{
                    Name  = 'Hardware'
                    Value = $hw.Name
                }
                [pscustomobject]@{
                    Name  = 'RecordingServer'
                    Value = $pathNameMap["RecordingServer[$($hw.FQID.ServerId.Id)]"]
                }
            }

            # Add driver and recording server info after model column for hardware objects
            'Model'                  = {
                if ($hwSettings = ($_ | Get-HardwareSetting -ErrorAction SilentlyContinue)) {
                    [pscustomobject]@{
                        Name  = 'MACAddress'
                        Value = $hwSettings.MacAddress
                    }
                    [pscustomobject]@{
                        Name  = 'SerialNumber'
                        Value = $hwSettings.SerialNumber
                    }
                    [pscustomobject]@{
                        Name  = 'FirmwareVersion'
                        Value = $hwSettings.FirmwareVersion
                    }
                }
                if ($driver = ($_ | Get-VmsHardwareDriver -ErrorAction SilentlyContinue)) {
                    [pscustomobject]@{
                        Name  = 'DriverNumber'
                        Value = $driver.Number
                    }
                    [pscustomobject]@{
                        Name  = 'DriverGroup'
                        Value = $driver.GroupName
                    }
                    [pscustomobject]@{
                        Name  = 'DriverDriverType'
                        Value = $driver.DriverType
                    }
                    [pscustomobject]@{
                        Name  = 'DriverVersion'
                        Value = $driver.DriverVersion
                    }
                    [pscustomobject]@{
                        Name  = 'DriverRevision'
                        Value = $driver.DriverRevision
                    }
                }
                [pscustomobject]@{
                    Name  = 'RecordingServer'
                    Value = $pathNameMap[$_.ParentItemPath]
                }
            }
        }
    }

    process {
        $properties = ($Device | Get-Member -MemberType Property | Where-Object { $_.Name -notlike '*Folder' -and $_.Name -notlike '*Path' -and $_.Name -notin $excludedProperties }).Name

        $obj = [ordered]@{}
        foreach ($property in $orderPriority) {
            if ($null -ne $Device.$property) {
                if ($translations.ContainsKey($property)) {
                    $translations[$property].Invoke($Device) | Foreach-Object {
                        $obj.Add($_.Name, $_.Value)
                    }
                } else {
                    $obj.Add($property, $Device.$property)
                }
                if ($additionalProperties.ContainsKey($property)) {
                    $additionalProperties[$property].Invoke($Device) | Foreach-Object {
                        $obj.Add($_.Name, $_.Value)
                    }
                }
            }
        }
        foreach ($property in $properties | Where-Object { $_ -notin $orderPriority -and $_ -notin $rearOrderPriority }) {
            if ($translations.ContainsKey($property)) {
                $translations[$property].Invoke($Device) | Foreach-Object {
                    $obj.Add($_.Name, $_.Value)
                }
            } else {
                $obj.Add($property, $Device.$property)
            }
            if ($additionalProperties.ContainsKey($property)) {
                $additionalProperties[$property].Invoke($Device) | Foreach-Object {
                    $obj.Add($_.Name, $_.Value)
                }
            }
        }
        foreach ($property in $rearOrderPriority) {
            if ($null -ne $Device.$property) {
                if ($translations.ContainsKey($property)) {
                    $translations[$property].Invoke($Device) | Foreach-Object {
                        $obj.Add($_.Name, $_.Value)
                    }
                } else {
                    $obj.Add($property, $Device.$property)
                }
                if ($additionalProperties.ContainsKey($property)) {
                    $additionalProperties[$property].Invoke($Device) | Foreach-Object {
                        $obj.Add($_.Name, $_.Value)
                    }
                }
            }
        }
        [pscustomobject]$obj
    }
}

function Get-GeneralSettings {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.IConfigurationItem]
        $Device
    )

    begin {
        $validDeviceTypes = @('Hardware', 'Camera', 'Microphone', 'Speaker', 'InputEvent', 'Output', 'Metadata')
    }

    process {
        $commonProperties = [ordered]@{}
        $devicePath = [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($Device.Path)
        $parentPath = [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($Device.ParentItemPath)
        if ($devicePath.ItemType -notin $validDeviceTypes) {
            Write-Error "Invalid device type for this cmdlet."
            return
        }

        switch ($parentPath.ItemType) {
            'Hardware' {
                $hwItem = [videoos.platform.configuration]::Instance.GetItem($parentPath.Id, [videoos.platform.kind]::Hardware)
                $recorderItem = [videoos.platform.configuration]::Instance.GetItem($hwItem.FQID.ServerId.Id, [videoos.platform.kind]::Server)
                $commonProperties['RecordingServer'] = $recorderItem.Name
                $commonProperties['Hardware'] = $hwItem.Name
            }

            'RecordingServer' {
                $recorderItem = [videoos.platform.configuration]::Instance.GetItem($parentPath.Id, [videoos.platform.kind]::Server)
                $commonProperties['RecordingServer'] = $recorderItem.Name
            }
            Default {}
        }
        $commonProperties[$devicePath.ItemType] = $Device.Name
        if ($null -ne $Device.Channel) {
            $commonProperties['Channel'] = $Device.Channel
        }

        $itemType = if ($devicePath.ItemType -eq 'Hardware') { 'Hardware' } else { 'Device' }
        Get-ConfigurationItem -Path "$($itemType)DriverSettings[$($Device.Id)]" | Select-Object -ExpandProperty Children | Where-Object ItemType -eq "$($itemType)DriverSettings" | Select-Object -ExpandProperty Properties | Foreach-Object {
            $property = $_
            $displayValue = ($property.ValueTypeInfos | Where-Object Value -eq $property.Value).Name
            $key = $property.Key
            if ($key -match '^([^/]+/)(?<key>[^/]+)(/[^/]+)?$') {
                $key = $Matches.key
            }
            $row = [ordered]@{}
            $commonProperties.Keys | Foreach-Object { $row[$_] = $commonProperties[$_] }
            $row.Setting = $key
            $row.Value = $property.Value
            $row.DisplayValue = if ($property.ValueType -eq 'Enum' -and $displayValue -ne $property.Value) { $displayValue } else { $null }
            $row.ReadOnly = !$property.IsSettable
            [pscustomobject]$row
        }
    }
}

function Set-DeviceEvents {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.IConfigurationItem]
        $Device,

        [Parameter(Mandatory)]
        [pscustomobject[]]
        $Settings
    )

    begin {
        $validDeviceTypes = @('Hardware', 'Camera', 'Microphone', 'Speaker', 'InputEvent')
    }

    process {
        $devicePath = [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($Device.Path)
        $itemType = $devicePath.ItemType
        if ($itemType -notin $validDeviceTypes) {
            Write-Error "Invalid device type for this cmdlet."
            return
        }

        $item = Get-ConfigurationItem -Path ('HardwareDeviceEvent[{0}]' -f $Device.Id)
        foreach ($eventRow in $Settings) {
            $deviceEvent = $item.Children | Where-Object DisplayName -eq $eventRow.EventName | Select-Object -First 1
            if ($deviceEvent) {
                $deviceEvent.EnableProperty.Enabled = $eventRow.Enabled.ToString() -eq 'True' # In case the column is treated like a string, we'll make sure to do a string comparison.
                $deviceEvent.Properties | Where-Object Key -eq 'EventUsed' | ForEach-Object { $_.Value = $eventRow.Used.ToString() -eq 'True' }
                $deviceEvent.Properties | Where-Object Key -eq 'EventIndex' | ForEach-Object { $_.Value = $eventRow.EventIndex }
            } else {
                Write-Warning "Device '$($Hardware.Name)' does not have a device event setting with the key '$($eventRow.EventName)'."
            }
        }
        $result = $item | Set-ConfigurationItem
        foreach ($entry in $result.ErrorResults) {
            Write-Error -Message "Validation error: $($entry.ErrorText) on device '$($device.Name)'."
        }
    }
}

function Set-DeviceProperties {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.IConfigurationItem]
        $Device,

        [Parameter(Mandatory)]
        [pscustomobject]
        $Settings
    )

    begin {
        $ignoredColumns = 'RecordingServer', 'Hardware', 'Address', 'LastModified', 'Id', 'MotionDetectionMethod', 'MotionGenerateMotionMetadata', 'MotionGridSize', 'MotionHardwareAccelerationMode', 'MotionKeyframesOnly', 'MotionManualSensitivity', 'MotionManualSensitivityEnabled', 'MotionProcessTime', 'MotionThreshold', 'MotionUseExcludeRegions'
        $recordingStorage = @{}
        Get-VmsRecordingServer -Name $Settings.RecordingServer | Get-VmsStorage | Foreach-Object {
            $recordingStorage[$_.Name] = $_
        }

        $translations = @{
            'Coordinates' = {
                param($item, $settings)
                try {
                    @{
                        Name  = 'GisPoint'
                        Value = if ($settings.Coordinates -eq 'Unknown' -or [string]::IsNullOrWhiteSpace($settings.Coordinates)) { 'POINT EMPTY' } else { ConvertTo-GisPoint -Coordinates $settings.Coordinates -ErrorAction Stop }
                    }
                } catch {
                    Write-Warning "Failed to convert value '$($settings.Coordinates)' to a GisPoint value compatible with Milestone."
                }
            }
            'Storage'     = {
                param($item, $settings)
                if ($recordingStorage.ContainsKey($settings.Storage)) {
                    @{
                        Name  = 'RecordingStorage'
                        Value = $recordingStorage[$settings.Storage].Path
                    }
                } else {
                    Write-Warning "Storage configuration '$($settings.Storage)' not found on recording server $($settings.RecordingServer)"
                }
            }
        }

        $customHandlers = @{
            'Enabled'          = {
                param($item, $settings)
                $enabled = $false
                if (-not [string]::IsNullOrWhiteSpace($settings.Enabled) -and [bool]::TryParse($settings.Enabled, [ref]$enabled) -and $item.EnableProperty.Enabled -ne $enabled) {
                    Write-Verbose "Changing 'Enabled' to $enabled on $($item.DisplayName)"
                    $item.EnableProperty.Enabled = $enabled
                    return $true
                }
                return $false
            }

            'RecordingStorage' = {
                param($item, $settings)
                try {
                    $storagePath = $recordingStorage[$settings.Storage].Path
                    if ($null -eq $storagePath) {
                        throw "Storage configuration named '$($settings.Storage)' not found."
                    }
                    if ($storagePath -eq ($item.Properties | Where-Object Key -eq 'RecordingStorage').Value) {
                        return $true
                    }
                    $invokeInfo = $item | Invoke-Method -MethodId 'ChangeDeviceRecordingStorage'
                    foreach ($p in $invokeInfo.Properties) {
                        switch ($p.Key) {
                            'ItemSelection' { $p.Value = $storagePath }
                            'moveData' { $p.Value = $false }
                        }
                    }
                    $invokeResult = $invokeInfo | Invoke-Method -MethodId 'ChangeDeviceRecordingStorage'
                    $taskPath = ($invokeResult.Properties | Where-Object Key -eq 'Path').Value
                    if ($taskPath) {
                        $null = Wait-VmsTask -Path $taskPath -Cleanup
                    }
                    return $true
                } catch {
                    Write-Warning $_.Exception.Message
                }
                return $false
            }

            'MotionEnabled'    = {
                param($item, $settings)
                $motion = Get-ConfigurationItem -Path "MotionDetection[$(($item.Properties | Where-Object Key -eq Id).Value)]"
                $dirty = $false
                foreach ($column in $settings | Get-Member -MemberType NoteProperty -Name Motion* | Select-Object -ExpandProperty Name) {
                    if ([string]::IsNullOrWhiteSpace($settings.$column)) {
                        continue
                    }
                    $key = $column.Substring(6)
                    if ($key -eq 'Enabled') {
                        $newValue = 'True' -eq $settings.$column
                        if ($motion.EnableProperty.Enabled -ne $newValue) {
                            $motion.EnableProperty.Enabled = $newValue
                            $dirty = $true
                        }
                    } else {
                        $property = $motion.Properties | Where-Object Key -eq $key
                        if ($property.Value -ne $settings.$column) {
                            $property.Value = $settings.$column
                            $dirty = $true
                        }
                    }
                }
                if ($dirty) {
                    $result = $motion | Set-ConfigurationItem
                    if (-not $result.ValidatedOk) {
                        foreach ($errorResult in $result.ErrorResults) {
                            Write-Warning "Failed to update motion detection settings for $($item.DisplayName). $($errorResult.ErrorText)."
                        }
                    }
                }
            }
        }
    }

    process {
        $dirty = $false
        $properties = @{}
        $item = $Device | Get-ConfigurationItem
        $item.Properties | Foreach-Object { $properties[$_.Key] = $_ }

        foreach ($columnName in $Settings | Get-Member -MemberType NoteProperty | Where-Object Name -notin $ignoredColumns | Select-Object -ExpandProperty Name) {
            $newValue = $Settings.$columnName
            if ($translations.ContainsKey($columnName)) {
                $columnName, $newValue = $translations[$columnName].Invoke($item, $Settings) | Foreach-Object {
                    Write-Verbose "Translating column name '$($columnName)' to '$($_.Name)', and value '$($newValue)' to '$($_.Value)'"
                    @($_.Name, $_.Value)
                }
                if ($null -eq $columnName -or $null -eq $newValue) {
                    Write-Verbose "Failed to translate column/value. No change will be made for this property."
                    continue
                }
            }

            if ($customHandlers.ContainsKey($columnName)) {
                if ($customHandlers[$columnName].Invoke($item, $Settings)) {
                    $dirty = $true
                }
            } else {
                $property = $properties[$columnName]
                if ($property) {
                    if ($property.Value -ne $newValue) {
                        Write-Verbose "Setting $columnName to $newValue on $($Device.Name)"
                        $property.Value = $newValue
                        $dirty = $true
                    } else {
                        Write-Verbose "Setting $columnName already has value $newValue on $($Device.Name)"
                    }
                } else {
                    Write-Warning "Property '$($columnName)' not found on $($Device.Name)"
                }
            }
        }

        # Update the name for the in-memory copy of $Device so that the verbose logging doesn't mention the old name anymore.
        $Device.Name = ($item.Properties | Where-Object Key -eq 'Name').Value

        if ($dirty) {
            Write-Verbose "Saving changes to $($Device.Name)"
            $result = $item | Set-ConfigurationItem
            foreach ($entry in $result.ErrorResults) {
                Write-Error -Message "Validation error: $($entry.ErrorText) on '$($Device.Name)'."
            }
        } else {
            Write-Verbose "No changes made to $($Device.Name)"
        }
    }
}

function Set-GeneralSettings {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.IConfigurationItem]
        $Device,

        [Parameter(Mandatory)]
        [pscustomobject[]]
        $Settings
    )

    begin {
        $validDeviceTypes = @('Hardware', 'Camera', 'Microphone', 'Speaker', 'InputEvent', 'Output', 'Metadata')
    }

    process {
        $devicePath = [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($Device.Path)
        if ($devicePath.ItemType -notin $validDeviceTypes) {
            Write-Error "Invalid device type for this cmdlet."
            return
        }

        $itemType = if ($devicePath.ItemType -eq 'Hardware') { 'Hardware' } else { 'Device' }
        Write-Verbose "$($devicePath.ItemType)GeneralSettings: Checking general settings for '$($Device.Name)'"
        $item = Get-ConfigurationItem -Path "$($itemType)DriverSettings[$($Device.Id)]"
        $general = $item.Children | Where-Object ItemType -eq "$($itemType)DriverSettings"
        $dirty = $false
        foreach ($setting in $Settings) {
            $property = $general.Properties | Where-Object Key -match "^([^/]+/)?(?<key>$($setting.Setting))(/[^/]+)?$" | Select-Object -First 1
            $key = $setting.Setting
            if ($property) {
                if ($property.IsSettable) {
                    if ($property.Value -cne $setting.Value) {
                        Write-Verbose "$($devicePath.ItemType)GeneralSettings: Changing $($property.DisplayName) ($key) to '$($setting.Value)'"
                        $property.Value = $setting.Value
                        $dirty = $true
                    } else {
                        Write-Verbose "$($devicePath.ItemType)GeneralSettings: Keeping $($property.DisplayName) ($key) value '$($setting.Value)'"
                    }
                } else {
                    Write-Verbose "$($devicePath.ItemType)GeneralSettings: Skipping read-only property $($property.DisplayName) ($key)"
                }
            } else {
                Write-Warning "$($devicePath.ItemType)GeneralSettings: Device '$($Device.Name)' does not have a general setting with the key '$($setting.Setting)'."
            }
        }

        if (-not $dirty) {
            Write-Verbose "$($devicePath.ItemType)GeneralSettings: No changes to general settings were required for '$($Device.Name)'"
            return
        }

        Write-Verbose "$($devicePath.ItemType)GeneralSettings: Saving changes to general settings for '$($Device.Name)'"
        $result = $item | Set-ConfigurationItem
        foreach ($entry in $result.ErrorResults) {
            Write-Error -Message "$($devicePath.ItemType)GeneralSettings: Validation error: $($entry.ErrorText) on '$($Device.Name)'."
        }
        <## Todo: See if its possible for the validation errorresults list to include all validation errors instead of one at a time.
        if (-not $result.ValidatedOk) {
            Write-verbose "Retrying without the invalid values"
            $general.Properties = $general.Properties | Where-Object Key -notin $result.ErrorResults.ErrorProperty
            $result = $item | Set-ConfigurationItem
            foreach ($entry in $result.ErrorResults) {
                Write-Error -Message "Validation error: $($entry.ErrorText) on '$($Device.Name)'."
            }
        }
        #>
    }
}

#endregion


#region public

function Export-VmsHardwareExcel {
    <#
    .SYNOPSIS
    Exports hardware configuration in Microsoft Excel XLSX format.

    .DESCRIPTION
    The `Export-VmsHardwareExcel` cmdlet accepts one or more Hardware objects
    from `Get-VmsHardware` and exports detailed configuration to an Excel XLSX
    document.

    The document will contain multiple worksheets, depending on which device
    types are specified in the `IncludedDevices` parameter. Each area of the
    hardware configuration is represented in it's own worksheet which makes it
    possible to represent many different types of objects and settings in the
    same document while keeping it human-readable and easy to modify.

    .PARAMETER Hardware
    Specifies one or more Hardware objects returned by `Get-VmsHardware`. If no
    hardware is provided, then all hardware found in the VMS matching the
    desired `EnableState` will be exported.

    .PARAMETER Path
    The absolute, or relative path, including filename, where the .XLSX file
    should be saved. If no path is provided, a save-file dialog will be shown.

    .PARAMETER IncludedDevices
    Defaults to "Cameras". Specifies the types of child devices to include in the export. It can be
    very time consuming to export configuration for thousands of devices, and
    if you only need camera and metadata settings, you can specify this and
    avoid retrieving detailed configuration on microphones, speakers, inputs,
    and outputs.

    .PARAMETER EnableFilter
    Defaults to "Enabled". Filters the exported hardware and devices to only
    those matching the specified EnableFilter.

    .PARAMETER Force
    Overwrite an existing file if the file specified in `Path` already exists.

    .EXAMPLE
    Export-VmsHardwareExcel -Path ~\Documents\hardware.xlsx -Verbose

    Exports configuration for all enabled hardware, and cameras to the current
    user's Documents directory.

    .EXAMPLE
    Export-VmsHardwareExcel -Path ~\Documents\hardware.xlsx -IncludedDevices Cameras, Microphones -Verbose

    Exports configuration for all enabled hardware, cameras, and microphones to
    the current user's Documents directory.

    .EXAMPLE
    $hardware = Get-VmsRecordingServer -Name Recorder1 | Get-VmsHardware
    Export-VmsHardwareExcel -Hardware $hardware -Path ~\Desktop\hardware.xlsx -Verbose

    Exports configuration for all enabled hardware, and cameras on the
    recording server named "Recorder1" tp the current user's Desktop.

    #>
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [VideoOS.Platform.ConfigurationItems.Hardware[]]
        $Hardware,

        [Parameter()]
        [string]
        $Path,

        [Parameter()]
        [ValidateSet('Cameras', 'Microphones', 'Speakers', 'Metadata', 'Inputs', 'Outputs')]
        [string[]]
        $IncludedDevices = @('Cameras'),

        [Parameter()]
        [ValidateSet('All', 'Disabled', 'Enabled')]
        [string]
        $EnableFilter = 'Enabled',

        [Parameter()]
        [switch]
        $Force
    )

    begin {
        if ($null -eq (Get-VmsManagementServer -ErrorAction 'SilentlyContinue')) {
            Connect-ManagementServer -ShowDialog -AcceptEula -Force -ErrorAction Stop
        }
        if ([string]::IsNullOrWhiteSpace($Path)) {
            $Path = Show-FileDialog -SaveFile
        }
        if (Test-Path $Path) {
            if ($Force) {
                Remove-Item -Path $Path -ErrorAction Stop
            } else {
                Write-Error "File $Path already exists." -ErrorAction Stop
            }
        } else {
            $fileInfo = [io.fileinfo](Resolve-Path2 -Path $Path -NoValidation)
            if (-not (Test-Path $fileInfo.DirectoryName)) {
                Write-Verbose "Directory $($fileInfo.DirectoryName) does not exist. This folder will be created."
                $null = New-Item -Path $fileInfo.DirectoryName -ItemType Directory
            }
        }
        $excelPackage = Open-ExcelPackage -Path $Path -Create
        $worksheets = @(
            'Hardware',
            'HardwareGeneralSettings',
            'HardwareEvents',
            'Cameras',
            'CameraGeneralSettings',
            'CameraStreams',
            'CameraStreamSettings',
            'CameraEvents',
            'Microphones',
            'MicrophoneGeneralSettings',
            'MicrophoneStreamSettings',
            'MicrophoneEvents',
            'Speakers',
            'SpeakerGeneralSettings',
            'SpeakerEvents',
            'Metadata',
            'MetadataGeneralSettings',
            'Inputs',
            'InputGeneralSettings',
            'InputEvents',
            'Outputs',
            'OutputGeneralSettings'
        )
        $null = $worksheets | Foreach-Object { $excelPackage.Workbook.Worksheets.Add($_) }
        Clear-VmsCache
    }

    process {
        $progress = @{
            Activity         = 'Exporting hardware configuration to {0}' -f $Path
            Id               = 11
            PercentComplete  = 0
            CurrentOperation = 'Preparing'
        }
        Write-Progress @progress

        if ($IncludedDevices) {
            $IncludedDevices = $IncludedDevices | Group-Object | Select-Object -ExpandProperty Name
        }


        $progress.CurrentOperation = "Retrieving list of recording servers"
        Write-Progress @progress
        Write-Verbose "Retrieving recording server list"
        $recorderMap = @{}
        Get-VmsRecordingServer | Foreach-Object {
            $recorderMap[$_.Path] = $_
        }

        if ($null -eq $Hardware) {
            $progress.CurrentOperation = "Retrieving list of hardware to be exported"
            Write-Progress @progress
            $Hardware = Get-VmsHardware
        }

        $excelParams = @{
            ExcelPackage       = $excelPackage
            TableStyle         = 'Medium9'
            AutoSize           = $true
            Append             = $true
            NoNumberConversion = 'Value', 'DisplayValue'
            PassThru           = $true
        }

        $totalHardwareCount = $Hardware.Count
        $processedHardwareCount = 0
        $Hardware | ForEach-Object {
            $hw = $_
            $progress.PercentComplete = [math]::Round(($processedHardwareCount++) / $totalHardwareCount * 100)
            $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
            Write-Progress @progress
            if (($EnableFilter -eq 'Enabled' -and -not $hw.Enabled) -or ($EnableFilter -eq 'Disabled' -and $hw.Enabled)) {
                Write-Verbose "Skipping hardware $($hw.Name) due to the EnableFilter value of $EnableFilter"
                return
            }
            Write-Verbose "Retrieving hardware properties for $($hw.Name)"
            $null = $hw | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Hardware -TableName HardwareList }

            Write-Verbose "Retrieving general setting properties for $($hw.Name)"
            $null = $hw | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName HardwareGeneralSettings -TableName HardwareGeneralSettingsList }

            Write-Verbose "Retrieving event properties for $($hw.Name)"
            $obj = [ordered]@{
                RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                Hardware        = $hw.Name
            }
            $null = $hw | Get-DeviceEvents | ForEach-Object {
                $eventInfo = $_
                $obj.EventName = $eventInfo.Event
                $obj.Used = $eventInfo.Used
                $obj.Enabled = $eventInfo.Enabled
                $obj.EventIndex = $eventInfo.EventIndex
                $obj.IndexName = $eventInfo.IndexName
                [pscustomobject]$obj | Export-Excel @excelParams -WorksheetName HardwareEvents -TableName HardwareEventsList
            }

            if ('Cameras' -in $IncludedDevices) {
                $hw | Get-VmsCamera -EnableFilter $EnableFilter | Foreach-Object {
                    Write-Verbose "Retrieving camera properties for $($_.Name)"
                    $cam = $_
                    $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
                    Write-Progress @progress
                    $null = $cam | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Cameras -TableName CamerasList }

                    Write-Verbose "Retrieving general setting properties for $($cam.Name)"
                    $null = $cam | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName CameraGeneralSettings -TableName CameraGeneralSettingsList }

                    Write-Verbose "Retrieving stream properties for $($cam.Name)"
                    $cam | Get-VmsCameraStream -Enabled -RawValues | Foreach-Object {
                        $stream = $_
                        $obj = [pscustomobject]@{
                            RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                            Hardware        = $hw.Name
                            Camera          = $cam.Name
                            Channel         = $cam.Channel

                            Name            = $stream.Name
                            DisplayName     = $stream.DisplayName
                            LiveMode        = $stream.LiveMode
                            LiveDefault     = $stream.LiveDefault
                            Recorded        = $stream.Recorded
                        }
                        $null = $obj | Export-Excel @excelParams -WorksheetName CameraStreams -TableName CameraStreamsList

                        $null = $stream.Settings.Keys | Foreach-Object {
                            $key = $_
                            $displayValue = ($stream.ValueTypeInfo[$key] | Where-Object { $_.Value -eq $property.Value -and $_.Name -notlike '*Value' }).Name
                            [pscustomobject]@{
                                RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                                Hardware        = $hw.Name
                                Camera          = $cam.Name
                                Channel         = $cam.Channel
                                Stream          = $stream.Name

                                Setting         = $key
                                Value           = $stream.Settings[$key]
                                DisplayValue    = if ($stream.Settings[$key] -ne $displayValue) { $displayValue } else { $null }
                            } | Export-Excel @excelParams -WorksheetName CameraStreamSettings -TableName CameraStreamSettingsList
                        }
                    }

                    Write-Verbose "Retrieving event properties for $($cam.Name)"
                    $obj = [ordered]@{
                        RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                        Hardware        = $hw.Name
                        Camera          = $cam.Name
                    }
                    $null = $cam | Get-DeviceEvents | ForEach-Object {
                        $eventInfo = $_
                        $obj.EventName = $eventInfo.Event
                        $obj.Used = $eventInfo.Used
                        $obj.Enabled = $eventInfo.Enabled
                        $obj.EventIndex = $eventInfo.EventIndex
                        $obj.IndexName = $eventInfo.IndexName
                        [pscustomobject]$obj | Export-Excel @excelParams -WorksheetName CameraEvents -TableName CameraEventsList
                    }
                }
            }

            if ('Microphones' -in $IncludedDevices) {
                $hw | Get-Microphone | Foreach-Object {
                    $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
                    Write-Progress @progress
                    $mic = $_
                    if (($EnableFilter -eq 'Enabled' -and -not $mic.Enabled) -or ($EnableFilter -eq 'Disabled' -and $mic.Enabled)) {
                        Write-Verbose "Skipping microphone $($mic.Name) due to the EnableFilter value of $EnableFilter"
                        return
                    }

                    Write-Verbose "Retrieving microphone properties for $($mic.Name)"
                    $null = $mic | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Microphones -TableName MicrophonesList }

                    Write-Verbose "Retrieving general setting properties for $($mic.Name)"
                    $null = $mic | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName MicrophoneGeneralSettings -TableName MicrophoneGeneralSettingsList }

                    Write-Verbose "Retrieving stream properties for $($mic.Name)"
                    $deviceDriverSettings | Select-Object -ExpandProperty Children | Where-Object ItemType -eq Stream | Select-Object -ExpandProperty Properties | Where-Object IsSettable | Foreach-Object {
                        if ($null -eq $_) {
                            return
                        }
                        $property = $_
                        $key = $property.Key
                        $displayValue = ($property.ValueTypeInfos | Where-Object Value -eq $property.Value).Name
                        if ($key -match '^([^/]+/)(?<key>[^/]+)(/[^/]+)?$') {
                            $key = $Matches.key
                        }
                        $obj = [pscustomobject]@{
                            RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                            Hardware        = $hw.Name
                            Microphone      = $mic.Name
                            Channel         = $mic.Channel

                            Setting         = $key
                            Value           = $property.Value
                            DisplayValue    = if ($property.ValueType -eq 'Enum' -and $displayValue -ne $property.Value) { $displayValue } else { $null }
                        }
                        $null = $obj | Export-Excel @excelParams -WorksheetName MicrophoneStreamSettings -TableName MicrophoneStreamSettingsList
                    }

                    Write-Verbose "Retrieving event properties for $($mic.Name)"
                    $obj = [ordered]@{
                        RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                        Hardware        = $hw.Name
                        Microphone      = $mic.Name
                    }
                    $null = $mic | Get-DeviceEvents | ForEach-Object {
                        $obj.EventName = $eventInfo.Event
                        $obj.Used = $eventInfo.Used
                        $obj.Enabled = $eventInfo.Enabled
                        $obj.EventIndex = $eventInfo.EventIndex
                        $obj.IndexName = $eventInfo.IndexName
                        [pscustomobject]$obj | Export-Excel @excelParams -WorksheetName MicrophoneEvents -TableName MicrophoneEventsList
                    }
                }
            }

            if ('Speakers' -in $IncludedDevices) {
                $hw | Get-Speaker | Foreach-Object {
                    $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
                    Write-Progress @progress
                    $speaker = $_
                    if (($EnableFilter -eq 'Enabled' -and -not $speaker.Enabled) -or ($EnableFilter -eq 'Disabled' -and $speaker.Enabled)) {
                        Write-Verbose "Skipping speaker $($speaker.Name) due to the EnableFilter value of $EnableFilter"
                        return
                    }
                    Write-Verbose "Retrieving speaker properties for $($speaker.Name)"
                    $null = $speaker | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Speakers -TableName SpeakersList }

                    Write-Verbose "Retrieving general setting properties for $($speaker.Name)"
                    $null = $speaker | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName SpeakerGeneralSettings -TableName SpeakerGeneralSettingsList }

                    Write-Verbose "Retrieving event properties for $($speaker.Name)"
                    $obj = [ordered]@{
                        RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                        Hardware        = $hw.Name
                        Speaker         = $speaker.Name
                    }
                    $null = $speaker | Get-DeviceEvents | ForEach-Object {
                        $eventInfo = $_
                        $obj.EventName = $eventInfo.Event
                        $obj.Used = $eventInfo.Used
                        $obj.Enabled = $eventInfo.Enabled
                        $obj.EventIndex = $eventInfo.EventIndex
                        $obj.IndexName = $eventInfo.IndexName
                        [pscustomobject]$obj | Export-Excel @excelParams -WorksheetName SpeakerEvents -TableName SpeakerEventsList
                    }
                }
            }

            if ('Metadata' -in $IncludedDevices) {
                $hw | Get-Metadata | Foreach-Object {
                    $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
                    Write-Progress @progress
                    $metadata = $_
                    if (($EnableFilter -eq 'Enabled' -and -not $metadata.Enabled) -or ($EnableFilter -eq 'Disabled' -and $metadata.Enabled)) {
                        Write-Verbose "Skipping metadata $($metadata.Name) due to the EnableFilter value of $EnableFilter"
                        return
                    }
                    Write-Verbose "Retrieving metadata properties for $($metadata.Name)"
                    $null = $metadata | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Metadata -TableName MetadataList }

                    Write-Verbose "Retrieving metadata general settings for $($metadata.Name)"
                    $null = $metadata | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName MetadataGeneralSettings -TableName MetadataGeneralSettingsList }
                }
            }

            if ('Inputs' -in $IncludedDevices) {
                $hw | Get-Input | Foreach-Object {
                    $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
                    Write-Progress @progress
                    $inputEvent = $_
                    if (($EnableFilter -eq 'Enabled' -and -not $inputEvent.Enabled) -or ($EnableFilter -eq 'Disabled' -and $inputEvent.Enabled)) {
                        Write-Verbose "Skipping input $($inputEvent.Name) due to the EnableFilter value of $EnableFilter"
                        return
                    }
                    Write-Verbose "Retrieving input properties for $($inputEvent.Name)"
                    $null = $inputEvent | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Inputs -TableName InputsList }

                    Write-Verbose "Retrieving input general settings for $($inputEvent.Name)"
                    $null = $inputEvent | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName InputGeneralSettings -TableName InputGeneralSettingsList }

                    Write-Verbose "Retrieving event properties for $($inputEvent.Name)"
                    $obj = [ordered]@{
                        RecordingServer = $recorderMap[$hw.ParentItemPath].Name
                        Hardware        = $hw.Name
                        Input           = $inputEvent.Name
                    }
                    $null = $inputEvent | Get-DeviceEvents | ForEach-Object {
                        $eventInfo = $_
                        $obj.EventName = $eventInfo.Event
                        $obj.Used = $eventInfo.Used
                        $obj.Enabled = $eventInfo.Enabled
                        $obj.EventIndex = $eventInfo.EventIndex
                        $obj.IndexName = $eventInfo.IndexName
                        [pscustomobject]$obj | Export-Excel @excelParams -WorksheetName InputEvents -TableName InputEventsList
                    }
                }
            }

            if ('Outputs' -in $IncludedDevices) {
                $hw | Get-Output | Foreach-Object {
                    $progress.CurrentOperation = '{0} "{1}"' -f [VideoOS.Platform.Proxy.ConfigApi.ConfigurationItemPath]::new($_.Path).ItemType, $_.Name
                    Write-Progress @progress
                    $output = $_
                    if (($EnableFilter -eq 'Enabled' -and -not $output.Enabled) -or ($EnableFilter -eq 'Disabled' -and $output.Enabled)) {
                        Write-Verbose "Skipping output $($output.Name) due to the EnableFilter value of $EnableFilter"
                        return
                    }
                    Write-Verbose "Retrieving output properties for $($output.Name)"
                    $null = $output | Get-DeviceProperties | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName Outputs -TableName OutputsList }

                    Write-Verbose "Retrieving output general settings for $($output.Name)"
                    $null = $output | Get-GeneralSettings | Foreach-Object { $_ | Export-Excel @excelParams -WorksheetName OutputGeneralSettings -TableName OutputGeneralSettingsList }
                }
            }
        }
        $progress.PercentComplete = 100
        $progress.Completed = $true
        Write-Progress @progress
    }

    end {
        $excelPackage.Workbook.Worksheets.Name | Foreach-Object {
            if ($null -eq $excelPackage.Workbook.Worksheets[$_].GetValue(1, 1)) {
                $excelPackage.Workbook.Worksheets.Delete($_)
            }
        }
        $excelPackage | Close-ExcelPackage
    }
}

function Import-VmsHardwareExcel {
    <#
    .SYNOPSIS
    Imports hardware configuration from an Excel .XLSX document and adds and
    optionally updates hardware based.

    .DESCRIPTION
    The `Import-VmsHardwareExcel` cmdlet accepts a path to an existing Excel
    .XLSX document, and imports the hardware configuration. The cmdlet can add
    new devices and update the settings of existing devices if the values in
    the Excel document differ from the live values.

    Depending on the content of the Excel document, the settings imported can
    include hardware, general settings, cameras, microphones, speakers, inputs,
    outputs, metadata, and the corresponding general settings, settings for
    streams, recording, events, motion, and more.

    The format of the Excel document, and the valid values for various settings
    is challenging to document. The best way to perform a successful import is
    to add and configure a representative sample of devices, and then use
    `Export-VmsHardwareExcel` to generate a configuration export. You can then
    use the export as a reference to build a document to import.

    .PARAMETER Path
    Specifies a path to an existing Excel document in .XLSX format. While the
    `ImportExcel` module supports reading from password protected files, this
    has not been extended to this cmdlet. If no path is provided, an open-file
    dialog will be shown.

    .PARAMETER UpdateExisting
    If hardware defined in the Excel document is already added, it will not be
    modified by default. If you wish to update the settings for existing
    hardware during an import, this switch can be used.

    .EXAMPLE
    Update-VmsHardwareExcel -Path ~\Desktop\hardware.xlsx -Verbose

    Imports the hardware.xlsx file on the current user's desktop. If any cameras
    in the Excel document are already added, they will be ignored and their
    settings will not be modified if they have drifted from the configuration
    defined in the document.

    .EXAMPLE
    Update-VmsHardwareExcel -Path ~\Desktop\hardware.xlsx -UpdateExisting -Verbose

    Imports the hardware.xlsx file on the current user's desktop. If any cameras
    in the Excel document are already added, they will be updated to reflect the
    configuration defined in the document.

    #>
    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $Path,

        [Parameter()]
        [switch]
        $UpdateExisting
    )

    begin {
        if ($null -eq (Get-VmsManagementServer -ErrorAction 'SilentlyContinue')) {
            Connect-ManagementServer -ShowDialog -AcceptEula -Force -ErrorAction Stop
        }
        if ([string]::IsNullOrWhiteSpace($Path)) {
            $Path = Show-FileDialog -OpenFile
        }
        try {
            $excelPackage = Open-ExcelPackage -Path $Path
            $worksheets = $excelPackage.Workbook.Worksheets.Name
            $data = @{
                Hardware                  = [system.collections.generic.list[pscustomobject]]::new()
                HardwareGeneralSettings   = [system.collections.generic.list[pscustomobject]]::new()
                HardwareEvents            = [system.collections.generic.list[pscustomobject]]::new()
                Cameras                   = [system.collections.generic.list[pscustomobject]]::new()
                CameraGeneralSettings     = [system.collections.generic.list[pscustomobject]]::new()
                CameraStreams             = [system.collections.generic.list[pscustomobject]]::new()
                CameraStreamSettings      = [system.collections.generic.list[pscustomobject]]::new()
                CameraEvents              = [system.collections.generic.list[pscustomobject]]::new()
                Microphones               = [system.collections.generic.list[pscustomobject]]::new()
                MicrophoneGeneralSettings = [system.collections.generic.list[pscustomobject]]::new()
                MicrophoneStreamSettings  = [system.collections.generic.list[pscustomobject]]::new()
                MicrophoneEvents          = [system.collections.generic.list[pscustomobject]]::new()
                Speakers                  = [system.collections.generic.list[pscustomobject]]::new()
                SpeakerGeneralSettings    = [system.collections.generic.list[pscustomobject]]::new()
                SpeakerEvents             = [system.collections.generic.list[pscustomobject]]::new()
                Metadata                  = [system.collections.generic.list[pscustomobject]]::new()
                MetadataGeneralSettings   = [system.collections.generic.list[pscustomobject]]::new()
                Inputs                    = [system.collections.generic.list[pscustomobject]]::new()
                InputGeneralSettings      = [system.collections.generic.list[pscustomobject]]::new()
                InputEvents               = [system.collections.generic.list[pscustomobject]]::new()
                Outputs                   = [system.collections.generic.list[pscustomobject]]::new()
                OutputGeneralSettings     = [system.collections.generic.list[pscustomobject]]::new()
            }
            foreach ($key in $data.Keys) {
                if ($key -in $worksheets) {
                    if ($excelPackage.Workbook.Worksheets[$key].GetValue(1, 1)) {
                        Import-Excel -ExcelPackage $excelPackage -WorksheetName $key | ForEach-Object {
                            $data[$key].Add($_)
                        }
                    } else {
                        Write-Verbose "Ignoring worksheet '$key' because the value at 1,1 is null."
                    }
                }
            }
        } finally {
            if ($excelPackage) {
                $excelPackage | Close-ExcelPackage -NoSave
            }
        }
    }

    process {
        if ($data.Hardware.Count -eq 0) {
            Write-Error "No hardware entries found in the Hardware worksheet."
            return
        }

        $totalRows = $data.Hardware.Count
        $processedRows = 0
        $progressParams = @{
            Activity         = 'Importing hardware configuration from {0}' -f $Path
            Id               = 42
            PercentComplete  = 0
            CurrentOperation = 'Preparing'
        }
        Write-Progress @progressParams

        $recorders = @{}
        $existingHardware = @{}
        Get-VmsRecordingServer -PipelineVariable rec | Foreach-Object {
            $recorders[$rec.Name] = $rec
            $existingHardware[$rec.Name] = @{}
            $rec | Get-VmsHardware -PipelineVariable hw | Foreach-Object { if ($uri = $hw.Address -as [uri]) { $existingHardware[$rec.Name][('{0}:{1}' -f $uri.Host, $uri.Port)] = $hw } }
        }

        foreach ($row in $data.Hardware | Sort-Object RecordingServer) {
            $progressParams.PercentComplete = [math]::Round(($processedRows++) / $totalRows * 100)
            $progressParams.CurrentOperation = '{0} ({1})' -f $row.Name, $row.Address
            Write-Progress @progressParams
            try {
                $recorder = if ($row.RecordingServer) { $recorders[$row.RecordingServer] } else { $null }
                if (-not $recorder) {
                    Write-Warning "Recording server '$($row.RecordingServer)' not found. Skipping hardware '$($row.Name)' ($($row.Address))."
                    continue
                }

                $params = @{
                    Name            = $row.Name
                    HardwareAddress = $row.Address -as [uri]
                    Credential      = try { [pscredential]::new($row.UserName, ($row.Password | ConvertTo-SecureString -AsPlainText -Force)) } catch { $null };
                    DriverNumber    = $row.DriverNumber -as [int]
                    RecordingServer = $recorder
                    ErrorAction     = 'Stop'
                }

                if ([string]::IsNullOrWhiteSpace($params.Name)) {
                    $params.Remove('Name')
                }
                if (-not $params.HardwareAddress -or -not $params.HardwareAddress.IsAbsoluteUri) {
                    Write-Warning "Hardware '$($row.Name)' must have a valid address in the Address column. The value '$($row.Address)' is not a valid absolute URI. Example: http://192.168.1.101"
                    continue
                }


                $key = '{0}:{1}' -f $params.HardwareAddress.Host, $params.HardwareAddress.Port
                if (($hardware = $existingHardware[$row.RecordingServer][$key])) {
                    if (-not $UpdateExisting) {
                        Write-Verbose "Skipping the hardware at $($params.HardwareAddress) because it is already added to $($recorder.Name). To Update existing hardware/devices, use the 'UpdateExisting' switch."
                        continue
                    }
                } else {
                    if (-not $params.DriverNumber) {
                        $scanParams = @{
                            RecordingServer = $recorder
                            Address         = $params.HardwareAddress
                        }
                        if ($row.DriverGroup) {
                            $scanParams.DriverFamily = $row.DriverGroup
                        }
                        if ($params.Credential) {
                            $scanParams.Credential = $params.Credential
                        } else {
                            $scanParams.UseDefaultCredentials
                        }
                        Write-Verbose "Scanning hardware at $($row.Address) for driver discovery"
                        $scan = Start-VmsHardwareScan @scanParams
                        if ($scan.HardwareScanValidated) {
                            $params.Remove('DriverNumber')
                            $params.HardwareDriverPath = $scan.HardwareDriverPath
                            if ($null -eq $params.Credential) {
                                $params.Credential = [pscredential]::new($scan.UserName, ($scan.Password | ConvertTo-SecureString -AsPlainText -Force))
                            }
                        } else {
                            Write-Error -Message "Hardware scan failed for '$($params.Name)' ($($params.HardwareAddress)). Result: $($scan.ErrorText)"
                            continue
                        }
                    }
                    $hardware = Add-VmsHardware @params
                }

                $hardware.Name = if ($row.Name) { $row.Name } else { $hardware.Name }
                $hardware.Enabled = 'False' -ne $row.Enabled
                $hardware.Description = $row.Description
                $hardware.Save()

                $settings = $data.HardwareGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($settings) {
                    Set-GeneralSettings -Device $hardware -Settings $settings
                }

                $settings = $data.HardwareEvents | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($settings) {
                    Set-DeviceEvents -Device $hardware -Settings $settings
                }


                $cameraRows = $data.Cameras | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($cameraRows) {
                    Write-Verbose "Updating camera properties for $($hardware.Name)"
                    $hardware | Get-VmsCamera -EnableFilter All | Where-Object Channel -in $cameraRows.Channel | Foreach-Object {
                        $camera = $_

                        Set-DeviceProperties -Device $_ -Settings ($cameraRows | Where-Object Channel -eq $_.Channel | Select-Object -First 1)

                        $generalSettings = $data.CameraGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Camera -eq $camera.Name }
                        if ($generalSettings) {
                            Set-GeneralSettings -Device $_ -Settings $generalSettings
                        }

                        $eventSettings = $data.CameraEvents | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Camera -eq $camera.Name }
                        if ($eventSettings) {
                            Set-DeviceEvents -Device $camera -Settings $eventSettings
                        }

                        $data.CameraStreams | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Camera -eq $camera.Name } | ForEach-Object {
                            $streamRow = $_
                            $stream = $camera | Get-VmsCameraStream -Name $streamRow.Name -ErrorAction SilentlyContinue
                            if ($stream) {
                                $streamParams = @{
                                    Verbose = $MyInvocation.BoundParameters['Verbose'] -eq $true
                                }
                                if ($streamRow.DisplayName) { $streamParams.DisplayName = $streamRow.DisplayName }
                                if ('True' -eq $streamRow.Recorded) { $streamParams.Recorded = $true }
                                if ('True' -eq $streamRow.LiveDefault) { $streamParams.LiveDefault = $true }
                                if ($streamRow.LiveMode) { $streamParams.LiveMode = $streamRow.LiveMode }
                                if ($streamParams.Count -gt 0) {
                                    $stream | Set-VmsCameraStream @streamParams
                                }
                            } else {
                                Write-Warning "No stream found on $($camera.Name) with the name '$($streamRow.Name)'"
                            }
                        }

                        $data.CameraStreamSettings |  Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Camera -eq $camera.Name -and $_.Setting -and $_.Value } | Group-Object Stream | Foreach-Object {
                            $streamName = $_.Name
                            $streamSettings = @{}
                            $_.Group | Foreach-Object { $streamSettings[$_.Setting] = $_.Value }
                            $stream = $camera | Get-VmsCameraStream -Name $streamName -ErrorAction Ignore
                            if ($stream) {
                                $stream | Set-VmsCameraStream -Settings $streamSettings -Verbose:($VerbosePreference -eq 'Continue' )
                            } else {
                                Write-Warning "No stream found on $($camera.Name) with the name '$($streamRow.Name)'"
                            }
                        }
                    }
                } else {
                    Write-Verbose "No cameras to configure for $($hardware.Name)"
                }


                $rows = $data.Microphones | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($rows) {
                    Write-Verbose "Updating microphone properties for $($hardware.Name)"
                    $hardware | Get-Microphone | Where-Object Channel -in $rows.Channel | Foreach-Object {
                        $device = $_

                        Set-DeviceProperties -Device $device -Settings ($rows | Where-Object Channel -eq $device.Channel | Select-Object -First 1)

                        $generalSettings = $data.MicrophoneGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Microphone -eq $device.Name }
                        if ($generalSettings) {
                            Set-GeneralSettings -Device $device -Settings $generalSettings
                        }

                        $eventSettings = $data.MicrophoneEvents | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Microphone -eq $device.Name }
                        if ($eventSettings) {
                            Set-DeviceEvents -Device $device -Settings $eventSettings
                        }
                    }
                } else {
                    Write-Verbose "No microphones to configure for $($hardware.Name)"
                }


                $rows = $data.Speakers | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($rows) {
                    Write-Verbose "Updating speaker properties for $($hardware.Name)"
                    $hardware | Get-Speaker | Where-Object Channel -in $rows.Channel | Foreach-Object {
                        $device = $_

                        Set-DeviceProperties -Device $device -Settings ($rows | Where-Object Channel -eq $device.Channel | Select-Object -First 1)

                        $generalSettings = $data.SpeakerGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Speaker -eq $device.Name }
                        if ($generalSettings) {
                            Set-GeneralSettings -Device $device -Settings $generalSettings
                        }
                    }
                } else {
                    Write-Verbose "No speakers to configure for $($hardware.Name)"
                }


                $rows = $data.Metadata | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($rows) {
                    Write-Verbose "Updating metadata properties for $($hardware.Name)"
                    $hardware | Get-Metadata | Where-Object Channel -in $rows.Channel | Foreach-Object {
                        $device = $_

                        Set-DeviceProperties -Device $device -Settings ($rows | Where-Object Channel -eq $device.Channel | Select-Object -First 1)

                        $generalSettings = $data.MetadataGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Metadata -eq $device.Name }
                        if ($generalSettings) {
                            Set-GeneralSettings -Device $device -Settings $generalSettings
                        }
                    }
                } else {
                    Write-Verbose "No microphones to configure for $($hardware.Name)"
                }


                $rows = $data.Inputs | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($rows) {
                    Write-Verbose "Updating IO input properties for $($hardware.Name)"
                    $hardware | Get-Input | Where-Object Channel -in $rows.Channel | Foreach-Object {
                        $device = $_

                        Set-DeviceProperties -Device $device -Settings ($rows | Where-Object Channel -eq $device.Channel | Select-Object -First 1)

                        $generalSettings = $data.InputGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.InputEvent -eq $device.Name }
                        if ($generalSettings) {
                            Set-GeneralSettings -Device $device -Settings $generalSettings
                        }
                    }
                } else {
                    Write-Verbose "No microphones to configure for $($hardware.Name)"
                }


                $rows = $data.Metadata | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name }
                if ($rows) {
                    Write-Verbose "Updating metadata properties for $($hardware.Name)"
                    $hardware | Get-Metadata | Where-Object Channel -in $rows.Channel | Foreach-Object {
                        $device = $_

                        Set-DeviceProperties -Device $device -Settings ($rows | Where-Object Channel -eq $device.Channel | Select-Object -First 1)

                        $generalSettings = $data.MetadataGeneralSettings | Where-Object { $_.RecordingServer -eq $recorder.Name -and $_.Hardware -eq $hardware.Name -and $_.Metadata -eq $device.Name }
                        if ($generalSettings) {
                            Set-GeneralSettings -Device $device -Settings $generalSettings
                        }
                    }
                } else {
                    Write-Verbose "No microphones to configure for $($hardware.Name)"
                }
            } catch {
                Write-Error -ErrorRecord $_
            }
        }
        $progressParams.CurrentOperation = 'Completed'
        $progressParams.PercentComplete = 100
        $progressParams.Completed = $true
        Write-Progress @progressParams
    }
}

#endregion

Export-ModuleMember -Function Export-VmsHardwareExcel, Import-VmsHardwareExcel