0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093
0094
0095
0096
0097
0098
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138
0139
0140
0141
0142
0143
0144
0145
0146
0147
0148
0149
0150
0151
0152
0153
0154
0155
0156
0157
0158
0159
0160
0161
0162
0163
0164
0165
0166
0167
0168
0169
0170
0171
0172
0173
0174
0175
0176
0177
0178
0179
0180
0181
0182
0183
0184
0185
0186
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207
0208
0209
0210
0211
0212
0213
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226
0227
0228
0229
0230
0231
0232
0233
0234
0235
0236
0237
0238
0239
0240
0241
0242
0243
0244
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255
0256
0257
0258
0259
0260
0261
0262
0263
0264
0265
0266
0267
0268
0269
0270
0271
0272
0273
0274
0275
0276
0277
0278
0279
0280
0281
0282
0283
0284
0285
0286
0287
0288
0289
0290
0291
0292
0293
0294
0295
0296
0297
0298
0299
0300
0301
0302
0303
0304
0305
0306
0307
0308
0309
0310
0311
0312
0313
0314
0315
0316
0317
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328
0329
0330
0331
0332
0333
0334
0335
0336
0337
0338
0339
0340
0341
0342
0343
0344
0345
0346
0347
0348
0349
0350
0351
0352
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377
0378
0379
0380
0381
0382
0383
0384
0385
0386
0387
0388
0389
0390
0391
0392
0393
0394
0395
0396
0397
0398
0399
0400
0401
0402
0403
0404
0405
0406
0407
0408
0409
0410
0411
0412
0413
0414
0415
0416
0417
0418
0419
0420
0421
0422
0423
0424
0425
0426
0427
0428
0429
0430
0431
0432
0433
0434
0435
0436
0437
0438
0439
0440
0441
0442
0443
0444
0445
0446
0447
0448
0449
0450
0451
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479
0480
0481
0482
0483
0484
0485
0486
0487
0488
0489
0490
0491
0492
0493
0494
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514
0515
0516
0517
0518
0519
0520
0521
0522
0523
0524
0525
0526
0527
0528
0529
0530
0531
0532
0533
0534
0535
0536
0537
0538
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554
0555
0556
0557
0558
0559
0560
0561
0562
0563
0564
0565
0566
0567
0568
0569
0570
0571
0572
0573
0574
0575
0576
0577
0578
0579
0580
0581
0582
0583
0584
0585
0586
0587
0588
0589
0590
0591
0592
0593
0594
0595
0596
0597
0598
0599
0600
0601
0602
0603
0604
0605
0606
0607
0608
0609
0610
0611
0612
0613
0614
0615
0616
0617
0618
0619
0620
0621
0622
0623
0624
0625
0626
0627
0628
0629
0630
0631
0632
0633
0634
0635
0636
0637
0638
0639
0640
0641
0642
0643
0644
0645
0646
0647
0648
0649
0650
0651
0652
0653
0654
0655
0656
0657
0658
0659
0660
0661
0662
0663
0664
0665
0666
0667
0668
0669
0670
0671
0672
0673
0674
0675
0676
0677
0678
0679
0680
0681
0682
0683
0684
0685
0686
0687
0688
0689
0690
0691
0692
0693
0694
0695
0696
0697
0698
0699
0700
0701
0702
0703
0704
0705
0706
0707
0708
0709
0710
0711
0712
0713
0714
0715
0716
0717
0718
0719
0720
0721
0722
0723
0724
0725
0726
0727
0728
0729
0730
0731
0732
0733
0734
0735
0736
0737
0738
0739
0740
0741
0742
0743
0744
0745
0746
0747
0748
0749
0750
0751
0752
0753
0754
0755
0756
0757
0758
0759
0760
0761
0762
0763
0764
0765
0766
0767
0768
0769
0770
0771
0772
0773
0774
0775
0776
0777
0778
0779
0780
0781
0782
0783
0784
0785
0786
0787
0788
0789
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804
0805
0806
0807
0808
0809
0810
0811
0812
0813
0814
0815
0816
0817
0818
0819
0820
0821
0822
0823
0824
0825
0826
0827
0828
0829
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862
0863
0864
0865
0866
0867
0868
0869
0870
0871
0872
0873
0874
0875
0876
0877
0878
0879
0880
0881
0882
0883
0884
0885
0886
0887
0888
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919
0920
0921
0922
0923
0924
0925
0926
0927
0928
0929
0930
0931
0932
0933
0934
0935
0936
0937
0938
0939
0940
0941
0942
0943
0944
0945
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956
0957
0958
0959
0960
0961
0962
0963
0964
0965
0966
0967
0968
0969
0970
0971
0972
0973
0974
0975
0976
0977
0978
0979
0980
0981
0982
0983
0984
0985
0986
0987
0988
0989
0990
0991
0992
0993
0994
0995
0996
0997
0998
0999
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
<# File-Server-Migration-Intra-Domain.ps1
 
Purposes:
1. Create Volumes with Labels
2. Create Virtual Clustered File Servers
3. Create SMB Shares on Clustered File Servers
4. Disable caching of certain shares
5. Generate Sources and Destination HashTable Variable
6. Perform File Copy Operation
 
Assumptions:
1. These are to be executed in the context of the System Administrator
2. PowerShell version 5.0 on Windows 2016 is expected
 
Limitations:
1. On "Create Volumes with Labels," PowerShell cannot reliably set disks as online or offline currently. Thus, prior to starting this script, the admin must set disks as online manually; otherwise, any offlined disks will be skipped by the program
2. I still consider myself a newbie at this time. Hence, please optimize/refactor this script without hesitation.
 
#>
 
################################## ↓ Part 1: Create Volumes with Labels ↓ #############################################
 
# Set global variables
$diskLabelsAndIndexes=@(
    @("APP001",14,"A"),
    @("APP002",15,"B"),
    @("APP003",16,"E"),
    @("APP004",17,"F"),
    @("APP005",18,"G"),
    @("APP006",19,"I"),
    @("APP007",20,"J"),
    @("APP008",21,"K"),
    @("APP009",24,"L"),
    @("APP010",22,"M")
) # Set cluster disk label and disk number
$sectorSize=8192 #8K which translates to 32TB max per volume
$driveLetterExclusions="[CDH]" # Scan for next available drive letters, excluding D "CD Rom" and H "Home"
 
# 1. Format disks as defined on variable $clusterDisks
# 2. Assign a drive letter to each item
# 3. Add those volumes into the connected MS Failover Cluster
 
