-
Notifications
You must be signed in to change notification settings - Fork 73
/
OneDriveMapper.ps1
3556 lines (3354 loc) · 173 KB
/
OneDriveMapper.ps1
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
##OneDrive Map to Drive Letter
param(
[Switch]$asTask,
[Switch]$fallbackMode,
[Switch]$hideConsole
)
$version = "3.19"
####MANDATORY MANUAL CONFIGURATION
$authMethod = "native" #Uses IE automation (old method) when set to ie, uses new native method when set to 'native'
$O365CustomerName = "ogd" #This should be the name of your tenant (example, ogd as in ogd.onmicrosoft.com)
$debugmode = $False #Set to $True for debugging purposes. You'll be able to see the script navigate in Internet Explorer if you're using IE auth mode
$userLookupMode = 3 #1 = Active Directory UPN, 2 = Active Directory Email, 3 = Azure AD Joined Windows 10, 4 = query user for his/her login, 5 = lookup by registry key, 6 = display full form (ask for both username and login if no cached versions can be found), 7 = whoami /upn
$AzureAADConnectSSO = $False #NOT NEEDED FOR NATIVE AUTH, if set to True, will automatically remove AzureADSSO registry key before mapping, and then readd them after mapping. Otherwise, mapping fails because AzureADSSO creates a non-persistent cookie
$adfsWaitTime = 10 #Amount of seconds to allow for SSO (ADFS or AzureAD or any other configured SSO provider) redirects, if set too low, the script may fail while just waiting for a slow redirect, this is because the IE object will report being ready even though it is not. Set to 0 if using passwords to sign in.
$adfsMode = 1 #1 = use whatever came out of userLookupMode, 2 = use only the part before the @ in the upn, 3 = use user certificate (local user store) and match Subject to Username
$showConsoleOutput = $True #Set this to $False to hide console output
$showElevatedConsole = $True
<#if you wish to add more, add more lines to the below (copy the first above itself). Parameter explanation:
displayName = the label of the driveletter, or name of the shortcut we'll create to the target site/library
targetLocationType = driveletter OR networklocation, if you use driveletter, enter a driveletter in targetLocationPath. If you use networklocation, enter a path to a folder where you want the shortcut to be created
targetLocationPath = enter a driveletter if mapping to a driveletter, enter a folder path if just creating shortcuts, type 'autodetect' if you want the script to automatically find a free driveletter
sourceLocationPath = autodetect or the full URL to the sharepoint / groups site. Autodetect automatically makes this a mapping to Onedrive For Business
mapOnlyForSpecificGroup = this only works for DOMAIN JOINED devices that can reach a domain controller and means that the mapping will only be made if the user is a member of the group you specify here
#>
#DEFAULT SETTINGS: (onedrive only, to the X: drive)
$desiredMappings = @(
@{"displayName"="Onedrive for Business";"targetLocationType"="driveletter";"targetLocationPath"="X:";"sourceLocationPath"="autodetect";"mapOnlyForSpecificGroup"=""}
)
#EXAMPLE SETTINGS (Onedrive for Business, two Sharepoint sites, one mapped to a driveletter, one to a shortcut, the last only when a member of the Active Directory group SEC-SHAREPOINTA)
#$desiredMappings = @(
# @{"displayName"="Onedrive for Business";"targetLocationType"="driveletter";"targetLocationPath"="X:";"sourceLocationPath"="autodetect";"mapOnlyForSpecificGroup"=""},
# @{"displayName"="Sharepoint Site A";"targetLocationType"="networklocation";"targetLocationPath"="$env:APPDATA\Microsoft\Windows\Network Shortcuts";"sourceLocationPath"="https://ogd.sharepoint.com/sites/OGDWerkplek/Gedeelde%20%20documenten/Forms/AllItems.aspx";"mapOnlyForSpecificGroup"="SEC-SHAREPOINTA"},
# @{"displayName"="Sharepoint Site A";"targetLocationType"="driveletter";"targetLocationPath"="Z:";"sourceLocationPath"="https://ogd.sharepoint.com/sites/OGDWerkplek/Gedeelde%20%20documenten/Forms/AllItems.aspx";"mapOnlyForSpecificGroup"=""} #note that the last entry does NOT end with a comma!
#)
$redirectFolders = $false #Set to TRUE and configure below hashtable to redirect folders
$listOfFoldersToRedirect = @(#One line for each folder you want to redirect, only works if redirectFolders=$True. For knownFolderInternalName choose from Get-KnownFolderPath function, for knownFolderInternalIdentifier choose from Set-KnownFolderPath function
@{"knownFolderInternalName" = "Desktop";"knownFolderInternalIdentifier"="Desktop";"desiredTargetPath"="X:\Desktop";"copyExistingFiles"="true"},
@{"knownFolderInternalName" = "MyDocuments";"knownFolderInternalIdentifier"="Documents";"desiredTargetPath"="X:\My Documents";"copyExistingFiles"="true"},
@{"knownFolderInternalName" = "MyPictures";"knownFolderInternalIdentifier"="Pictures";"desiredTargetPath"="X:\My Pictures";"copyExistingFiles"="false"} #note that the last entry does NOT end with a comma
)
###OPTIONAL CONFIGURATION
$autoMapFavoriteSites = $False #Set to $True to automatically map any sites/teams/groups the user has favorited (https://yourtenantname.sharepoint.com/_layouts/15/sharepoint.aspx?v=following)
$autoMapFavoritesMode = "Converged" #Normal = map each detected site to a free driveletter, Onedrive = map to Onedrive subfolder (Links), Converged = single dummy mapping with all links in it
$autoMapFavoritesDrive = "S" #Driveletter when using automapFavoritesMode = "Converged"
$autoMapFavoritesLabel = "Teams" #Label of favorites container, ie; folder name if automapFavoritesMode = "Onedrive", drive label if automapFavoritesMode = "Converged"
$autoMapFavoritesDrvLetterList = "DEFGHIJKLMNOPQRSTUVWXYZ" #List of driveletters that shall be used (you can ommit some of yours "reserved" letters)
$favoriteSitesDLName = "Gedeelde Documenten" #Normally autodetected, default document library name in Teams/Groups/Sites to map in conjunction with $autoMapFavoriteSites, note the double spaces! Use Shared Documents for english language tenants
$restartExplorer = $False #Leave at False unless you're redirecting folders and they don't get redirected properly
$autoResetIE = $False #always clear all Internet Explorer cookies before running (prevents certain occasional issues with IE)
$authenticateToProxy = $False #use system proxy settings and authenticate automatically
$libraryName = "Documents" #leave this default, unless you wish to map a non-default onedrive library you've created
$autoKillIE = $True #Kill any running Internet Explorer processes prior to running the script to prevent security errors when mapping
$abortIfNoAdfs = $False #If set to True, will stop the script if no ADFS server has been detected during login
$adfsSmartLink = $Null #If set, the ADFS smartlink will be used to log in to Office 365. For more info, read the FAQ at http://http://www.lieben.nu/liebensraum/onedrivemapper/onedrivemapper-faq/
$displayErrors = $True #show errors to user in visual popups
$persistentMapping = $True #If set to $False, the mapping will go away when the user logs off
$buttonText = "Login" #Text of the button on the password input popup box
$loginformTitleText = "OneDriveMapper" #Used as the window title for input popup boxes (userLookupMode is set to 4) and login forms (userLookupMode is set to 6)
$loginformIntroText = "Welcome to COMPANY NAME`r`nPlease enter your login and password" #used as introduction text when you set userLookupMode to 6
$loginFieldText = "Please enter your login in the form of xxx@xxx.com" #used as label above the login text field when you set userLookupMode to 6
$passwordFieldText = "Please enter your password" #used as label above the password text field when you set userLookupMode to 6
$adfsLoginInput = "userNameInput" #change to user-signin if using Okta, username2Txt if using RMUnify, user_email if using onelogin
$adfsPwdInput = "passwordInput" #change to pass-signin if using Okta, passwordTxt if using RMUnify, user_password if using onelogin
$adfsButton = "submitButton" #change to singin-button if using Okta, Submit if using RMUnify, user_submit if using onelogin
$urlOpenAfter = "" #This URL will be opened by the script after running if you configure it
$showProgressBar = $True #will show a progress bar to the user
$progressBarColor = "#CC99FF"
$progressBarText = "OnedriveMapper v$version is connecting your drives..."
$versionCheck = $False #will check if running the latest version, if not, this will be logged to the logfile, no personal data is transmitted.
$autoDetectProxy = $False #if set to $False, unchecks the 'Automatically detect proxy settings' setting in IE; this greatly enhanced WebDav performance, set to true to not modify this IE setting (leave as is)
$forceUserName = '' #if anything is entered here, userLookupMode is ignored
$forcePassword = '' #if anything is entered here, the user won't be prompted for a password. This function is not recommended, as your password could be stolen from this file
$autoProtectedMode = $True #Automatically temporarily disable IE Protected Mode if it is enabled. ProtectedMode has to be disabled for the script to function
$addShellLink = $False #Adds a link to Onedrive to the Shell under Favorites (Windows 7, 8 / 2008R2 and 2012R2 only) If you use a remote path, google EnableShellShortcutIconRemotePath
$logfile = ($env:APPDATA + "\OneDriveMapper_$version.log") #Logfile to log to
$pwdCache = ($env:APPDATA + "\OneDriveMapper.tmp") #file to store encrypted password into, change to $Null to disable
$loginCache = ($env:APPDATA + "\OneDriveMapper.tmp2") #file to store encrypted login into, change to $Null to disable
$allowFallbackMode = $True #if set to True, and the selected authentication method fails, onedrivemapper will try again using the other authentication method
if($hideConsole){
$showConsoleOutput = $False
$showElevatedConsole = $False
}
if($showConsoleOutput -eq $False){
$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
try{
add-type -name win -member $t -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)
}catch{$Null}
}
########
#Required resources and some customizations you'll probably not use
########
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
$mapresult = $False
$protectedModeValues = @{}
$privateSuffix = "-my"
$script:errorsForUser = ""
$userLoginRegistryKey = "HKCU:\System\CurrentControlSet\Control\CustomUID"
$onedriveIconPath = "C:\GitRepos\OnedriveMapper\onedrive.ico" #if this file exists, and you've set addShellLink to True, it will be used as icon for the shortcut
$teamsIconPath = "C:\GitRepos\OnedriveMapper\teams.ico" #if this file exists, and you've set addShellLink to True, it will be used as icon for the shortcut
$sharepointIconPath = "C:\GitRepos\OnedriveMapper\sharepoint.ico" #if this file exists, and you've set addShellLink to True, it will be used as icon for the shortcut
$i_MaxLocalLogSize = 2 #max local log size in MB
$certificateMatchMethod = 1 #used with adfsMode = 3, when set to 1 it'll match based on the local username, if set to 2 it'll use the following variable to match to a template name
$certificateTemplateName = "Office365_Client_Authentication"
$maxWaitSecondsForSpO = 5 #Maximum seconds the script waits for Sharepoint Online to load before mapping
if($adfsSmartLink){
$o365loginURL = $adfsSmartLink
}else{
$o365loginURL = "https://login.microsoftonline.com/login.srf?msafed=0"
}
$O365CustomerName = $O365CustomerName.ToLower()
#for people that don't RTFM, fix wrongly entered customer names:
$O365CustomerName = $O365CustomerName -Replace ".onmicrosoft.com",""
$forceUserName = $forceUserName.ToLower()
$finalURLs = @()
$finalURLs += "https://portal.office.com"
$finalURLs += "https://outlook.office365.com"
$finalURLs += "https://outlook.office.com"
$finalURLs += "https://$($O365CustomerName)-my.sharepoint.com"
$finalURLs += "https://$($O365CustomerName).sharepoint.com"
$finalURLs += "https://www.office.com"
function log{
param (
[Parameter(Mandatory=$true)][String]$text,
[Switch]$fout,
[Switch]$warning
)
if($fout){
$text = "ERROR | $text"
}
elseif($warning){
$text = "WARNING | $text"
}
else{
$text = "INFO | $text"
}
try{
Add-Content $logfile "$(Get-Date) | $text"
}catch{$Null}
if($showConsoleOutput){
if($fout){
Write-Host $text -ForegroundColor Red
}elseif($warning){
Write-Host $text -ForegroundColor Yellow
}else{
Write-Host $text -ForegroundColor Green
}
}
}
function ResetLog{
<#
-------------------------------------------------------------------------------------------
Manage the local log file size
Always keep a backup
#credits to Steven Heimbecker
-------------------------------------------------------------------------------------------
#>
#Restart the local log file if it exists and is bigger than $i_MaxLocalLogSize MB as defined below
[int]$i_LocalLogSize
if ((Test-Path $logfile) -eq $True){
#The log file exists
try{
$i_LocalLogSize=(Get-Item $logfile).Length
if($i_LocalLogSize / 1Mb -gt $i_MaxLocalLogSize){
#The log file is greater than the defined maximum. Let's back it up / rename it
#Blank line in the old log
log -text ""
log -text "******** End of log - maximum size ********"
#Save the current log as a .old. If one already exists, delete it.
if ((Test-Path ($logfile + ".old")) -eq $True){
#Already a backup file, delete it
Remove-Item ($logfile + ".old") -Force -Confirm:$False
}
#Now lets rename
Rename-Item -path $logfile -NewName ($logfile + ".old") -Force -Confirm:$False
#Start a new log
log -text "******** Log file reset after reaching maximum size ********`n"
}
}catch{
log -text "there was an issue resetting the logfile! $($Error[0])" -fout
}
}
}
$scriptPath = $MyInvocation.MyCommand.Definition
ResetLog
log -text "-----$(Get-Date) OneDriveMapper v$version - $($env:USERNAME) on $($env:COMPUTERNAME) starting-----"
###THIS ONLY HAS TO BE CONFIGURED IF YOU WANT TO MAP USER SECURITY GROUPS TO SHAREPOINT SITES
if($desiredMappings.mapOnlyForSpecificGroup | Where-Object{$_.Length -gt 0}){
try{
$groups = ([ADSISEARCHER]"(member:1.2.840.113556.1.4.1941:=$(([ADSISEARCHER]"samaccountname=$($env:USERNAME)").FindOne().Properties.distinguishedname))").FindAll().Properties.distinguishedname -replace '^CN=([^,]+).+$','$1'
log -text "cached user group membership because you have configured mappings where the mapOnlyForSpecificGroup option was configured"
}catch{
log -text "failed to cache user group membership, ignoring these mappings because of: $($Error[0])" -fout
$desiredMappings = $desiredMappings | Where-Object{$_.mapOnlyForSpecificGroup.Length -eq 0}
}
}
#Find a driveletter for any drivemappings that have autotect as targetlocationpath
$drvlist=(Get-PSDrive -PSProvider filesystem).Name
for($i=0;$i -lt $desiredMappings.Count;$i++){
if($desiredMappings[$i].targetLocationPath -eq "autodetect"){
Foreach ($drvletter in $autoMapFavoritesDrvLetterList.ToCharArray()) {
If ($drvlist -notcontains $drvletter) {
$drvlist += $drvletter
$desiredMappings[$i].targetLocationPath = "$($drvletter):"
log -text "automatically selected drive $drvletter for Onedrive mapping"
break
}
}
}
}
function Add-NetworkLocation
<#
Author: Tom White, 2015.
Description:
Creates a network location shortcut using the specified path, name and target.
Replicates the behaviour of the 'Add Network Location' wizard, creating a special folder as opposed to a simple shortcut.
Returns $true on success and $false on failure.
Use -Verbose for extended output.
Example:
Add-NetworkLocation -networkLocationPath "$env:APPDATA\Microsoft\Windows\Network Shortcuts" -networkLocationName "Network Location" -networkLocationTarget "\\server\share" -Verbose
#>
{
[CmdLetBinding()]
param
(
[string]$networkLocationPath="$env:APPDATA\Microsoft\Windows\Network Shortcuts",
[Parameter(Mandatory=$true)][string]$networkLocationName ,
[Parameter(Mandatory=$true)][string]$networkLocationTarget,
[String]$iconPath
)
Begin
{
Write-Verbose -Message "Network location path: `"$networkLocationPath`"."
Write-Verbose -Message "Network location name: `"$networkLocationName`"."
Write-Verbose -Message "Network location target: `"$networkLocationTarget`"."
Set-Variable -Name desktopIniContent -Option ReadOnly -value ([string]"[.ShellClassInfo]`r`nCLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}`r`nFlags=2")
}
Process
{
Write-Verbose -Message "Checking that `"$networkLocationPath`" is a valid directory..."
if(Test-Path -Path $networkLocationPath -PathType Container)
{
try
{
Write-Verbose -Message "Creating `"$networkLocationPath\$networkLocationName`"."
[void]$(New-Item -Path "$networkLocationPath\$networkLocationName" -ItemType Directory -ErrorAction Stop)
Write-Verbose -Message "Setting system attribute on `"$networkLocationPath\$networkLocationName`"."
Set-ItemProperty -Path "$networkLocationPath\$networkLocationName" -Name Attributes -Value ([System.IO.FileAttributes]::System) -ErrorAction Stop
}
catch [Exception]
{
Write-Error -Message "Cannot create or set attributes on `"$networkLocationPath\$networkLocationName`". Check your access and/or permissions."
return $false
}
}
else
{
Write-Error -Message "`"$networkLocationPath`" is not a valid directory path."
return $false
}
try
{
Write-Verbose -Message "Creating `"$networkLocationPath\$networkLocationName\desktop.ini`"."
[object]$desktopIni = New-Item -Path "$networkLocationPath\$networkLocationName\desktop.ini" -ItemType File
Write-Verbose -Message "Writing to `"$($desktopIni.FullName)`"."
Add-Content -Path $desktopIni.FullName -Value $desktopIniContent
}
catch [Exception]
{
Write-Error -Message "Error while creating or writing to `"$networkLocationPath\$networkLocationName\desktop.ini`". Check your access and/or permissions."
return $false
}
try
{
$WshShell = New-Object -ComObject WScript.Shell
Write-Verbose -Message "Creating shortcut to `"$networkLocationTarget`" at `"$networkLocationPath\$networkLocationName\target.lnk`"."
$Shortcut = $WshShell.CreateShortcut("$networkLocationPath\$networkLocationName\target.lnk")
$Shortcut.TargetPath = $networkLocationTarget
if([System.IO.File]::Exists($iconPath)){
$Shortcut.IconLocation = "$($iconPath), 0"
}
$Shortcut.Description = "Created $(Get-Date -Format s) by $($MyInvocation.MyCommand)."
$Shortcut.Save()
}
catch [Exception]
{
Write-Error -Message "Error while creating shortcut @ `"$networkLocationPath\$networkLocationName\target.lnk`". Check your access and permissions."
return $false
}
return $true
}
}
function handleSpoReAuth{
Param(
$res
)
try{
if((returnEnclosedFormValue -res $res -searchString "<form method=`"POST`" name=`"hiddenform`" action=`"" -decode) -ne -1){
$nextURL = returnEnclosedFormValue -res $res -searchString "<form method=`"POST`" name=`"hiddenform`" action=`"" -decode
$code = returnEnclosedFormValue -res $res -searchString "<input type=`"hidden`" name=`"code`" value=`""
$id_token = returnEnclosedFormValue -res $res -searchString "<input type=`"hidden`" name=`"id_token`" value=`""
$session_state = returnEnclosedFormValue -res $res -searchString "<input type=`"hidden`" name=`"session_state`" value=`""
$body = "code=$code&id_token=$id_token&session_state=$session_state"
}
if($nextURL.Length -gt 10){
log -text "Retrieving Sharepoint cookie step 2 at $nextURL"
$res = JosL-WebRequest -url $nextURL -Method POST -body $body
}
return $res
}catch{
log -text "Problem reported during sharepoint reauth: $($Error[0])" -fout
}
}
function handleMFArequest{
Param(
$res,
$clientId
)
$mfaArray = returnEnclosedFormValue -res $res -searchString "`"arrUserProofs`":" -endString "]" -includeEndString
if($mfaArray -ne -1){
$mfaArray = $mfaArray | ConvertFrom-Json
$mfaMethod = @($mfaArray | Where-Object {$_.isDefault})[0].authMethodId
}else{
$mfaMethod = returnEnclosedFormValue -res $res -searchString "`"authMethodId`":`""
}
if($mfaMethod -eq -1){
Throw "No MFA method detected"
}
if($mfaMethod -ne "PhoneAppNotification" -and $mfaMethod -ne "TwoWayVoiceMobile"){
Throw "Unsupported MFA method detected: $mfaMethod"
}
$canary = returnEnclosedFormValue -res $res -searchString "`",`"canary`":`""
$apiCanary = returnEnclosedFormValue -res $res -searchString "ConvergedTFA`",`"apiCanary`":`""
$ctx = returnEnclosedFormValue -res $res -searchString "sFTName`":`"flowToken`",`"sCtx`":`""
$sFT = returnEnclosedFormValue -res $res -searchString "`",`"sFT`":`""
$body = @{"AuthMethodId"=$mfaMethod;"Method"="BeginAuth";"ctx"=$ctx;"flowToken"=$sFT}
$customHeaders = @{"canary" = $apiCanary;"hpgrequestid" = $res.Headers["x-ms-request-id"];"client-request-id"=$clientId;"hpgid"=1114;"hpgact"=2000}
try{
$res = JosL-WebRequest -url "https://login.microsoftonline.com/common/SAS/BeginAuth" -Method POST -customHeaders $customHeaders -body ($body | ConvertTo-Json) -referer $res.rawResponse.ResponseUri.AbsoluteUri -contentType "application/json"
$result = $res.Content | convertfrom-json
$sFT = $result.FlowToken
$ctx = $result.Ctx
if($result.Success -eq $False){
Throw
}
$sessionId = $result.SessionId
}catch{
Throw "SAS BeginAuth failure, MFA initiation not accepted $($result.Message)"
}
$body = @{"Method"="EndAuth";"SessionId"=$sessionId;"FlowToken"=$sFT;"Ctx"=$ctx;"AuthMethodId"=$mfaMethod;"PollCount"=1}
$waitedForMFA = 0
while($true){
if($waitedForMFA -ge 60){
Throw "Waited longer than 60 seconds for MFA request to be validated, aborting"
}
try{
$res = JosL-WebRequest -url "https://login.microsoftonline.com/common/SAS/EndAuth" -Method POST -customHeaders $customHeaders -body ($body | ConvertTo-Json) -referer $res.rawResponse.ResponseUri.AbsoluteUri -contentType "application/json"
$result = $res.Content | convertfrom-json
if($result.Success){
break
}
}catch{
Throw "SAS EndAuth failure, MFA initiation not accepted"
}
Start-Sleep -s 5
$waitedForMFA+=5
}
try{
$ctx = [System.Web.HttpUtility]::UrlEncode($ctx)
$canary = [System.Web.HttpUtility]::UrlEncode($canary)
$sFT = [System.Web.HttpUtility]::UrlEncode($result.FlowToken)
if($mfaMethod -eq "PhoneAppNotification"){
$mfaAuthMethod = "PhoneAppOTP"
$type=22
}
if($mfaMethod -eq "TwoWayVoiceMobile"){
$mfaAuthMethod = "TwoWayVoiceMobile"
$type=1
}
$body = "type=$type&request=$ctx&mfaAuthMethod=$mfaAuthMethod&canary=$canary&login=$userUPN&flowToken=$sFT&hpgrequestid=$($customHeaders["hpgrequestid"])&sacxt=&i2=&i17=&i18=&i19=7406"
$res = JosL-WebRequest -url "https://login.microsoftonline.com/common/SAS/ProcessAuth" -Method POST -body $body -referer $res.rawResponse.ResponseUri.AbsoluteUri
return $res
}catch{
Throw "SAS ProcessAuth failure"
}
}
function createFavoritesShortcutToO4B{
Param(
$targetLocation
)
$regPath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
try{
$linksPath = (Get-ItemProperty -Path $regPath -Name "{BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968}")."{BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968}"
log -text "Path to links folder determined: $linksPath"
}catch{
Throw "Failed to determine path to Links folder: $($Error[0])"
}
$shortcutName = "Onedrive - $O365CustomerName.lnk"
$shortcutPath = Join-Path $linksPath -ChildPath $shortcutName
if([System.IO.Directory]::Exists($linksPath)){
if([System.IO.File]::Exists($shortcutPath)){
log -text "Shortcut already exists"
return
}else{
try{
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($shortcutPath)
$Shortcut.TargetPath = $targetLocation
if([System.IO.File]::Exists($onedriveIconPath)){
$Shortcut.IconLocation = "$($onedriveIconPath), 0"
}
$Shortcut.Description ="Onedrive for Business"
$Shortcut.Save()
}catch{
Throw
}
}
}else{
Throw "Links folder does not exist"
}
}
Function Set-KnownFolderPath {
Param (
[Parameter(Mandatory = $true)][ValidateSet('AddNewPrograms', 'AdminTools', 'AppUpdates', 'CDBurning', 'ChangeRemovePrograms', 'CommonAdminTools', 'CommonOEMLinks', 'CommonPrograms', `
'CommonStartMenu', 'CommonStartup', 'CommonTemplates', 'ComputerFolder', 'ConflictFolder', 'ConnectionsFolder', 'Contacts', 'ControlPanelFolder', 'Cookies', `
'Desktop', 'Documents', 'Downloads', 'Favorites', 'Fonts', 'Games', 'GameTasks', 'History', 'InternetCache', 'InternetFolder', 'Links', 'LocalAppData', `
'LocalAppDataLow', 'LocalizedResourcesDir', 'Music', 'NetHood', 'NetworkFolder', 'OriginalImages', 'PhotoAlbums', 'Pictures', 'Playlists', 'PrintersFolder', `
'PrintHood', 'Profile', 'ProgramData', 'ProgramFiles', 'ProgramFilesX64', 'ProgramFilesX86', 'ProgramFilesCommon', 'ProgramFilesCommonX64', 'ProgramFilesCommonX86', `
'Programs', 'Public', 'PublicDesktop', 'PublicDocuments', 'PublicDownloads', 'PublicGameTasks', 'PublicMusic', 'PublicPictures', 'PublicVideos', 'QuickLaunch', `
'Recent', 'RecycleBinFolder', 'ResourceDir', 'RoamingAppData', 'SampleMusic', 'SamplePictures', 'SamplePlaylists', 'SampleVideos', 'SavedGames', 'SavedSearches', `
'SEARCH_CSC', 'SEARCH_MAPI', 'SearchHome', 'SendTo', 'SidebarDefaultParts', 'SidebarParts', 'StartMenu', 'Startup', 'SyncManagerFolder', 'SyncResultsFolder', `
'SyncSetupFolder', 'System', 'SystemX86', 'Templates', 'TreeProperties', 'UserProfiles', 'UsersFiles', 'Videos', 'Windows')]
[string]$KnownFolder,
[Parameter(Mandatory = $true)][string]$Path
)
# Define known folder GUIDs
$KnownFolders = @{
'AddNewPrograms' = 'de61d971-5ebc-4f02-a3a9-6c82895e5c04';'AdminTools' = '724EF170-A42D-4FEF-9F26-B60E846FBA4F';'AppUpdates' = 'a305ce99-f527-492b-8b1a-7e76fa98d6e4';
'CDBurning' = '9E52AB10-F80D-49DF-ACB8-4330F5687855';'ChangeRemovePrograms' = 'df7266ac-9274-4867-8d55-3bd661de872d';'CommonAdminTools' = 'D0384E7D-BAC3-4797-8F14-CBA229B392B5';
'CommonOEMLinks' = 'C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D';'CommonPrograms' = '0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8';'CommonStartMenu' = 'A4115719-D62E-491D-AA7C-E74B8BE3B067';
'CommonStartup' = '82A5EA35-D9CD-47C5-9629-E15D2F714E6E';'CommonTemplates' = 'B94237E7-57AC-4347-9151-B08C6C32D1F7';'ComputerFolder' = '0AC0837C-BBF8-452A-850D-79D08E667CA7';
'ConflictFolder' = '4bfefb45-347d-4006-a5be-ac0cb0567192';'ConnectionsFolder' = '6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD';'Contacts' = '56784854-C6CB-462b-8169-88E350ACB882';
'ControlPanelFolder' = '82A74AEB-AEB4-465C-A014-D097EE346D63';'Cookies' = '2B0F765D-C0E9-4171-908E-08A611B84FF6';'Desktop' = @('B4BFCC3A-DB2C-424C-B029-7FE99A87C641');
'Documents' = @('FDD39AD0-238F-46AF-ADB4-6C85480369C7','f42ee2d3-909f-4907-8871-4c22fc0bf756');'Downloads' = @('374DE290-123F-4565-9164-39C4925E467B','7d83ee9b-2244-4e70-b1f5-5393042af1e4');
'Favorites' = '1777F761-68AD-4D8A-87BD-30B759FA33DD';'Fonts' = 'FD228CB7-AE11-4AE3-864C-16F3910AB8FE';'Games' = 'CAC52C1A-B53D-4edc-92D7-6B2E8AC19434';
'GameTasks' = '054FAE61-4DD8-4787-80B6-090220C4B700';'History' = 'D9DC8A3B-B784-432E-A781-5A1130A75963';'InternetCache' = '352481E8-33BE-4251-BA85-6007CAEDCF9D';
'InternetFolder' = '4D9F7874-4E0C-4904-967B-40B0D20C3E4B';'Links' = 'bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968';'LocalAppData' = 'F1B32785-6FBA-4FCF-9D55-7B8E7F157091';
'LocalAppDataLow' = 'A520A1A4-1780-4FF6-BD18-167343C5AF16';'LocalizedResourcesDir' = '2A00375E-224C-49DE-B8D1-440DF7EF3DDC';'Music' = @('4BD8D571-6D19-48D3-BE97-422220080E43','a0c69a99-21c8-4671-8703-7934162fcf1d');
'NetHood' = 'C5ABBF53-E17F-4121-8900-86626FC2C973';'NetworkFolder' = 'D20BEEC4-5CA8-4905-AE3B-BF251EA09B53';'OriginalImages' = '2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39';
'PhotoAlbums' = '69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C';'Pictures' = @('33E28130-4E1E-4676-835A-98395C3BC3BB','0ddd015d-b06c-45d5-8c4c-f59713854639');
'Playlists' = 'DE92C1C7-837F-4F69-A3BB-86E631204A23';'PrintersFolder' = '76FC4E2D-D6AD-4519-A663-37BD56068185';'PrintHood' = '9274BD8D-CFD1-41C3-B35E-B13F55A758F4';
'Profile' = '5E6C858F-0E22-4760-9AFE-EA3317B67173';'ProgramData' = '62AB5D82-FDC1-4DC3-A9DD-070D1D495D97';'ProgramFiles' = '905e63b6-c1bf-494e-b29c-65b732d3d21a';
'ProgramFilesX64' = '6D809377-6AF0-444b-8957-A3773F02200E';'ProgramFilesX86' = '7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E';'ProgramFilesCommon' = 'F7F1ED05-9F6D-47A2-AAAE-29D317C6F066';
'ProgramFilesCommonX64' = '6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D';'ProgramFilesCommonX86' = 'DE974D24-D9C6-4D3E-BF91-F4455120B917';'Programs' = 'A77F5D77-2E2B-44C3-A6A2-ABA601054A51';
'Public' = 'DFDF76A2-C82A-4D63-906A-5644AC457385';'PublicDesktop' = 'C4AA340D-F20F-4863-AFEF-F87EF2E6BA25';'PublicDocuments' = 'ED4824AF-DCE4-45A8-81E2-FC7965083634';
'PublicDownloads' = '3D644C9B-1FB8-4f30-9B45-F670235F79C0';'PublicGameTasks' = 'DEBF2536-E1A8-4c59-B6A2-414586476AEA';'PublicMusic' = '3214FAB5-9757-4298-BB61-92A9DEAA44FF';
'PublicPictures' = 'B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5';'PublicVideos' = '2400183A-6185-49FB-A2D8-4A392A602BA3';'QuickLaunch' = '52a4f021-7b75-48a9-9f6b-4b87a210bc8f';
'Recent' = 'AE50C081-EBD2-438A-8655-8A092E34987A';'RecycleBinFolder' = 'B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC';'ResourceDir' = '8AD10C31-2ADB-4296-A8F7-E4701232C972';
'RoamingAppData' = '3EB685DB-65F9-4CF6-A03A-E3EF65729F3D';'SampleMusic' = 'B250C668-F57D-4EE1-A63C-290EE7D1AA1F';'SamplePictures' = 'C4900540-2379-4C75-844B-64E6FAF8716B';
'SamplePlaylists' = '15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5';'SampleVideos' = '859EAD94-2E85-48AD-A71A-0969CB56A6CD';'SavedGames' = '4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4';
'SavedSearches' = '7d1d3a04-debb-4115-95cf-2f29da2920da';'SEARCH_CSC' = 'ee32e446-31ca-4aba-814f-a5ebd2fd6d5e';'SEARCH_MAPI' = '98ec0e18-2098-4d44-8644-66979315a281';
'SearchHome' = '190337d1-b8ca-4121-a639-6d472d16972a';'SendTo' = '8983036C-27C0-404B-8F08-102D10DCFD74';'SidebarDefaultParts' = '7B396E54-9EC5-4300-BE0A-2482EBAE1A26';
'SidebarParts' = 'A75D362E-50FC-4fb7-AC2C-A8BEAA314493';'StartMenu' = '625B53C3-AB48-4EC1-BA1F-A1EF4146FC19';'Startup' = 'B97D20BB-F46A-4C97-BA10-5E3608430854';
'SyncManagerFolder' = '43668BF8-C14E-49B2-97C9-747784D784B7';'SyncResultsFolder' = '289a9a43-be44-4057-a41b-587a76d7e7f9';'SyncSetupFolder' = '0F214138-B1D3-4a90-BBA9-27CBC0C5389A';
'System' = '1AC14E77-02E7-4E5D-B744-2EB1AE5198B7';'SystemX86' = 'D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27';'Templates' = 'A63293E8-664E-48DB-A079-DF759E0509F7';
'TreeProperties' = '5b3749ad-b49f-49c1-83eb-15370fbd4882';'UserProfiles' = '0762D272-C50A-4BB0-A382-697DCD729B80';'UsersFiles' = 'f3ce0f7c-4901-4acc-8648-d5d44b04ef8f';
'Videos' = @('18989B1D-99B5-455B-841C-AB7C74E4DDFC','35286a68-3c57-41a1-bbb1-0eae73d76c95');'Windows' = 'F38BF404-1D43-42F2-9305-67DE0B28FC23';
}
$Type = ([System.Management.Automation.PSTypeName]'KnownFolders').Type
If (-not $Type) {
$Signature = @'
[DllImport("shell32.dll")]
public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
'@
$Type = Add-Type -MemberDefinition $Signature -Name 'KnownFolders' -Namespace 'SHSetKnownFolderPath' -PassThru
}
If (!(Test-Path $Path -PathType Container)) {
New-Item -Path $Path -Type Directory -Force -Verbose
}
If (Test-Path $Path -PathType Container) {
ForEach ($guid in $KnownFolders[$KnownFolder]) {
$result = $Type::SHSetKnownFolderPath([ref]$guid, 0, 0, $Path)
If ($result -ne 0) {
$errormsg = "Error redirecting $($KnownFolder). Return code $($result) = $((New-Object System.ComponentModel.Win32Exception($result)).message)"
Throw $errormsg
}
}
} Else {
Throw New-Object System.IO.DirectoryNotFoundException "Could not find part of the path $Path."
}
Attrib +r $Path
Return $Path
}
Function Get-KnownFolderPath {
Param (
[Parameter(Mandatory = $true)]
[ValidateSet('AdminTools','ApplicationData','CDBurning','CommonAdminTools','CommonApplicationData','CommonDesktopDirectory','CommonDocuments','CommonMusic',`
'CommonOemLinks','CommonPictures','CommonProgramFiles','CommonProgramFilesX86','CommonPrograms','CommonStartMenu','CommonStartup','CommonTemplates',`
'CommonVideos','Cookies','Downloads','Desktop','DesktopDirectory','Favorites','Fonts','History','InternetCache','LocalApplicationData','LocalizedResources','MyComputer',`
'MyDocuments','MyMusic','MyPictures','MyVideos','NetworkShortcuts','Personal','PrinterShortcuts','ProgramFiles','ProgramFilesX86','Programs','Recent',`
'Resources','SendTo','StartMenu','Startup','System','SystemX86','Templates','UserProfile','Windows')]
[string]$KnownFolder
)
if($KnownFolder -eq "Downloads"){
Return $Null
}else{
Return [Environment]::GetFolderPath($KnownFolder)
}
}
Function Redirect-Folder {
Param (
$GetFolder,
$SetFolder,
$Target,
$copyExistingFiles
)
$Folder = Get-KnownFolderPath -KnownFolder $GetFolder
If ($Folder -ne $Target) {
Set-KnownFolderPath -KnownFolder $SetFolder -Path $Target
if($copyExistingFiles -and $Folder){
Get-ChildItem -Path $Folder -ErrorAction Continue | Copy-Item -Destination $Target -Recurse -Container -Force -Confirm:$False -ErrorAction Continue
}
Attrib +h $Folder
}
}
function getElementById{
Param(
[Parameter(Mandatory=$true)]$id
)
$localObject = $Null
try{
$localObject = $script:ie.document.getElementById($id)
if($localObject.tagName -eq $Null){Throw "The element $id was not found (1) or had no tagName"}
return $localObject
}catch{$localObject = $Null}
try{
$localObject = $script:ie.document.IHTMLDocument3_getElementById($id)
if($localObject.tagName -eq $Null){Throw "The element $id was not found (2) or had no tagName"}
return $localObject
}catch{
Throw
}
}
function ConvertTo-Json20([object] $item){
add-type -assembly system.web.extensions
$ps_js=new-object system.web.script.serialization.javascriptSerializer
return $ps_js.Serialize($item)
}
function ConvertFrom-Json20([object] $item){
add-type -assembly system.web.extensions
$ps_js=new-object system.web.script.serialization.javascriptSerializer
return ,$ps_js.DeserializeObject($item)
}
function JosL-WebRequest{
Param(
$url,
$method="GET",
$body,
$trySSO=1,
$customHeaders,
$accept = "application/json",
$referer = $Null,
$contentType = "application/x-www-form-urlencoded"
)
$maxAttempts = 3
$attempts=0
while($true){
$attempts++
try{
$retVal = @{}
$request = [System.Net.WebRequest]::Create($url)
$request.KeepAlive = $True
if($adfsMode -eq 3){
#Find the FIRST certificate that matches the user's username and append it to all requests
if($certificateMatchMethod -eq 1){
$userCert = (Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object {$_.Subject -like "*$($Env:USERNAME)*"})[0]
}
#Find the FIRST certificate that matches the template name specified in the script configuration
if($certificateMatchMethod -eq 2){
$attempts = 0
while($true){
try{
$userCert = (Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object {($_.extensions.Format(1)[0].split('(')[0]).Split('=')[-1] -like "*$($certificateTemplateName)*"})[0]
if(!$userCert){Throw}
break
}catch{
$attempts++
if($attemps -le 3){
certutil -user -pulse
Start-Sleep -s 10
}else{
log -text "Failed to find a local certificate to authenticate with" -fout
abort_OM
}
}
}
}
$request.ClientCertificates.AddRange($userCert)
}
$request.TimeOut = 10000
$request.Method = $method
$request.Referer = $referer
$request.Accept = $accept
if($trySSO -eq 1){
$request.UseDefaultCredentials = $True
}
if($customHeaders){
$customHeaders.Keys | % {
$request.Headers[$_] = $customHeaders.Item($_)
}
}
if($authenticateToProxy){
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$request.proxy = $proxy
}
$request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E); OneDriveMapper/$version"
$request.ContentType = $contentType
$request.CookieContainer = $script:cookiejar
if($method -eq "POST"){
$body = [byte[]][char[]]$body
$upStream = $request.GetRequestStream()
$upStream.Write($body, 0, $body.Length)
$upStream.Flush()
$upStream.Close()
}
$response = $request.GetResponse()
$retVal.rawResponse = $response
$retVal.StatusCode = $response.StatusCode
$retVal.StatusDescription = $response.StatusDescription
$retVal.Headers = $response.Headers
$stream = $response.GetResponseStream()
$streamReader = [System.IO.StreamReader]($stream)
$retVal.Content = $streamReader.ReadToEnd()
$streamReader.Close()
$response.Close()
$response = $Null
$request = $Null
return $retVal
}catch{
if($attempts -ge $maxAttempts){Throw}else{Start-Sleep -s 2}
}
}
}
function returnEnclosedFormValue{
Param(
$res,
$searchString,
$endString = "`"",
[Switch]$includeEndString,
[Switch]$decode
)
try{
if($res.Content.Length -le 0){Throw "no request given"}
if($searchString){$start = $searchString}else{Throw "empty search string"}
$startLoc = $res.Content.IndexOf($start)+$start.Length
if($startLoc -eq $start.Length-1){
return -1
}
$searchLength = $res.Content.IndexOf($endString,$startLoc)-$startLoc
if($searchLength -le 0){
return -1
}
if($includeEndString){
$searchLength += $endString.Length
}
if($decode){
return([System.Web.HttpUtility]::UrlDecode($res.Content.Substring($startLoc,$searchLength)))
}else{
return($res.Content.Substring($startLoc,$searchLength))
}
}catch{Throw}
}
function handleAzureADConnectSSO{
Param(
[Switch]$initial
)
$failed = $False
if($script:AzureAADConnectSSO -and $authMethod -ne "native"){
if((checkRegistryKeyValue -basePath "HKLM:\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\microsoftazuread-sso.com\autologon" -entryName "https") -eq 1){
log -text "ERROR: https://autologon.microsoftazuread-sso.com found in IE Local Intranet sites, Azure AD Connect SSO is only supported if you let OnedriveMapper set the registry keys! Don't set this site through GPO" -fout
$failed = $True
}
if((checkRegistryKeyValue -basePath "HKLM:\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\nsatc.net\aadg.windows.net" -entryName "https") -eq 1){
log -text "ERROR: https://aadg.windows.net.nsatc.net found in IE Local Intranet sites, Azure AD Connect SSO is only supported if you let OnedriveMapper set the registry keys! Don't set this site through GPO" -fout
$failed = $True
}
if((checkRegistryKeyValue -basePath "HKCU:\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\microsoftazuread-sso.com\autologon" -entryName "https") -eq 1){
log -text "ERROR: https://autologon.microsoftazuread-sso.com found in IE Local Intranet sites, Azure AD Connect SSO is only supported if you let OnedriveMapper set the registry keys! Don't set this site through GPO" -fout
$failed = $True
}
if((checkRegistryKeyValue -basePath "HKCU:\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\nsatc.net\aadg.windows.net" -entryName "https") -eq 1){
log -text "ERROR: https://aadg.windows.net.nsatc.net found in IE Local Intranet sites, Azure AD Connect SSO is only supported if you let OnedriveMapper set the registry keys! Don't set this site through GPO" -fout
$failed = $True
}
if($failed -eq $False){
if($initial){
#check AzureADConnect SSO intranet sites
if((checkRegistryKeyValue -basePath "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\microsoftazuread-sso.com\autologon" -entryName "https") -eq 1){
$res = remove-item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\microsoftazuread-sso.com\autologon"
log -text "Automatically removed autologon.microsoftazuread-sso.com from intranet sites for this user"
}
if((checkRegistryKeyValue -basePath "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\nsatc.net\aadg.windows.net" -entryName "https") -eq 1){
$res = remove-item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\nsatc.net\aadg.windows.net"
log -text "Automatically removed aadg.windows.net.nsatc.net from intranet sites for this user"
}
}else{
#log results, try to automatically add trusted sites to user trusted sites if not yet added
if((addSiteToIEZoneThroughRegistry -siteUrl "aadg.windows.net.nsatc.net" -mode 1) -eq $True){log -text "Automatically added aadg.windows.net.nsatc.net to intranet sites for this user"}
if((addSiteToIEZoneThroughRegistry -siteUrl "autologon.microsoftazuread-sso.com" -mode 1) -eq $True){log -text "Automatically added autologon.microsoftazuread-sso.com to intranet sites for this user"}
}
}
}
}
function storeSecureString{
Param(
$filePath,
$string
)
try{
$stringForFile = $string | ConvertTo-SecureString -AsPlainText -Force -ErrorAction Stop | ConvertFrom-SecureString -ErrorAction Stop
Set-Content -Path $filePath -Value $stringForFile -Force -ErrorAction Stop | Out-Null
}catch{
Throw "Failed to store string: $($Error[0] | out-string)"
}
}
function loadSecureString{
Param(
$filePath
)
try{
$string = Get-Content $filePath -ErrorAction Stop | ConvertTo-SecureString -ErrorAction Stop
$string = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($string)
$string = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($string)
if($string.Length -lt 3){throw "no valid string returned from cache"}
return $string
}catch{
Throw
}
}
function versionCheck{
Param(
$currentVersion
)
$apiURL = "http://om.lieben.nu/lieben_api.php?script=OnedriveMapper&version=$currentVersion"
$apiKeyword = "latestOnedriveMapperVersion"
try{
$result = JosL-WebRequest -Url $apiURL
}catch{
Throw "Failed to connect to API url for version check: $apiURL $($Error[0])"
}
try{
$keywordIndex = $result.Content.IndexOf($apiKeyword)
if($keywordIndex -lt 1){
Throw ""
}
}catch{
Throw "Connected to API url for version check, but invalid API response"
}
$latestVersion = $result.Content.SubString($keywordIndex+$apiKeyword.Length+1,4)
if($latestVersion -ne $currentVersion){
Throw "OnedriveMapper version mismatch, current version: v$currentVersion, latest version: v$latestVersion"
}
}
function startWebDavClient{
$Source = @"
using System;
using System.Text;
using System.Security;
using System.Collections.Generic;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace JosL.WebClient{
public static class Starter{
[StructLayout(LayoutKind.Explicit, Size=16)]
public class EVENT_DESCRIPTOR{
[FieldOffset(0)]ushort Id = 1;
[FieldOffset(2)]byte Version = 0;
[FieldOffset(3)]byte Channel = 0;
[FieldOffset(4)]byte Level = 4;
[FieldOffset(5)]byte Opcode = 0;
[FieldOffset(6)]ushort Task = 0;
[FieldOffset(8)]long Keyword = 0;
}
[StructLayout(LayoutKind.Explicit, Size = 16)]
public struct EventData{
[FieldOffset(0)]
internal UInt64 DataPointer;
[FieldOffset(8)]
internal uint Size;
[FieldOffset(12)]
internal int Reserved;
}
public static void startService(){
Guid webClientTrigger = new Guid(0x22B6D684, 0xFA63, 0x4578, 0x87, 0xC9, 0xEF, 0xFC, 0xBE, 0x66, 0x43, 0xC7);
long handle = 0;
uint output = EventRegister(ref webClientTrigger, IntPtr.Zero, IntPtr.Zero, ref handle);
bool success = false;
if (output == 0){
EVENT_DESCRIPTOR desc = new EVENT_DESCRIPTOR();
unsafe{
uint writeOutput = EventWrite(handle, ref desc, 0, null);
success = writeOutput == 0;
EventUnregister(handle);
}
}
}
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern uint EventRegister(ref Guid guid, [Optional] IntPtr EnableCallback, [Optional] IntPtr CallbackContext, [In][Out] ref long RegHandle);
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern unsafe uint EventWrite(long RegHandle, ref EVENT_DESCRIPTOR EventDescriptor, uint UserDataCount, EventData* UserData);
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern uint EventUnregister(long RegHandle);
}
}
"@
try{
log -text "Attempting to automatically start the WebDav client without elevation..."
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compilerParameters.CompilerOptions="/unsafe"
$compilerParameters.GenerateInMemory = $True
Add-Type -TypeDefinition $Source -Language CSharp -CompilerParameters $compilerParameters
[JosL.WebClient.Starter]::startService()
log -text "Start Service Command completed without errors"
Start-Sleep -s 5
if((Get-Service -Name WebClient).status -eq "Running"){
log -text "detected that the webdav client is now running!"
}else{
log -text "but the webdav client is still not running! Please set the client to automatically start!" -fout
}
}catch{
Throw "Failed to start the webdav client :( $($Error[0])"
}
}
function restart_explorer{
log -text "Restarting Explorer.exe to make the drive(s) visible"
#kill all running explorer instances of this user
$explorerStatus = Get-ProcessWithOwner explorer
if($explorerStatus -eq 0){
log -text "no instances of Explorer running yet, at least one should be running" -warning
}elseif($explorerStatus -eq -1){
log -text "ERROR Checking status of Explorer.exe: unable to query WMI" -fout
}else{
log -text "Detected running Explorer processes, attempting to shut them down..."
foreach($Process in $explorerStatus){
try{
Stop-Process $Process.handle | Out-Null
log -text "Stopped process with handle $($Process.handle)"
}catch{
log -text "Failed to kill process with handle $($Process.handle)" -fout
}
}
}
}
function queryForAllCreds {
Param(
[Parameter(Mandatory=$true)]$titleText,
[Parameter(Mandatory=$true)]$introText,
[Parameter(Mandatory=$true)]$buttonText,
[Parameter(Mandatory=$true)]$loginLabel,
[Parameter(Mandatory=$true)]$passwordLabel
)
$objBalloon = New-Object System.Windows.Forms.NotifyIcon
$objBalloon.BalloonTipIcon = "Info"
$objBalloon.BalloonTipTitle = $titleText
$objBalloon.BalloonTipText = "OneDriveMapper - www.lieben.nu"
$objBalloon.Visible = $True
$objBalloon.ShowBalloonTip(10000)
$userForm = New-Object 'System.Windows.Forms.Form'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
$Form_StateCorrection_Load= {$userForm.WindowState = $InitialFormWindowState}
$userForm.Text = $titleText
$userForm.Size = New-Object System.Drawing.Size(400,380)
$userForm.StartPosition = "CenterScreen"
$userForm.AutoSize = $False
$userForm.MinimizeBox = $False
$userForm.MaximizeBox = $False
$userForm.SizeGripStyle= "Hide"
$userForm.WindowState = "Normal"
$userForm.FormBorderStyle="Fixed3D"
$userForm.KeyPreview = $True
$userForm.Add_KeyDown({if ($_.KeyCode -eq "Enter"){$userForm.Close()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(290,300)
$OKButton.Size = New-Object System.Drawing.Size(90,30)
$OKButton.Text = $buttonText
$OKButton.Add_Click({$userForm.Close()})
$userForm.Controls.Add($OKButton)
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,10)
$objTextBox.Size = New-Object System.Drawing.Size(370,180)
$objTextBox.Multiline = $True
$objTextBox.ReadOnly = $True
$objTextBox.Text = $introText
$userForm.Controls.Add($objTextBox)
$userLabel = New-Object System.Windows.Forms.Label
$userLabel.Location = New-Object System.Drawing.Size(10,200)
$userLabel.Size = New-Object System.Drawing.Size(370,20)
$userLabel.Text = $loginLabel
$userForm.Controls.Add($userLabel)
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Size(10,220)
$objTextBox2.Size = New-Object System.Drawing.Size(370,20)
$objTextBox2.Name = "loginField"
if($userUPN.Length -gt 5 -and $userUPN.IndexOf("@") -ne -1){
$objTextBox2.Text = $userUPN
}else{
$objTextBox2.Text = ""
}
$userForm.Controls.Add($objTextBox2)
$userLabel2 = New-Object System.Windows.Forms.Label
$userLabel2.Location = New-Object System.Drawing.Size(10,250)
$userLabel2.Size = New-Object System.Drawing.Size(370,20)
$userLabel2.Text = $passwordLabel
$userForm.Controls.Add($userLabel2)
$objTextBox3 = New-Object System.Windows.Forms.TextBox
$objTextBox3.UseSystemPasswordChar = $True
$objTextBox3.Location = New-Object System.Drawing.Size(10,270)
$objTextBox3.Size = New-Object System.Drawing.Size(370,20)
$objTextBox3.Text = ""
$objTextBox3.Name = "passwordField"
$userForm.Controls.Add($objTextBox3)
$userForm.Topmost = $True
$userForm.TopLevel = $True
$userForm.ShowIcon = $True
$userForm.Add_Shown({$userForm.Activate();
if($userUPN.Length -gt 5 -and $userUPN.IndexOf("@") -ne -1){
$objTextBox3.focus()
}else{
$objTextBox2.focus()
}})
$InitialFormWindowState = $userForm.WindowState
$userForm.add_Load($Form_StateCorrection_Load)
[void]$userForm.ShowDialog()
$objTextBox2.Text
$objTextBox3.Text
}
function checkIfAtO365URL{
param(
$userUPN,
[Array]$finalURLs