function processDisks{
    param($clusterDisks=$diskLabelsAndIndexes)
    #$allAvailableDisks=Get-WmiObject -Class win32_volume | ?{$_.Name -match "\\\\?\\";}
     
    # Checkpoint: requiring use to understand what's happening
    $warningMessage="Warning: this function will wipe out all data on items inside array $diskLabelsAndIndexes`r`n";
    $warningMessage+="This function requires that the disks to be set online using diskmgmt.msc prior to its execution because current PowerShell commands do not consistently set disks online."
    $confirmed=confirmation;
    if(!$confirmed){
        return $false;
        }else{
            function validateDisksArray{
                $proceed=$false
                $diskIndexes=$diskLabelsAndIndexes|%{$_[1]}
                $diskIndexes|%{try{if(get-disk -Number $_ -ErrorAction Stop){$proceed=$true}}catch{$proceed=$false}}
                return $proceed
            }
     
            function createVolume($name,$number,$letter){
                # Set variables
                $diskNumber=$number
                $diskLabel=$name
                $driveLetter=$letter
                $drivePath=$driveLetter+":"
                #$driveLetterExclusions="[ABCDHKLMPZ]"
                #$availableDriveLetters=ls function:[A-Z]: -n|?{!(test-path $_)}|%{$_[0]}|?{!($_ -match $driveLetterExclusions)}
                #$tempDriveLetter=$availableDriveLetters[$($($availableDriveLetters.Length) -1)]
                #$tempDriveLetter="Z"
                #$tempPath=$tempDriveLetter+":"
     
                write-host "Processing disk number $diskNumber`: set drive letter as $driveLetter & label equals $diskLabel.";
         
                # Clean Disk
                Set-Disk $diskNumber -isOffline $false
                Set-Disk $diskNumber -isReadOnly $false
                Clear-Disk -Number $diskNumber -RemoveData -Confirm:$False
                Update-HostStorageCache
     
 
                # Set partition as GPT
                Initialize-Disk -Number $diskNumber -PartitionStyle GPT -InformationAction SilentlyContinue
         
                # Create a new partition and format it
                #Add-PartitionAccessPath -DiskNumber $diskNumber -PartitionNumber 2 -AccessPath $drivePath
                try{
                    #New-Partition $diskNumber -UseMaximumSize -DriveLetter $tempDriveLetter
                    #Format-Volume -DriveLetter $tempDriveLetter -FileSystem NTFS -AllocationUnitSize $sectorSize -NewFileSystemLabel $diskLabel -Confirm:$false -Force
                    New-Partition $diskNumber -UseMaximumSize -DriveLetter $driveLetter
                    Format-Volume -DriveLetter $driveLetter -FileSystem NTFS -AllocationUnitSize $sectorSize -NewFileSystemLabel $diskLabel -Confirm:$false -Force
                    }catch{
                        write-host "$Error"
                        break;
                        }
                <#
                PS C:\Windows\system32> Format-Volume -DriveLetter $driveLetter -FileSystem NTFS -AllocationUnitSize $sectorSize -NewFil
                eSystemLabel $diskLabel -Confirm:$false -Force
 
                DriveLetter FileSystemLabel FileSystem DriveType HealthStatus OperationalStatus SizeRemaining  Size
                ----------- --------------- ---------- --------- ------------ ----------------- -------------  ----
                F           SIMONICULA-007   NTFS       Fixed     Healthy      OK                        12 TB 12 TB
                #>
 
                Set-Disk $diskNumber -isOffline $false
                Set-Disk $diskNumber -isReadOnly $false
     
                # Set-Partition -DriveLetter $driveLetter -IsActive $true
                <#
                Error:
                PS C:\Windows\system32> Set-Partition -DriveLetter $driveLetter -IsActive $true
                Set-Partition : A parameter is not valid for this type of partition.
 
                Extended information:
                The parameters MbrType and IsActive cannot be used on a GPT disk.
 
                Activity ID: {9b225291-2b3f-43e5-b62f-74a96d8e5dd6}
                At line:1 char:1
                + Set-Partition -DriveLetter $driveLetter -IsActive $true
                + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                    + CategoryInfo          : InvalidArgument: (StorageWMI:ROOT/Microsoft/..._StorageCmdlets) [Set-Partition], CimExce
                   ption
                    + FullyQualifiedErrorId : StorageWMI 41006,Set-Partition
 
                Resolution:
                The command only works with MBR disks - cannot issue it against at GTP type.
                #>
 
                # Use WMI to relabel volumes as native PowerShell currently doesn't have this capability
                try{
                    $disk = Get-WmiObject -Class win32_volume -Filter "Label = '$diskLabel'"
                    }catch{
                        write-host "$Error";
                        break;
                    }
                Set-WmiInstance -input $disk -Arguments @{DriveLetter=$drivePath; Label="$diskLabel"}
 
                #if (Test-Path $tempPath) {Remove-PartitionAccessPath -DiskNumber $diskNumber -PartitionNumber 2 -Accesspath $tempPath}
                }
     
            function addDiskToCluster($name,$number){
                # Test values
                #$number=2
                #$name="Disk 2";
                Get-Disk -Number $number | Add-ClusterDisk | %{$_.name=$name }
                }
 
            if(validateDisksArray){
                # Initialize and create volumes
                $i=0;
                foreach ($disk in $clusterDisks){   
                    #createVolume $($disk[0])  $($disk[1]) $availableDriveLetters[$i++];
                    createVolume $($disk[0])  $($disk[1]) $($disk[2]);
                    #pause;
                    }
 
                # Create report after volumes have been created
                Get-WmiObject -Class win32_volume | select name,blocksize
     
                Write-Host "Please verify that all disks have been online prior to add disks to Clusters."
                pause;
     
                $clusterName=(get-cluster).name   
                $clusterDisks | %{addDiskToCluster -diskObject $_
                    "Please verify the accuracy of this statement and press Enter to accept:`r`n";
                    #pause;
                    $label=$_[0];
                    $diskIndex=$_[1];
                    "Name: $label | Disk Number: $diskIndex | Clustername: $clusterName";
                    try{
                        addDiskToCluster $label $diskIndex;
                        }
                        catch{
                            Write-Host "unable to add disk $label into the cluster $clusterName"
                            }
                    }
            }
    }
}
 
processDisks;
<################################################################################################
Some troubleshooting documentation:
 
using diskpart (manual):
    SELECT DISK 2
    ONLINE DISK
    CLEAN
    CREATE PARTITION PRIMARY
    FORMAT FS=NTFS UNIT=16K QUICK
    ASSIGN LETTER=B  #Change B to any other available access-path letter
    ACTIVE
    EXIT
 
Add to Cluster (manual):
    $numero=7
    $etiqueta="LUN007"
    Get-Disk -Number $numero | Add-ClusterDisk | %{$_.Name=$etiqueta }
 
Report a list of physical disks available on the host:   
PS C:\Windows\system32> Get-WmiObject -Class win32_volume | select name,blocksize
name                                              blocksize
----                                              ---------
C:\                                                    4096
E:\                                                   16384
F:\                                                   16384
G:\                                                   16384
I:\                                                   16384
J:\                                                   16384
N:\                                                   16384
\\?\Volume{3b1730ae-2559-40e3-a547-ae6a91d2d540}\      4096
 
Error:
Add-ClusterDisk : The disk with Id {1}\\TestCluster007\root/Microsoft/Windows/Storage/Providers_v2\WSP_Disk.ObjectId="{4ef8972
8-9924-414d-960a-f09d2ab2155a}:DI:\\?\Disk{6fca7305-68a9-5804-84ed-bf26bd6bfc62}" is unable to be clustered.
At line:1 char:22
+ Get-Disk -Number 7 | Add-ClusterDisk | %{$_.name="APP007" }
+                      ~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_Disk (Obje...Windows/Sto...):CimInstance) [Add-ClusterDisk], Invalid
    OperationException
    + FullyQualifiedErrorId : Add-ClusterDisk,Microsoft.FailoverClusters.PowerShell.AddClusterDiskCommand
 
Resolution:
- Delete the LUNs at the SAN Volumes Manager
- Online disk > partition GPT > format disk as NTFS > assign drive letter > add disk to Cluster
 
Miscellaneous clustering commands:
# $clusterDiskObject=Get-ClusterResource -Cluster $cluster -Name $clusterDiskName
# Put disk in cluster maintenance mode
# $clusterDiskObject | Suspend-ClusterResource
# $clusterDiskObject | Stop-ClusterResource
    <# avoid this error:
Format-Volume : The specified object is managed by the Microsoft Failover Clustering component. The disk must be in
cluster maintenance mode and the cluster resource status must be online to perform this operation.
 
#Clear-ClusterDiskReservation -Disk $diskNumber
#$clusterDiskObject | Start-ClusterResource | Resume-ClusterResource
# Put clustered disk in maintenance mode
# Get volume
# get-partition -DriveLetter C
#New-FileShare -Name $shareName -FileServerFriendlyName $serverName -SourceVolume $Volume -IsContinuouslyAvailable $True -Protocol SMB
 
# If only extracting 1 set of variables
$regexServerName="\\\\(.{1,})\\"
$regexShareName="\\\\.+\\(.{1,})"
for ($i=0;$i -lt $smbShares.to.length;$i++){[void]($smbShares.to[$i] -match $regexServerName);$matches[1];}
for ($i=0;$i -lt $smbShares.to.length;$i++){[void]($smbShares.to[$i] -match $regexShareName);$matches[1];}
 
# Set disk as online via GUI
Run diskmgmt.msc > locate newly created volume > right-click > Online > note the disk number as value for below variable
 
# Set disk name and number
$diskNumber="SELECT_NUMBER_FROM_ABOVE_RESULT"
$diskName="APPLICATION_NAME"
$driveLetter="Pick_An_Available_Drive_Letter"
$tempDriveLetter="A" #Make sure that this letter is currently not in use
$sectorSize=16384 #16K which translates to 64TB max per volume
 
# Create volume
function createVolume{
        # Set variables
        $drivePath=$driveLetter+":"
        $tempPath=$tempDriveLetter+":"
     
        "Processing disk number $diskNumber`: set drive letter as $driveLetter & label equals $diskName"   
    
        # Clean disk
        Clear-Disk -Number $diskNumber -RemoveData -Confirm:$False
 
        # Set partition as GPT
        Initialize-Disk -Number $diskNumber -PartitionStyle GPT -InformationAction SilentlyContinue
         
        # Create a new partition and format it
        New-Partition $diskNumber -UseMaximumSize -DriveLetter $tempDriveLetter
        Format-Volume -DriveLetter $tempDriveLetter -FileSystem NTFS -AllocationUnitSize $sectorSize -NewFileSystemLabel $diskName -Confirm:$false -Force
         
        # Online disk and mark writable
        Set-Disk $diskNumber -isOffline $false
        Set-Disk $diskNumber -isReadOnly $false 
         
        # Use WMI to relabel volumes as PowerShell currently doesn't have this capability
        $disk = Get-WmiObject -Class win32_volume -Filter "Label = '$diskName'"
        Set-WmiInstance -input $disk -Arguments @{DriveLetter=$drivePath; Label="$diskName"}
 
        Remove-PartitionAccessPath -DiskNumber $diskNumber -PartitionNumber 2 -Accesspath $tempPath
        }
createVolume
 
# Add disk to cluster
Get-Disk -Number $diskNumber | Add-ClusterDisk | %{$_.name=$diskName }
 
# Resize volume to its available maximum
$driveLetter="V"
Update-HostStorageCache
$max=(Get-PartitionSupportedSize -DriveLetter $driveLetter).SizeMax
Resize-Partition -DriveLetter $driveLetter -Size $max
 
Error: Remove-PartitionAccessPath : The access path is not valid
Ignore this error until you know what it means. Or try this
Remove-PsDrive -Name $tempDriveLetter -Force
or this
net use /delete "$tempDriveLetter`:" /y
 
###############################################################################################
#>
 
################################## ↑ Part 1: Create Volumes with Labels ↑ #############################################
 
 
################################## ↓ Part 2: Create Virtual Clustered File Servers ↓ #############################################
 
# Specify the servers subnet to scan for available IPs
$serversCidrBlock="500.500.500.1/24"
 
# Obtain drive letters and labels
$suffix="-n";
$driveLetterExclusions="[ABCDHKLMPZ]"
$maxCharsServernameAllowed=15;
$driveLettersAndLabels = Get-WmiObject Win32_Volume -Filter "DriveType=3" |?{$_.DriveLetter -ne $null -and $_.Label -ne $null -and $_.DriveLetter[0] -notlike $driveLetterExclusions}| select DriveLetter,Label | Sort Label;
 
function createClusteredFileServers{
    param(
        $newFileServers=($driveLettersAndLabels|%{ $lettersCount=($_.Label+$suffix).length;
                                        if($lettersCount -lt $maxCharsServernameAllowed){
                                            "$($_.Label)$suffix";
                                            }else{
                                            #($_.Label).length - ($lettersCount-15)
                                            $sliceIndex=($_.Label).length - ($lettersCount-$maxCharsServernameAllowed)                                           
                                            $truncatedLabel=$_.Label.SubString(0,$sliceIndex)
                                            "$truncatedLabel$suffix";
                                            }})
        )
 
    $existingFileServers=get-clusterresource|?{$_.ResourceType -eq "File Server"}|%{[void]($_.Name -match "\\\\(.*)\)");$matches[1]}
     
    function checkIfServerExists{
        param($nameToCheck)    
        if($nameToCheck -in $existingFileServers){return $true}else{return $false}
    }
 
    function scanForAvailableIPs{
        param(
            $cidrBlock=$(
                    $interfaceIndex=(Get-WmiObject -Class Win32_IP4RouteTable | where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} |  Sort-Object metric1).interfaceindex;
                    $interfaceObject=(Get-NetIPAddress -InterfaceIndex $interfaceIndex|select IPAddress,PrefixLength)[0];
                    "$($interfaceObject.IPAddress)/$($interfaceObject.PrefixLength)";
                    )         
            )
 
        function Get-IPrange{
          <# This Get-IPrange function has been obtained at
            Snippet Author: BarryCWT
          .SYNOPSIS 
            Get the IP addresses in a range
          .EXAMPLE
           Get-IPrange -start 192.168.8.2 -end 192.168.8.20
          .EXAMPLE
           Get-IPrange -ip 192.168.8.2 -mask 255.255.255.0
          .EXAMPLE
           Get-IPrange -ip 192.168.8.3 -cidr 24
            #>
  
            param (
          [string]$start,
          [string]$end,
          [string]$ip,
          [string]$mask,
          [int]$cidr
            )
  
            function IP-toINT64 () {
              param ($ip)
  
              $octets = $ip.split(".")
              return [int64]([int64]$octets[0]*16777216 +[int64]$octets[1]*65536 +[int64]$octets[2]*256 +[int64]$octets[3])
            }
  
            function INT64-toIP() {
              param ([int64]$int)
 
              return (([math]::truncate($int/16777216)).tostring()+"."+([math]::truncate(($int%16777216)/65536)).tostring()+"."+([math]::truncate(($int%65536)/256)).tostring()+"."+([math]::truncate($int%256)).tostring() )
            }
  
            if ($ip) {$ipaddr = [Net.IPAddress]::Parse($ip)}
            if ($cidr) {$maskaddr = [Net.IPAddress]::Parse((INT64-toIP -int ([convert]::ToInt64(("1"*$cidr+"0"*(32-$cidr)),2)))) }
            if ($mask) {$maskaddr = [Net.IPAddress]::Parse($mask)}
            if ($ip) {$networkaddr = new-object net.ipaddress ($maskaddr.address -band $ipaddr.address)}
            if ($ip) {$broadcastaddr = new-object net.ipaddress (([system.net.ipaddress]::parse("255.255.255.255").address -bxor $maskaddr.address -bor $networkaddr.address))}
  
            if ($ip) {
              $startaddr = IP-toINT64 -ip $networkaddr.ipaddresstostring
              $endaddr = IP-toINT64 -ip $broadcastaddr.ipaddresstostring
            } else {
              $startaddr = IP-toINT64 -ip $start
              $endaddr = IP-toINT64 -ip $end
            }
  
  
            for ($i = $startaddr; $i -le $endaddr; $i++)
            {
              INT64-toIP -int $i
            }
 
        }
 
        # Regex values
        $regexIP = [regex] "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
        $regexCidr=[regex] "\/(.*)"
        $regexFourthOctetValue=[regex] ".+\..+\..+\.(.+)"
 
        # Value Extractions
        $ip=$regexIP.Matches($cidrBlock).Value
        $cidr=$regexCidr.Matches($cidrBlock).Groups[1].Value
        $allIPs=Get-IPrange -ip $ip -cidr $cidr
 
        # Remove fourth octet values matching 0,1, and 255
        if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 0){$first, $rest= $allIPs; $allIPs=$rest;}
        if($regexFourthOctetValue.Matches($allIPs[0]).Groups[1].Value -eq 1){$first, $rest= $allIPs; $allIPs=$rest;}   
        if($regexFourthOctetValue.Matches($allIPs[$allIPs.length-1]).Groups[1].Value -eq 255){$allIPs = $allIPs | ? {$_ -ne $allIPs[$allIPs.count-1]}}
 
        # Display sweep scanning output
        #$allIPs | ForEach-Object {if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*)){$_}}
 
        # Collect unpingable IPs
        "Collecting available IPs. Please wait awhile..."
        $GLOBAL:availableIPs=$allIPs | ForEach-Object { if(!(Get-WmiObject Win32_PingStatus -Filter "Address='$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*)){
                                                            write-host "$_ is available.";
                                                            $_;}else{write-host "$_ is NOT available.";}
                                                        }
         
        # Also, export unavailableIPs just because I can
        $GLOBAL:unavailableIPs=Compare-Object $allIPs $availableIPs -PassThru
        }
    if(!($availableIPs)){scanForAvailableIPs};
    #$availableIPs;   
 
    # Proceed to create virtual file servers
    $i=0;
    for ($i=0;$i -lt $newFileServers.count;$i++){
        $serverName=$newFileServers[$i];
        $availableIP=[string]$availableIPs[$i];       
        $vServerLabel=$driveLettersAndLabels[$i].Label;
        if(!(checkIfServerExists $serverName)){
            Write-Host "Verify the accuracy of this statement. Press any key to commit.";
            Write-Host "Add-ClusterFileServerRole -Name $serverName -StaticAddress $availableIP -Storage $vServerLabel";
            pause;
            Add-ClusterFileServerRole -Name $serverName -StaticAddress $availableIP -Storage $vServerLabel
            "$serverName processed.";
            }else{
                Write-Host "$vServerLabel already exists. Skipping this item."
                }
    }
}
 
if($driveLettersAndLabels){createClusteredFileServers};
 
################################## ↑ Part 2: Create Virtual Clustered File Servers ↑ #############################################
 
################################## ↓ Part 3: Create SMB Shares on Clustered File Servers ↓ #############################################
 
# This section allows three types of inputs:
# (a) Manual entries of file shares
# (b) Specifying standalone file server(s) and
# (c) Identifying the clustername to retrieve SMB Shares
 
# Set SMB Shares manually:
$manualShares=@();
$manualShares+=[PSCustomObject]@{ShareFolder="PUBLIC";ServerName="SHERVER007";ShareName="PUBLIC";Description=""};
$manualShares+=[PSCustomObject]@{ShareFolder="NOTPUBLIC";ServerName="SHERVER700";ShareName="NOTPUBLIC";Description=""};
 
# Retrieve shares from standalone servers
# Automatically populate lists of all volumes, sharenames, and descriptions of the cluster(s) to be migrated from
$standaloneFileServers="RAMBO01"
$standaloneFileServerShares=@()
if ($standaloneFileServers){
$standaloneFileServerShares=$standaloneFileServers|%{Get-WmiObject Win32_Share -computername $_ |?{$_.Name -notlike "*$" -and $_.Path -match "^\w{1}\:\\.*"}|`
                            select @{name="ShareFolder";Expression={$_.Name}},`
                            @{name="ServerName";Expression={$_.PSComputerName}},`
                            @{name="ShareName";Expression={$_.Name}},`
                            Description}
}
 
# Retrieve shares from clusters
$sourceClusters="CLUSTER08.KIMCONNECT.local"
$clusterShares=@()
if ($sourceClusters){
    #$nodes=$sourceClusters|%{$_;get-clusternode -cluster $_}
    $nodes=$sourceClusters|%{get-clusternode -cluster $_}
    $computerNames=$nodes.Name
    #$computerNames=$nodes|group|Select -ExpandProperty Name
    #$smbShares=$computerNames|%{Get-WmiObject Win32_Share -computername $_ | FT  -Property Path,Name,Caption}
    $regexServerName="\\\\(.{1,})\\";
    $regexShareName="\\\\(.{1,})\\(.{1,})";
    $clusterShares=$computerNames|%{try{
                                        write-host "scanning $_`...";
                                        Get-WmiObject Win32_Share -computername $_ |?{$_.Name -notlike "*$"}|`
                                        select `
                                        @{name="ShareFolder";Expression={$folderName=$_.Path.SubString(3,$_.Path.Length-3);
                                                                                if($folderName){$folderName}else{[void]($_.Name -match $regexShareName);$matches[2]}}},`                                        @{name="ServerName";Expression={[void]($_.Name -match $regexServerName);$matches[1]}},`
                                        @{name="ShareName";Expression={[void]($_.Name -match $regexShareName);$matches[2]}},`
                                        Description
                                        }catch{
                                            write-host "$_ has errors";
                                            write-host $Error;
                                            }
                                    }
    }
 
if($clusterShares -and $standaloneFileServerShares -and $manualShares){
    $smbShares=$standaloneFileServerShares+$clusterShares+$manualShares;
    }else{
        if($clusterShares){$smbShares=$clusterShares}
        if($standaloneFileServerShares){$smbShares=$standaloneFileServerShares}
        }
 
#$existingFileServerRoles=get-clusterresource|?{$_.ResourceType -eq "File Server"}|%{[void]($_.Name -match "\\\\(.*)\)$");$matches[1]}
 
Function listEmptyNodes{
    $sourceClusters|%{$_;get-clusternode -cluster $_}
    $emptyNodes=$computernames|%{if(!(Get-WmiObject Win32_Share -computername $_ |?{$_.Name -notlike "*$"})){$_}}
    write-host "These nodes appear to have zero SMB shares:`r`n$emptyNodes"
}
 
 
# These variables may already have been generated from "Part 2: Create Virtual Clustered File Servers"
$suffix="-n";
$maxCharsServernameAllowed=15;
$driveLetterExclusions="[CHKLMPZ]"
 
Function gatherPaths{
 
    $driveLettersAndLabels = Get-WmiObject Win32_Volume -Filter "DriveType=3" |`
        ?{$_.DriveLetter -ne $null -and $_.Label -ne $null -and $_.DriveLetter[0] -notlike $driveLetterExclusions}|`
        select @{Name="DriveLetter";Expression={$_.DriveLetter[0]}},Name,Label | Sort DriveLetter
 
    # Create a map for all file server roles in the standardized format of DriveLetter + ClientAccessPoint Label + Default Shares folder name (e.g. E:\SHERVER01\Shares)
    # Note this is dependent on successful completion of previous steps, where all sub-folder names with ClientAccessPoint labels have been created
    $paths=$driveLettersAndLabels|%{$defaultPath="$($_.Name)$($_.Label)";
                                    $folders=get-childitem $_.Name;
                                        if($folders){
                                            $folders|%{
                                                $subFolderPath= "$($_.FullName)"
                                                mkdir $subFolderPath -ea SilentlyContinue|out-null
                                                $subFolderPath
                                                }
                                            }else{
                                                mkdir $defaultPath -ea SilentlyContinue|out-null;
                                                $defaultPath;
                                                };
                                        }
    return $paths;
}
 
Function createSharesToMatchClientAccessPoints{
    param(
        $shares=$smbShares
        )                               
 
    # Generate Domain Admins label
    $subdomain=(net config workstation) -match 'Workstation domain\s+\S+$' -replace '.+?(\S+)$','$1'
    $domainadmins="$subdomain`\Domain Admins";
 
    function includePrerequisites{
        # Set PowerShell Gallery as Trusted to bypass prompts
        $trustPSGallery=(Get-psrepository -Name 'PSGallery' -ErrorAction SilentlyContinue).InstallationPolicy
        If($trustPSGallery -ne 'Trusted'){
            Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
            }
 
        # Add the required NTFS security module
        if (!(Get-InstalledModule -Name NTFSSecurity -ErrorAction SilentlyContinue)) {
            Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction SilentlyContinue;
            Install-Module -Name NTFSSecurity -Force -ErrorAction SilentlyContinue;
            }
     
        # Add the required Microsoft Clustering PowerShell module
        if (!(get-module -Name "FailoverClusters" -ErrorAction SilentlyContinue)){
            #Install-WindowsFeature Failover-Clustering | out-null;
            Import-Module servermanager
            Add-WindowsFeature RSAT-Clustering
            Install-WindowsFeature RSAT-Clustering-MGMT | out-null;
            Install-WindowsFeature RSAT-Clustering-PowerShell | out-null;
            Import-Module FailoverClusters | out-null;
            }
        }
    includePrerequisites;
 
    $paths=gatherPaths
 
    if(!($paths)){
        write-host "No clustered share volumes are detected. Program will move all roles to this $($env:computername).";
        get-clustergroup|move-clustergroup -node $env:computername;
        $paths=gatherPaths;
        }
 
    # Set the number of pauses for checking
    $checkPause=3;
    foreach ($share in $shares){   
        # Generate variables
        $maxCharsServernameAllowed=15;     
        $smbServer=$( $lettersCount=($share.ServerName+$suffix).length;
                        if($lettersCount -lt $maxCharsServernameAllowed){
                            "$($share.ServerName)$suffix";
                            }else{
                            #($_.Label).length - ($lettersCount-15)
                            $sliceIndex=($share.ServerName).length - ($lettersCount-$maxCharsServernameAllowed)                                           
                            $truncatedLabel=$share.ServerName.SubString(0,$sliceIndex)
                            "$truncatedLabel$suffix";
                            })
        $shareFolder=$share.ShareFolder;
        $shareName=$share.ShareName;
        $smbServerName=$share.ServerName;
        $sharePath=$paths[($paths|%{[void]($_ -match ":\\(.*)");$matches[1]}).IndexOf($smbServerName)]+"\"+$shareFolder
        #$sharePathDriveLetter=$driveLettersAndLabels.DriveLetter[$driveLettersAndLabels.Label.IndexOf($share.ServerName)]
        #$sharePathLabel=$driveLettersAndLabels.Label[$driveLettersAndLabels.Label.IndexOf($share.ServerName)]
        #$sharePath="$sharePathDriveLetter`:\$sharePathLabel\$($share.SharePath)";
        $regexNonAlphaNumeric = '[^a-zA-Z0-9]';
        $description=$share.Description -replace $regexNonAlphaNumeric, ' ';
        $permission = '$domainadmins,Administrators' , 'Full', 'ContainerInherit, ObjectInherit', 'None', 'Allow';
        $rule=New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission
 
        $statement="
            # Create directory and its parents if they do not exists
            New-Item -ItemType Directory -Force -Path '$sharePath';
 
            # Set NTFS Permissions on folder
            Add-NTFSAccess –Path '$sharePath' –Account '$domainadmins',Administrators –AccessRights Full -ErrorAction SilentlyContinue;
 
            # Create the share with associated share permissions
            New-SmbShare -ScopeName $smbServer -Name '$shareName' -Path '$sharePath' -FullAccess '$domainadmins',Administrators -FolderEnumerationMode AccessBased -CachingMode Manual -Description '$description' -Confirm:$('$False');
            Grant-SmbShareAccess -Name '$shareName' -ScopeName $smbServer -AccountName 'Authenticated Users' -AccessRight Full -Force;
            "       
        try{           
            Write-Host "Executing...`r`n $statement";
            if($checkPause -ne 0){pause;$checkPause=$checkPause-1}; 
            invoke-expression $statement -ErrorAction Stop | Out-Null;
            Write-Host "$shareName on $smbServer has been created.";
 
            #pause;
        }catch{
            write-host "$Error";
            break;                      
            }       
 
        }
}
 
do{
    $exitLoop=$False
    $userInput=(Read-Host -Prompt "Type 'Yes' or 'y' to trigger 'createSharesToMatchClientAccessPoints' function").toLower()
    if($userInput -match "^(yes|y)$"){createSharesToMatchClientAccessPoints;$exitLoop=$True;}
    }while ($exitLoop -eq $False)
     
<#
 
# Setting shares manually
New-Item -ItemType Directory -Force -Path 'S:\SHARE005\SCANS';
Add-NTFSAccess –Path 'S:\SHARE005\SCANS' –Account 'INTRANET\Domain Admins',Administrators –AccessRights Full -ErrorAction SilentlyContinue;
New-SmbShare -ScopeName SHARE005-n -Name 'SCANS' -Path 'S:\INTRANET\SCANS' -FullAccess 'INTRANET\Domain Admins',Administrators -FolderEnumerationMode AccessBased -CachingMode Manual -Description '' -Confirm:$False;
Grant-SmbShareAccess -Name 'SCANS' -ScopeName SHARE005-n -AccountName 'Authenticated Users' -AccessRight Full -Force;
 
# To turn OFF caching
$rolesWithNoCaching="SHARE005-n","SHARE006-n"
$rolesWithNoCaching | %{$shares=Get-SMBShare -scopename "$_"; foreach ($share in $shares){if(!($share.Name -like "*$")){"Turning caching OFF for share: $share.Name..."; Set-SMBShare -Name $share.Name -CachingMode None -Confirm:$False;}};}
 
# To turn ON caching
$rolesWithCaching="SHARE007-n"
$rolesWithCaching | %{$shares=Get-SMBShare -scopename "$_"; foreach ($share in $shares){if(!($share.Name -like "*$")){"Turning caching ON for share: $share.Name..."; Set-SMBShare -Name $share.Name -CachingMode Manual -Confirm:$False;}};}
         
# Changing caching mode for a single share
$shareName="SHARE005"
Set-SMBShare -Name $shareName -CachingMode None -Confirm:$False;
Set-SMBShare -Name $shareName -CachingMode Manual -Confirm:$False;
 
# Legend:
-- None: Prevents users from storing documents and programs offline.
-- Manual: Allows users to identify the documents and programs that they want to store offline. Equivalent to "Allow Caching of Shares"
-- Programs: Automatically stores documents and programs offline.
-- Documents: Automatically stores documents offline.
-- BranchCache: Enables BranchCache and manual caching of documents on the
 
# Changing cache settings for Windows 2008R2 or older:
     
# All Files and Programs that users open from the shared folder are automatically available offline. Also, Optimized for performance is enabled.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:Programs")
     
# Only the files and programs that users specify are available offline.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:Manual")
     
# All Files and Programs that users open from the shared folder are automatically available offline. Optimized for performance is not checked.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:Documents")
 
# No files or programs from the shared folder are available offline.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:None")
#>
 
<#
# Get caching mode in 2016
get-smbshare -name "Users" -scopename SHARE005 | select CachingMode
 
# To turn OFF caching
$rolesWithNoCaching="SHARE005-n","SHARE006-n"
$rolesWithNoCaching | %{$shares=Get-SMBShare -scopename "$_"; foreach ($share in $shares){if(!($share.Name -like "*$")){"Turning caching OFF for share: $share.Name..."; Set-SMBShare -Name $share.Name -CachingMode None -Confirm:$False;}};}
 
# To turn ON caching
$rolesWithCaching="SHARE007-n","SHARE008-n"
$rolesWithCaching | %{$shares=Get-SMBShare -scopename "$_"; foreach ($share in $shares){if(!($share.Name -like "*$")){"Turning caching ON for share: $share.Name..."; Set-SMBShare -Name $share.Name -CachingMode Manual -Confirm:$False;}};}
         
# Changing caching mode for a single share
$shareName="SHARE005"
Set-SMBShare -Name $shareName -CachingMode None -Confirm:$False;
Set-SMBShare -Name $shareName -CachingMode Manual -Confirm:$False;
 
# Legend:
-- None: Prevents users from storing documents and programs offline.
-- Manual: Allows users to identify the documents and programs that they want to store offline. Equivalent to "Allow Caching of Shares"
-- Programs: Automatically stores documents and programs offline.
-- Documents: Automatically stores documents offline.
-- BranchCache: Enables BranchCache and manual caching of documents on the
 
# Changing cache settings for Windows 2008R2 or older:
     
# All Files and Programs that users open from the shared folder are automatically available offline. Also, Optimized for performance is enabled.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:Programs")
     
# Only the files and programs that users specify are available offline.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:Manual")
     
# All Files and Programs that users open from the shared folder are automatically available offline. Optimized for performance is not checked.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:Documents")
 
# No files or programs from the shared folder are available offline.
([WMIClass]"\\dc1\root\cimv2:win32_Process").Create("cmd /C net share PS /Cache:None")
 
# How to manually create shares
$shareNames="19"
$smbServer="SHARE005-n"
$description=""
$sharesFolder="S:\Shares";
$subdomain=(net config workstation) -match 'Workstation domain\s+\S+$' -replace '.+?(\S+)$','$1';
$domainadmins="$subdomain`\Domain Admins";
$shareNames|%{
    New-Item -ItemType Directory -Force -Path $($sharesFolder+"\"+$_)
    New-SmbShare -ScopeName $smbServer -Name $_ -Path "$sharesFolder\$_" -FullAccess $domainadmins,Administrators,"Authenticated Users" -FolderEnumerationMode AccessBased -CachingMode Manual -Description $description -Confirm:$False;
    }
#>
 
################################## ↑ Part 3: Create SMB Shares on Clustered File Servers ↑ #############################################
 
################################## ↓ Part 4: Disable caching of certain shares ↓ #############################################
# Specify the exceptions of shares with caching disabled
$sharesWithCachingDisabled=@(
    "SHARE005",
    "SHARE006"
)
 
function disableCaching($smbSharesayOfShares){
    $smbSharesayOfShares|%{set-smbshare -name $_ -CachingMode None -Confirm:$False}
}
 
disableCaching $sharesWithCachingDisabled;
################################## ↑ Part 4: Disable caching of certain shares ↑ #############################################
 
################################## ↓ Part 5: Generate Sources and Destination Array Variable ↓ #############################################
 
# Supporting variables
$regexServerNameAndShareName="\\\\(.{1,})\\(.{1,})";
$suffix="-n";
$maxCharsServernameAllowed=15;
 
# Set Sources and Destinations manually:
$manualSourcesAndDestinations=@();
$manualSourcesAndDestinations+=[PSCustomObject]@{Clustername="CLUSTER007";From="P:\PUBLIC";To="\\SHARE007-n\DUDE";SourceSmb="\\SHARE007\DUDE"};
$manualSourcesAndDestinations+=[PSCustomObject]@{Clustername="CLUSTER007";From="N:\NOTPUBLIC";To="\\SHARE008-n\DUDE";SourceSmb="\\SHARE008\DUDE"};
 
# Setting server names
$standaloneFileServers="STANDALONEFILESERVER3"
$sourceClusters="CLUSTER08","CLUSTER09"
$nodes=$sourceClusters|%{write-host "Scanning $_...";get-clusternode -cluster $_}
$computerNames=$nodes|group|Select -ExpandProperty Name
 
# Generate Sources and Destinations from clusters
$clusteredSourcesAndDestinations=$computerNames|ForEach-Object{
                write-host "Scanning $_..."; Get-WmiObject Win32_Share -computername $_ |?{$_.Name -notlike "*$"}|`
                select `
                @{name="Clustername";Expression={get-wmiobject -class "MSCluster_Cluster" -namespace "root\mscluster" -ComputerName $($_.PSComputerName)|select -ExpandProperty Name}},`
                @{name="SourceSmb";Expression={$_.Name}},`
                @{name="From";Expression={$_.Path}},`
                @{name="To";Expression={$([void]($_.Name -match $regexServerNameAndShareName);
                                            $serverName=$matches[1];
                                            $smbShare=$matches[2];
                                            $lettersCount=($serverName+$suffix).length;
                                            if($lettersCount -lt $maxCharsServernameAllowed){
                                                "\\$serverName$suffix\$smbShare";
                                                }else{                                               
                                                $sliceIndex=($serverName).length - ($lettersCount-$maxCharsServernameAllowed)                                           
                                                $truncatedLabel=$serverName.SubString(0,$sliceIndex)
                                                "\\$truncatedLabel$suffix\$smbShare";
                                                })
                                            }}
                                            }|?{$_.To -ne $null}
 
#  Generate Sources and Destinations from standalone file servers
$standaloneSourcesAndDestinations=$standaloneFileServers|%{Get-WmiObject Win32_Share -computername $_ |?{$_.Name -notlike "*$" -and $_.Path -match "^\w{1}\:\\.*"}|`
                select `
                @{name="Clustername";Expression={get-wmiobject -class "MSCluster_Cluster" -namespace "root\mscluster" -ComputerName $($_.PSComputerName)|select -ExpandProperty Name}},`
                @{name="SourceSmb";Expression={"\\$($_.PSComputerName)\$($_.Name)"}},`
                @{name="From";Expression={$_.Path}},`
                @{name="To";Expression={$( $serverName=$_.PSComputerName;
                                            $smbShare=$_.Name;
                                            $lettersCount=($serverName+$suffix).length;
                                            if($lettersCount -lt $maxCharsServernameAllowed){
                                                "\\$serverName$suffix\$smbShare";
                                                }else{                                               
                                                $sliceIndex=($serverName).length - ($lettersCount-$maxCharsServernameAllowed)                                           
                                                $truncatedLabel=$serverName.SubString(0,$sliceIndex)
                                                "\\$truncatedLabel$suffix\$smbShare";
                                                })
                                            }}}
 
$sourcesAndDestinations=$clusteredSourcesAndDestinations+$standaloneSourcesAndDestinations+$manualSourcesAndDestinations
 
################################## ↑ Part 5: Generate Sources and Destination Array Variable ↑ #############################################
 
################################## ↓ Part 6: Perform File Copy Operation ↓ #############################################
 
# Retrieve the $sourcesAndDestinations Object from "Part 5" prior to proceeding further
function validateDestinations{
    param($inputData=$sourcesAndDestinations)
    $objectLength=$inputData.from.length
    for ($i=0;$i -lt $objectLength; $i++){       
        #$from=$inputData.from[$i]
        $to=$inputData.to[$i]
        #"Checking $from and $to ..."
        #if(!(test-path $from) -OR !(test-path $to) ){
        if(!(test-path $to) ){
            write-host "Record corresponding to $to is not reachable."   
            # Remove row if any path doesn't resolve. Overcome limitations of Powershell's immutable array "fixed size" using this workaround
            $castedArrayList=[System.Collections.ArrayList]$inputData;
            $castedArrayList.RemoveAt($i);
            $inputData=[Array]$castedArrayList; #reverse the casting and reassign to original Array
            $objectLength--;
            $i--;
            } #else{write-host "$to is reachable."}
    }
    return $inputData
}
 
$validatedData=validateDestinations -inputData $sourcesAndDestinations
 
Function FindDuplicates{
    param(
        $originalArray,
        $subArrayWithDuplicates
        )
 
    function FindDuplicatesInArray{
        param(
            $array
            )  
        $hash = @{ }
        $duplicates = @()
        for ($i=0;$i -lt $array.Count;$i++){
            $item=$array[$i];
            try{
                $hash.add($item, 0)
                }
            catch [System.Management.Automation.MethodInvocationException]{          
                $duplicates += $array[$i]
                }
            }   
        return $duplicates
        }
 
    function returnDuplicateRecords{
        param(
            $duplicates,
            $sourceArray
            )
        $duplicateRecords=@();
        for ($i=0;$i -lt $duplicates.count;$i++){
            $x=$duplicates[$i]
            for ($j=0;$j -lt $sourceArray.Count;$j++){           
                if ($x -like $sourceArray[$j].From){$duplicateRecords+=$sourceArray[$j]}
            }
        }
        return $duplicateRecords
    }
    $duplicates=FindDuplicatesInArray $subArrayWithDuplicates
    $duplicateRecords=returnDuplicateRecords -duplicates $duplicates -sourceArray $originalArray
    return $duplicateRecords
}
 
for ($col=0;$col -le $validatedData.length;$col++){
    for ($row=0;$row -le $array[$col].length;$row++){
        echo $validatedData[$col][$row]
    }
}
# I currently don't know how to retrieve the number of columns to set the number of $columns-1 as the variable for $passes
$duplicatesPass1=FindDuplicates -originalArray $validatedData -subArrayWithDuplicates $validatedData.From
$duplicatesPass2=FindDuplicates -originalArray $duplicatesPass1 -subArrayWithDuplicates $duplicatesPass1.Clustername
if($duplicatesPass2){"These records have duplicated sources:`r`n$duplicatesPass2"}
 
function constructHashTable($array){
    $hash="`$arr=@{};
`$arr['from']=@{}; `$arr['to']=@{};
`$arr['from']=@('$($array[0].from)'); `$arr['to']=@('$($array[0].to)');
    "
    for ($i=1;$i -lt $array.length;$i++){
        $hash+="`r`n`$arr['from']+='$($array[$i].from)'; `$arr['to']+='$($array[$i].to)';";
    }
    return $hash
}
 
$hashTableConstructor=constructHashTable $validatedData
# $hashTableConstructor
 
 
function createArrayConstructor($array){
    $arrayConstructor="`$arr=@();"
    for ($i=0;$i -lt $array.length;$i++){
        $arrayConstructor+="`r`n`$arr+=[PSCustomObject]@{Clustername='$($array[$i].Clustername)';From='$($array[$i].From)';To='$($array[$i].To)'};";
    }
    return $arrayConstructor
}
 
$systemArrayConstructor=createArrayConstructor $validatedData
$systemArrayConstructor
 
# Proceed to plugin the hashTableConstructor into the file-copy operations (a different script)
 
################################## ↑ Part 6: Perform File Copy Operation  ↑ #############################################
 
################################## ↓ Part 7: Copy SMB Share Permissions ↓ #############################################
 
# Please run "Part 5: Generate Sources and Destination Array Variable" prior to proceeding
$dateStamp = Get-Date -Format "yyyy-MM-dd-hhmmss"
$logFile="C:\copySmbPermissions-Log-$dateStamp.txt"
$GLOBAL:logMessages="";
 
function copySmbPermissions{
    param(
        [string]$sourceSmbSharePath,
        [string]$destinationSmbSharePath
        )
 
    # Set some variables
    $sourceSmbServerName = $sourceSmbSharePath.split("\")[2];
    $sourceSmbShareName = $sourceSmbSharePath.split("\")[3];
    $destinationSmbServerName = $destinationSmbSharePath.split("\")[2];
    $destinationSmbShareName = $destinationSmbSharePath.split("\")[3];
    $GLOBAL:messages="";
 
    # Legacy method to obtain SMB share permissions that would work with PowerShell 2.0 (Windows 2008)
    function getSmbPermmissions{
        param(
            [string]$smbServerName,
            [string]$smbPath
            )
        $smbShareName = $smbPath.split("\")[3]
        $smbList = Get-WmiObject win32_LogicalShareSecuritySetting -ComputerName $smbServerName|?{$_.Name -notlike "*$"}
        if($smbList){
            $sample=$smbList.Name[0];
            if($sample -match "^\\\\(.*)"){
                # This accounts for Clustered File Server Role
                $smbObject=$smbList|?{$_.Name -eq $smbPath};
                }else{
                    # This accounts for Standalone File Server Role
                    $smbObject=$smbList|?{$_.Name -eq $smbShareName};
                    }
            }else{
                $message="Failed to retrieve SMB Permissions from $smbServerName";
                $GLOBAL:messages+=$message+"`r`n";
                write-host $message -ForegroundColor Yellow;
                $smbObject=$false;
                }
 
        if($smbObject){
            $message="Collecting share permissions for $smbPath...";
            $GLOBAL:messages+=$message+"`r`n";
            Write-Host $message;
            $smbPermissions = @()
            $acls = $smbObject.GetSecurityDescriptor().Descriptor.DACL
            foreach($acl in $acls){
                $user = $acl.Trustee.Name
                if(!($user)){$user = $acl.Trustee.SID}
                $domain = $acl.Trustee.Domain
                switch($acl.AccessMask){
                    2032127 {$accessRight = "Full"}
                    1245631 {$accessRight = "Change"}
                    1179817 {$accessRight = "Read"}
                    }         
                $smbPermissions+=[PSCustomObject]@{IdentityReference="$domain\$user";AccessRight=$accessRight};
                }
            return $smbPermissions;
            }else{
                return $false;
                }
    }
 
    # This function requires PowerShell 4.0 and higher
    function setSmbPermissions{
        param(
            $smbName=$destinationSmbShareName,
            $fileServerRole=$destinationSmbServerName,
            $smbPermissions=$sourceSmbPermissions
            )
        # Locate the host for the file server role
        $roleOwner=(Get-ClusterResource -Name $fileServerRole -ErrorAction SilentlyContinue).OwnerNode.Name
         
        if ($roleOwner){
            # Connect to host
            $message="Connecting to remote computer $roleOwner...";
            $GLOBAL:messages+=$message;
            write-host $message;
            $maxTime=10; $duration=0;
            do{
                $session = New-PSSession -ComputerName $roleOwner -ErrorAction SilentlyContinue;
                if (!($session)){
                    write-host "." -NoNewline;
                    $duration++;
                    sleep -seconds 1;
                    }
                if ($session){
                    $message=".. Connected in $duration seconds.";
                    $GLOBAL:messages+=$message+"`r`n";
                    write-host $message -NoNewline;
                    }
                } until ($session.state -match "Opened" -or $duration -eq $maxTime)
 
            if($session){
                $message="Setting share permissions for $smbName of $fileServerRole, currently owned by $roleOwner...";
                $GLOBAL:messages+=$message+"`r`n";
                Write-Host $message;
                $invokeCommandResult=Invoke-Command -Session $session -ScriptBlock{
                            param($smbName,$fileServerRole,$smbPermissions)
 
                            # Declare some variables;
                            [int]$successCount=0;
                            [int]$failuresCount=0;
                            [bool]$singleItem=$smbPermissions.Count -eq $null -or $smbPermissions.Count -eq 1;
                            [string]$sessionMessages="";
 
                            foreach ($permission in $smbPermissions){
                                $identityReference=$permission.IdentityReference;
                                # This accounts for non-domain accounts
                                if($identityReference -match "^\\[^\\]+$"){$identityReference=$identityReference.SubString(1,$identityReference.Length-1)}
                                $accessRight=$permission.AccessRight;
                                $expression="Grant-SmbShareAccess -Name $smbName -ScopeName $fileServerRole -AccountName '$identityReference' -AccessRight $accessRight -Force";
 
                                # Using self executing anonymous function to exit try-loop upon failures
                                .{
                                    try{
                                        $success=Invoke-Expression $expression;
                                        if(!($success)) {
                                            $failuresCount++;                                      
                                            $success=$false;
                                            return; # Exit try-loop
                                            }
                                        $successCount++;                                    
                                        $success=$true;                             
                                        }
                                    catch{
                                        write-host $Error;
                                        }                     
                                }
                            if($success){
                                $message="$expression => Success";
                                $sessionMessages+=$message+"`r`n";
                                write-host $message;
                                }else{
                                    $message="$expression => Failure"
                                    $sessionMessages+=$message+"`r`n";
                                    write-host $message -ForegroundColor Yellow;
                                    }
                            }
 
                            if ($singleItem){
                                $message="$successCount of 1 permission set is successful.";
                                $sessionMessages+=$message+"`r`n";
                                write-host $message;
                                }else{
                                    $message="$successCount of $($smbPermissions.Count) permission settings are successful.";
                                    $sessionMessages+=$message+"`r`n";
                                    write-host $message;                                   
                                    }
                            $overallResult=$failuresCount -eq 0;
                            $outputArray=@($overallResult,$sessionMessages)
                            return $outputArray;
                        } -Args $smbName,$fileServerRole,$smbPermissions
                Remove-PSSession $session;
 
                $GLOBAL:messages+=$invokeCommandResult[1]+"`r`n";               
                $result=$invokeCommandResult[0];               
                }else{
                    $message="Unable to connect to $roleOwner.";
                    $GLOBAL:messages+=$message+"`r`n";
                    write-host $message -ForegroundColor Red;
                    $result=$false;
                    }
            }else{
                    $message="Unable to get owner node for $fileServerRole.";
                    $GLOBAL:messages+=$message+"`r`n";
                    write-host $message -ForegroundColor Red;
                    $result=$false;
                    }
        return $result;
        }
 
    $sourceSmbPermissions=getSmbPermmissions -smbServerName $sourceSmbServerName -smbPath $sourceSmbSharePath
    if ($sourceSmbPermissions){
        $success=setSmbPermissions -smbName $destinationSmbShareName -fileServerRole $destinationSmbServerName -smbPermissions $sourceSmbPermissions
        if ($success){
            $message="Permissions from $sourceSmbSharePath have been successfully copied to $destinationSmbSharePath.";
            $GLOBAL:messages+=$message+"`r`n";
            write-host $message;
            return $true;
                }else{
                $message="Unable to *SET* SMB Permissions to destination $destinationSmbSharePath.";
                $GLOBAL:messages+=$message+"`r`n";
                write-host $message -ForegroundColor Red;
                return $false;
                }
        }else{
            $message="Unable to *GET* SMB Permissions from $sourceSmbSharePath.";
            $GLOBAL:messages+=$message+"`r`n";
            write-host $message -ForegroundColor Yellow;
            return $false;
            }
}
 
foreach ($item in $sourcesAndDestinations){
    # This part could be further optimized by grouping all SMB paths by role/servername and copying permissions of the whole group in one batch
    $sourceSmbPath=$item.SourceSmb
    $destinationSmbPath=$item.To
    $expression="copySmbPermissions -sourceSmbSharePath $sourceSmbPath -destinationSmbSharePath $destinationSmbPath";
    $successfulPass=Invoke-Expression $expression;
    if($successfulPass){
        write-host "$expression => succeeded!`r`n";
        }else{
            write-host "$expression => failed!`r`n" -ForegroundColor Red
            }
    $logMessages+=$messages;
    Add-Content $logFile $messages;
}
 
<#
# Manually revoking SMB Share access of an account (after moving all roles onto 'this' node)
$currentSmbShares=get-smbshare|?{$_.Name[$_.Name.Length-1] -ne '$' -and $_.Path[0] -ne 'c'}
$currentSmbShares|%{Revoke-SmbShareAccess -Name $_.Name -ScopeName $_.ScopeName -AccountName 'Authenticated Users' -Force}
#>
################################## ↑ Part 7: Copy SMB Share Permissions  ↑ #############################################
 
 
################################## ↓ Part 8: Remove the 260 Characters Path Limitation ↓ #############################################
 
$newClusters="CLUSTER08","CLUSTER09"
$newNodes=$newClusters|%{get-clusternode -cluster $_}
$newComputerNames=$newNodes|group|Select -ExpandProperty Name
 
# This function increases the default windows 260 characters path length limit to 1024
Function remove260CharsPathLimit{
    param(
        [string]$computerName=$env:computername
        )   
    # Declare static variables
    $registryHive= "SYSTEM\CurrentControlSet\Control\FileSystem"
    $keyName = "LongPathsEnabled"
    $value= 1
     
    # The legacy command-line method
    #$result=REG ADD "\\$computerName\HKLM\$registryHive" /v $keyName /t REG_DWORD /d $value /f
    #if($result){"\\$computerName\HKLM\$registryHive\$keyName has been added successfully."}
 
    #The PowerShell Method to set remote registry key
    $registryHive="SYSTEM\CurrentControlSet\Control\FileSystem"
    $keyName="LongPathsEnabled"
    $value=1
    $remoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computerName)
    $remoteHive = $remoteRegistry.OpenSubKey($registryHive,$True)
    $remoteHive.CreateSubKey($keyName)|out-null
    $remoteKeyValue = $remoteRegistry.OpenSubKey("$registryHive\$keyName",$True)
    $remoteKeyValue.SetValue($keyName,$value)
 
    # Validation
    $resultKey=$remoteRegistry.OpenSubKey("$registryHive\$keyName")   
    if($resultKey.GetValue($keyName) -eq $value){"\\$computerName\HKLM\$registryHive\$keyName has been added successfully."}
    }
 
# This reverses the effects of that previous function
Function restore260CharsPathLimit{
    param([string]$computerName=$env:computername)
 
    $registryHive= "SYSTEM\CurrentControlSet\Control\FileSystem"
    $keyName = "LongPathsEnabled"
    $result=REG DELETE "\\$computerName\HKLM\$registryHive" /v $keyName /f
    if($result){"\\$computerName\HKLM\$registryHive\$keyName has been removed successfully."}
    }
 
$newComputerNames|%{remove260CharsPathLimit $_}
 
    #This method only works locally
    #$registryHive="REGISTRY::HKLM\SYSTEM\CurrentControlSet\Control\FileSystem"
    #$registryKey="LongPathsEnabled"
    #$value=1
    #New-ItemProperty -Path $registryPath -Name $registryHive -Value $value -PropertyType DWORD -Force -ea SilentlyContinue
    #Verify result
    #Get-Item "REGISTRY::HKLM\$registryHive"
     
    # WMI method
    #$HKEY_LOCAL_MACHINE = 2147483650 #Set unique ID for Registry hive of local machine
    #$registryClass = [WMIClass]"ROOT\DEFAULT:StdRegProv"
    #$keyName = "LongPathsEnabled"
    #$value     = 1
    #$registryHive       = "SYSTEM\CurrentControlSet\Control\FileSystem"
    #$createRegistryKey   = $registryClass.SetExpandedStringValue($HKEY_LOCAL_MACHINE, $registryHive, $keyName, $value)
    #If ($createRegistryKey.Returnvalue -eq 0) {"REGISTRY::HKLM\$registryHive\$keyName has been created with the value of $value"}
 
################################## ↑ Part 8: Remove the 260 Characters Path Limitation  ↑ #############################################
 
 
################################## ↓ Part 9: Create Scheduled Tasks on Source Servers ↓ ###############################################
# Scheduled-tasks-remote.ps1
# Purpose: to add a schedule task onto remote Windows system(s)
# Requires: PowerShell 3.0 or higher at the Jump box. Powershell 2.0 or higher at the targets.
 
# Set variables:
$scriptFile="\\snapshots\FileServerClusters\File_Copy_Script.ps1";
$description="File Copy Operations";
$taskName="File_Copy_Operations";
[DateTime]$timeToStartTasks = '6:00pm';
#$standaloneFileServers="STANDALONEFILESERVER3";
$sourceClusters="CLUSTER01.kimconnect.local";
 
$clusterNodes=($sourceClusters|%{get-clusternode -cluster $_})|group|Select -ExpandProperty Name
$allNodes=$clusterNodes+$(if($standaloneFileServers){$standaloneFileServers})
 
# Credentials
#$user=Read-Host -Prompt "Input $env:USERDOMAIN administrator's username"
$user="$env:UserName"
$domainAccount="$env:UserDomain`\$user"
$plainTextPassword=Read-Host -Prompt "Input the password for $domainAccount"
$password=ConvertTo-SecureString -String $plainTextPassword -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $domainAccount,$password
 
function enableRemoteWinRM{
  Param([string]$computername)
 
  Write-Host "checking $computername..."
 
  function pingTest{
      Param([string]$node)
      try{
        Return Test-Connection $node -Count 1 -Quiet -ea Stop;
      }
      catch{Return $False}
    }
 
  if (pingTest $computername){
      if (!(Test-WSMan $computername -ea SilentlyContinue)){
        if(!(get-command psexec)){
            if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
                Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
                }
            choco install sysinternals -y
            }
        psexec.exe \\$computername -s C:\Windows\system32\winrm.cmd qc -quiet
        }else{Write-Host "WinRM has been already enabled. No changes to WinRM have been made."}
    }
  Else{Write-Host "Unable to determine if WinRM is enabled on $computername`.`n Ping test has failed. Check if this computer is online and whether there's a firewall blocking of ICMP";}
 
  $winRMEnabled=test-netconnection $computername -CommonTCPPort WINRM -InformationLevel Quiet
  if ($winRMEnabled){
    write-host "WinRM has been abled on $computerName - Passed!";
    }else{
        write-host "WinRM was NOT reachable via port 5985 of $computerName - Failed!";
        }
}
 
$allNodes|%{if ($_){enableRemoteWinRM $_}} ;
 
function setScheduledTasks{
    param($servers=$allNodes)
 
    function isUnc($path){
        $GLOBAL:uncServer=$scriptFile | select-string -pattern "(?<=\\\\)(.*?)(?=\\)" | Select -ExpandProperty Matches | Select -ExpandProperty Value
        if ($uncServer){return $True}else{return $False}
    }
 
    function isDomainAdmin($account){
        if (!(get-module activedirectory)){Install-WindowsFeature RSAT-AD-PowerShell -Confirm:$false}
        if((Get-ADUser $account -Properties MemberOf).MemberOf -match 'Domain Admins'){return $True;}else{return $false;}
    }
 
    function isValidCred($u,$p){
        # Get current domain using logged-on user's credentials
        $domain = "LDAP://" + ([ADSI]"").distinguishedName
        $domainCred = New-Object System.DirectoryServices.DirectoryEntry($domain,$u,$p)
        if ($domainCred){return $True}else{return $False}
    }
                                                                                                                                                                                                                                                                           if ((isDomainAdmin $user)-AND (isValidCred $user $password)){
    if (isUnc $scriptFile){
        foreach ($computer in $servers){
            "Processing $computer...";
            $result=Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock{
                param($scriptFile,$taskName,$description,$user,$password,$uncServer,$timeToStart)
                # Debug
                "Running with these variables:`n"
                "`nUserID: $user"
                "`nScript: $scriptFile"
                "`nTask name: $taskName"
                "`nDescription: $description"
                "`nUNC server: $uncServer"
                #
                $username="$user"
 
                # Execute this sequence if the detected PowerShell version is 3.0 or greater
                #$powershellVersion=$PSVersionTable.PSVersion.Major
                $osName=(Get-WmiObject -class Win32_OperatingSystem).Caption
                $windowsVersionNumber=[System.Environment]::OSVersion.Version.Major
                switch ($windowsVersionNumber){
                    5{
                        "$osName is detected.`r`nNow running commands basing on features available in this version...";
                        #$Moss_backupjob_filename = 'd:\MOSS_Backup.bat';
                        $HostName = $env:computername;
                        $TaskRun = "C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -noprofile -ExecutionPolicy Bypass $scriptFile";
                        $startIn=split-path $scriptFile -Parent;
                        schtasks /create /s $hostname /ru $username /rp $password /tn $taskName /tr $TaskRun /sc daily /st $timeToStart.ToString('HH:mm')
                        break;
                        }
                    6{
                        "$osName is detected.`r`nNow running commands basing on features available in this version...";                  
                        $TaskDescription = $description
                        $TaskCommand = "powershell.exe"
                        $TaskScript = $scriptFile
                        $TaskArg = "-noprofile -ExecutionPolicy Bypass -file $TaskScript";
                        $startIn=split-path $TaskScript -Parent;
                        #$TaskStartTime = [datetime]::Now.AddMinutes(60)
                        $TaskStartTime = $timeToStart
                        $service = new-object -ComObject("Schedule.Service")
                        $service.Connect()
                        $rootFolder = $service.GetFolder("\")
                        $TaskDefinition = $service.NewTask(0)
                        $TaskDefinition.RegistrationInfo.Description = $TaskDescription
                        $TaskDefinition.RegistrationInfo.Author = $taskRunAsuser
                        $TaskDefinition.Settings.Enabled = $true
                        $TaskDefinition.Settings.AllowDemandStart = $true
                        $TaskDefinition.Settings.ExecutionTimeLimit = "PT0S"
                        $TaskDefinition.Principal.RunLevel = 1
                        $triggers = $TaskDefinition.Triggers                   
                        $trigger = $triggers.Create(2)
                        $trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
                        $trigger.Enabled = $true
                        $action = $TaskDefinition.Actions.Create(0)
                        $action.Path = $TaskCommand
                        $action.Arguments = $TaskArg
                        $action.WorkingDirectory = $startIn
                        $rootFolder.RegisterTaskDefinition($TaskName,$TaskDefinition,6,$username,$password,1)
                        break;
                        }
                   default{
                        "$osName is detected.`r`nNow running commands basing on features available in this version...";
                        $settingsCommand = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit 0
                        $callPowerShell = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-noprofile -ExecutionPolicy Bypass $scriptFile"
                        $startIn=split-path $scriptFile -Parent;
                        $dailyTrigger =  New-ScheduledTaskTrigger -Daily -At $timeToStart
 
                        # Unrestrict this Domain Administrator from security prompts
                        Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted -Force                  
 
                        # Unblock file & Ensure that script exists
                        <# Overcome error caused by double hop issue:
                        Cannot find path '\\snapshots\FileServerClusters\Daily-VSS-Snapshot.ps1' because it does not exist.
                        + CategoryInfo          : ObjectNotFound: (\\snapshots\Fil...SS-Snapshot.ps1:String) [Unblock-File], ItemNotFoundException
                        + FullyQualifiedErrorId : FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand
                        + PSComputerName        : SHERVER007
 
                        1. Run scheduled task as: New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-ExecutionPolicy Bypass $scriptFile"
                        2. Unblock-File -Path $scriptFile
                        #>      
                        if ((Invoke-Command -computername $uncServer -Credential $Using:cred -ScriptBlock{Unblock-File -Path $Args[0];Test-Path $Args[0] -ErrorAction SilentlyContinue}-Args $scriptFile) -eq $False) {"Errors locating $scriptFile... Skipping";break;}
 
                        # Unregister the Scheduled task if it already exists
                        Get-ScheduledTask $taskName -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false;
 
                        # Create new scheduled task
                        Register-ScheduledTask -Action $callPowerShell -WorkingDirectory $startIn -Trigger $dailyTrigger -TaskName $taskName -Description $description -User $username -Password $password -Settings $settingsCommand -RunLevel Highest;
                        break;
                        }
                    }                    
                } -ArgumentList $scriptFile,$taskName,$description,$domainAccount,$plainTextPassword,$uncServer,$timeToStartTasks
             
            if($result){write-host "$computer scheduled task setup - Success!"}else{write-host "$computer scheduled task setup: Failed!"}
            #pause;
            $timeToStartTasks = $timeToStartTasks.AddMinutes(1)
        }
    }
    }else{
        "Need to run this program with a valid Domain Administrator account."
        }
}
 
setScheduledTasks $allNodes
 
################################## ↑ Part 9: Create Scheduled Tasks on Source Servers ↑ #############################################
 
 
################################## ↓ Part 10: Cutover Functions ↓ ###################################################################
 
###############################################################################################
# Granting Authenticated Users full SMB access to non-admin shares
$nonAdminShares=(get-smbshare).name |?{$_[$_.length-1] -ne "$" }
$nonAdminShares|%{Grant-SmbShareAccess -Name "$_" -AccountName "Authenticated Users" -AccessRight Full -Force}
 
# Copying SMB access permission from a share to another
$sourceSmb="SHARE006"
$sourceServerName="NODE12"
$destinationSmb="SHARE006-N"
$destinationServerName="NODE008"
$sourcePermissions=Get-SmbShareAccess -Name $sourceSmb -ScopeName $sourceServerName
foreach ($permission in $sourcePermissions){
    $account=$permission.AccountName
    $access=$permission.AccessRight
    Grant-SmbShareAccess -Name $destinationSmb -ScopeName $destinationServerName -AccountName "$account" -AccessRight $access -Force
    }
 
# Using emcopy to copy all files from DirectoryA to DirectoryB, while excluding some folders
$fromDirectory="X:\"
$toDirectory="\\node008\b$\app007"
$excludeFolders="X:\nocopy","X:\necopo"
emcopy '$fromDirectory' '$toDirectory' *.*  /s /o /a /i /d /c /th 32 /r:0 /w:0 /xd $($excludeFolders -join ' ')
 
 
# Get Cluster Nodes
$clusterName="SOMECLUSTER"
$roleName="SOMEROLE"
$nodes=get-clusternode -cluster $clusterName
 
# Discover connected computers to port 445 (SMB)
invoke-command -computername 'NODE008' -ScriptBlock {
    $connectedComputers=get-nettcpconnection -LocalPort 139,445|select-object @{Name="ComputerName";Expression={[System.Net.dns]::GetHostbyAddress($_.RemoteAddress).HostName;}};
    return $connectedComputers;
    }
 
invoke-command -computername $server -ScriptBlock {
    param($checkTcpConnection,$port)
#$connectedComputers=get-nettcpconnection -LocalPort 139,445 | ?{$_.RemoteAddress -notmatch "(0.0.0.0)|(::)|(127.0.0.1)"};
[ScriptBlock]::Create($checkTcpConnection).invoke($port);
$connectedComputers|%{[System.Net.dns]::GetHostbyAddress($_.RemoteAddress).Hostname}
} -arg ${function:Check-TcpConnection},$port
 
################################
 
Disable-NetAdapterBinding -Name "Your network adapter name" -DisplayName "File and Printer Sharing for Microsoft Networks"
Enable-NetAdapterBinding -Name "Your network adapter name" -DisplayName "File and Printer Sharing for Microsoft Networks"
 
################################
 
# Get list of nodes in this cluster
$clusterNodes=get-clusternode|group|Select -ExpandProperty Name
 
# Disable Controlled Folder Access
$clusterNodes=get-clusternode|group|Select -ExpandProperty Name
$clusterNodes|%{invoke-command -computername $_ -scriptBlock {Set-MpPreference -EnableControlledFolderAccess Disabled}}