-
Notifications
You must be signed in to change notification settings - Fork 3
/
TimeZoneUI.ps1
1050 lines (908 loc) · 42.4 KB
/
TimeZoneUI.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
<#
.SYNOPSIS
Prompts user to set time zone
.DESCRIPTION
Prompts user to set time zone using windows presentation framework
Can be used in:
- SCCM Tasksequences (User interface allowed)
- SCCM Software Delivery (User interface allowed)
- Intune Autopilot
.NOTES
Author : Dick Tracy <richard.tracy@hotmail.com>
Source : https://github.com/PowerShellCrack/AutopilotTimeZoneSelectorUI
Version : 2.0.6
README : Review README.md for more details and configurations
CHANGELOG : Review CHANGELOG.md for updates and fixes
IMPORTANT : By using this script or parts of it, you have read and accepted the DISCLAIMER.md and LICENSE agreement
.LINK
https://matthewjwhite.co.uk/2019/04/18/intune-automatically-set-timezone-on-new-device-build/
https://ipstack.com
https://azuremarketplace.microsoft.com/en-us/marketplace/apps/bingmaps.mapapis
.PARAMETER SyncNTP
String --> defaults to 'pool.ntp.org'
If value exist, the script will attempt to sync time with NTP.
If this is not desired, remove the value or call it '-SynNTP $Null'
NTP uses port UDP 123
.PARAMETER IpStackAPIKey
String --> value is Null
Used to get geoCoordinates of the public IP. get the API key from https://ipstack.com
.PARAMETER BingMapsAPIKeyy
String --> value is Null
Used to get the Windows TimeZone value of the location coordinates. get the API key from https://azuremarketplace.microsoft.com/en-us/marketplace/apps/bingmaps.mapapis
.PARAMETER NoControl
Boolean (True or False) --> Default is False
Used for single deployment scenarios; This will not track status by writing registry keys.
WARNING: UserDriven & RunOnce options are **IGNORED**.
.PARAMETER UserDriven
Boolean (True or False) --> Default is True
Deploy to user when set to true.
if _true_ sets HKCU key, if _false_, set HKLM key.
Set to True if the deployment is for Autopilot.
When using 'Users context deployment' and UserDriven is ste to False; users will need permission to write to device registry hive
.PARAMETER NoUI
Boolean (True or False) --> Default is False
If set to True, the UI will not show but still attempt to set the timezone.
If API Keys are provided it will use the internet to determine location.
If Keys are not set, then it won't change the timezone because its the same as before, but it will attempt to sync time if a NTP value is provided.
.PARAMETER RunOnce
Boolean (True or False) --> Default is True
Specifies this script will only launch one time.
If RunOnce set to True and UserDriven is True, it will launch once for each user on the device.
If RunOnce set to True and UserDriven is False, it will only launch once for the first user to login on the device
If RunOnce set to False and UserDriven is True and on a reoccurring schedule, it will launch once for each user every time for each occupance (NOT RECOMMENDED)
If RunOnce set to False and UserDriven is False and on a reoccurring schedule, it will launch for the current user logged in each occupance (NOT RECOMMENDED)
.PARAMETER ForceInteraction
Boolean (True or False) --> Default is False
If set to True, no matter the other settings (including NoUI), the UI will **ALWAYS** show!
.EXAMPLE
NOTE: this example is using invalid API keys.
PS> .\TimeZoneUI.ps1 -IpStackAPIKey "4bd1443445dfhrrt9dvefr45341" -BingMapsAPIKey "Bh53uNUOwg71czosmd73hKfdHf465ddfhrtpiohvknlkewufjf4-d" -Verbose
RESULT: Uses IP GEO location for the pre-selection
.EXAMPLE
PS> .\TimeZoneUI.ps1 -ForceInteraction:$true -verbose
RESULT: This will ALWAYS display the time selection screen; if IPStack and BingMapsAPI included the IP GEO location timezone will be preselected. Verbose output will be displayed
.EXAMPLE
NOTE: this example is using invalid API keys.
PS> .\TimeZoneUI.ps1 -IpStackAPIKey "4bd1443445dfhrrt9dvefr45341" -BingMapsAPIKey "Bh53uNUOwg71czosmd73hKfdHf465ddfhrtpiohvknlkewufjf4-d" -NoUI:$true -SyncNTP "time-a-g.nist.gov"
RESULT: This will set the time automatically using the IP GEO location without prompting user. If API not provided, timezone or time will not change the current settings
.EXAMPLE
PS> .\TimeZoneUI.ps1 -UserDriven:$false
RESULT: Writes a registry key in System (HKEY_LOCAL_MACHINE) hive to determine run status
.EXAMPLE
PS> .\TimeZoneUI.ps1 -RunOnce:$true
RESULT: This allows the screen to display one time. RECOMMENDED for Autopilot to display after ESP screen
#>
#===========================================================================
# CONTROL VARIABLES
#===========================================================================
[CmdletBinding()]
param(
[string]$SyncNTP = 'pool.ntp.org',
[string]$IpStackAPIKey = "",
[string]$BingMapsAPIKey = "" ,
[boolean]$NoControl = $False,
[boolean]$UserDriven = $true,
[boolean]$RunOnce = $true,
[boolean]$NoUI = $False,
[boolean]$ForceInteraction = $false
)
#*=============================================
##* Runtime Function - REQUIRED
##*=============================================
#region FUNCTION: Check if running in WinPE
Function Test-WinPE{
return Test-Path -Path Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlset\Control\MiniNT
}
#endregion
#region FUNCTION: Check if running in ISE
Function Test-IsISE {
# try...catch accounts for:
# Set-StrictMode -Version latest
try {
return ($null -ne $psISE);
}
catch {
return $false;
}
}
#endregion
#region FUNCTION: Check if running in Visual Studio Code
Function Test-VSCode{
if($env:TERM_PROGRAM -eq 'vscode') {
return $true;
}
Else{
return $false;
}
}
#endregion
#region FUNCTION: Find script path for either ISE or console
Function Get-ScriptPath {
<#
.SYNOPSIS
Finds the current script path even in ISE or VSC
.LINK
Test-VSCode
Test-IsISE
#>
param(
[switch]$Parent
)
Begin{}
Process{
if ($PSScriptRoot -eq "")
{
if (Test-IsISE)
{
$ScriptPath = $psISE.CurrentFile.FullPath
}
elseif(Test-VSCode){
$context = $psEditor.GetEditorContext()
$ScriptPath = $context.CurrentFile.Path
}Else{
$ScriptPath = (Get-location).Path
}
}
else
{
$ScriptPath = $PSCommandPath
}
}
End{
If($Parent){
Split-Path $ScriptPath -Parent
}Else{
$ScriptPath
}
}
}
#endregion
#region FUNCTION: Attempt to connect to Task Sequence environment
Function Test-SMSTSENV{
<#
.SYNOPSIS
Tries to establish Microsoft.SMS.TSEnvironment COM Object when running in a Task Sequence
.REQUIRED
Allows Set Task Sequence variables to be set
.PARAMETER ReturnLogPath
If specified, returns the log path, otherwise returns ts environment
#>
[CmdletBinding()]
param(
[switch]$ReturnLogPath
)
Begin{
## Get the name of this function
[string]${CmdletName} = $MyInvocation.MyCommand
}
Process{
try{
# Create an object to access the task sequence environment
$tsenv = New-Object -ComObject Microsoft.SMS.TSEnvironment
#grab the progress UI
$TSProgressUi = New-Object -ComObject Microsoft.SMS.TSProgressUI
Write-Verbose ("Task Sequence environment detected!")
}
catch{
Write-Verbose ("Task Sequence environment NOT detected.")
#set variable to null
$tsenv = $null
}
Finally{
#set global Logpath
if ($null -ne $tsenv)
{
# Convert all of the variables currently in the environment to PowerShell variables
#$tsenv.GetVariables() | ForEach-Object { Set-Variable -Name "$_" -Value "$($tsenv.Value($_))" }
# Query the environment to get an existing variable
# Set a variable for the task sequence log path
#Something like C:\WINDOWS\CCM\Logs\SMSTSLog
[string]$LogPath = $tsenv.Value("_SMSTSLogPath")
If($null -eq $LogPath){$LogPath = $env:Temp}
}
Else{
$LogPath = $env:Temp
$tsenv = $false
}
}
}
End{
If($ReturnLogPath){
return $LogPath
}
Else{
return $tsenv
}
}
}
#endregion
Function Write-LogEntry{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[string]$Message,
[Parameter(Mandatory=$false,Position=1)]
[string]$Source = '',
[Parameter(Mandatory=$false,Position=2)]
[ValidateSet(0,1,2,3,4)]
[int16]$Severity,
[parameter(Mandatory=$false, HelpMessage="Name of the log file that the entry will written to.")]
[ValidateNotNullOrEmpty()]
[string]$OutputLogFile = $Global:LogFilePath,
[parameter(Mandatory=$false)]
[switch]$Outhost
)
Begin{
## Get the name of this function
[string]$LogTime = (Get-Date -Format 'HH:mm:ss.fff').ToString()
[string]$LogDate = (Get-Date -Format 'MM-dd-yyyy').ToString()
[int32]$script:LogTimeZoneBias = [timezone]::CurrentTimeZone.GetUtcOffset([datetime]::Now).TotalMinutes
[string]$LogTimePlusBias = $LogTime + $script:LogTimeZoneBias
# Get the file name of the source script
}
Process{
Try {
If ($script:MyInvocation.Value.ScriptName) {
[string]$ScriptSource = Split-Path -Path $script:MyInvocation.Value.ScriptName -Leaf -ErrorAction 'Stop'
}
Else {
[string]$ScriptSource = Split-Path -Path $script:MyInvocation.MyCommand.Definition -Leaf -ErrorAction 'Stop'
}
}
Catch {
$ScriptSource = ''
}
If(!$Severity){$Severity = 1}
$LogFormat = "<![LOG[$Message]LOG]!>" + "<time=`"$LogTimePlusBias`" " + "date=`"$LogDate`" " + "component=`"$ScriptSource`" " + "context=`"$([Security.Principal.WindowsIdentity]::GetCurrent().Name)`" " + "type=`"$Severity`" " + "thread=`"$PID`" " + "file=`"$ScriptSource`">"
# Add value to log file
try {
Out-File -InputObject $LogFormat -Append -NoClobber -Encoding Default -FilePath $OutputLogFile -ErrorAction Stop
}
catch {
Write-Output ("[{0}] [{1}] :: Unable to append log entry to [{2}]: {3}" -f $LogTimePlusBias,$ScriptSource,$OutputLogFile,$_.Exception.Message)
}
If($Outhost){
If($Source){
$OutputMsg = ("[{0}] [{1}] :: {2}" -f $LogTimePlusBias,$Source,$Message)
}
Else{
$OutputMsg = ("[{0}] [{1}] :: {2}" -f $LogTimePlusBias,$ScriptSource,$Message)
}
Switch($Severity){
0 {Write-Output $OutputMsg}
1 {Write-Output $OutputMsg}
2 {Write-Warning $OutputMsg}
3 {Write-Output $OutputMsg}
4 {If($VerbosePreference){Write-Verbose $OutputMsg}}
default {Write-Output $OutputMsg}
}
}
}
End{}
}
##*=============================================
##* VARIABLE DECLARATION
##*=============================================
#region VARIABLES: Building paths & values
[string]$scriptPath = Get-ScriptPath
[string]$scriptName = [IO.Path]::GetFileNameWithoutExtension($scriptPath)
#Grab all times zones plus current timezones
$Global:AllTimeZones = Get-TimeZone -ListAvailable
$Global:CurrentTimeZone = Get-TimeZone
$Global:NTPServer = $SyncNTP
#set the appropriate registry hive to use when logging
If($UserDriven -eq $false){$RegHive = 'HKLM'}Else{$RegHive = 'HKCU'}
#Return log path (either in task sequence or temp dir)
#build log name
[string]$FileName = $scriptName +'.log'
#build global log fullpath
$Global:LogFilePath = Join-Path (Test-SMSTSENV -ReturnLogPath -Verbose) -ChildPath $FileName
Write-Host "logging to file: $LogFilePath" -ForegroundColor Cyan
#===========================================================================
# XAML LANGUAGE
#===========================================================================
$XAMLPayload = @"
<Window x:Class="SelectTimeZoneWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SelectTimeZoneWPF"
mc:Ignorable="d"
WindowState="Maximized"
WindowStartupLocation="CenterScreen"
WindowStyle="None"
Title="Time Zone Selection">
<Window.Resources>
<ResourceDictionary>
<Style TargetType="{x:Type Window}">
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="FontWeight" Value="Light" />
<Setter Property="Background" Value="#FF1D3245" />
<Setter Property="Foreground" Value="#FFE8EDF9" />
</Style>
<Style x:Key="DataGridContentCellCentering" TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="#FF1D3245" />
<Setter Property="Foreground" Value="#FFE8EDF9" />
<Setter Property="FontSize" Value="15" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button" >
<Border Name="border"
BorderThickness="1"
Padding="4,2"
BorderBrush="#FF1D3245"
CornerRadius="2"
Background="#00A4EF">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"
TextBlock.TextAlignment="Center"
/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="#FFE8EDF9" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="#FF1D3245" />
<Setter Property="Button.Foreground" Value="#FF1D3245" />
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect ShadowDepth="0" Color="#FF1D3245" Opacity="1" BlurRadius="10"/>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="{x:Type ListBox}" TargetType="ListBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Border Name="Border" BorderThickness="1" CornerRadius="2">
<ScrollViewer Margin="0" Focusable="false">
<StackPanel Margin="2" IsItemsHost="True" />
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="{x:Type ListBoxItem}" TargetType="ListBoxItem">
<Setter Property="ScrollViewer.CanContentScroll" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="ItemBorder" Padding="8" Margin="1" Background="#FF1D3245">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="ItemBorder" Property="Background" Value="#00A4EF" />
<Setter Property="Foreground" Value="#FF1D3245" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True" />
<Condition Property="IsSelected" Value="False" />
</MultiTrigger.Conditions>
<Setter TargetName="ItemBorder" Property="Background" Value="#00A4EF" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid Background="#FF1D3245" HorizontalAlignment="Center" VerticalAlignment="Center" Height="600">
<TextBlock x:Name="txtTimeZoneTitle" HorizontalAlignment="Center" Text="@anchor" VerticalAlignment="Top" FontSize="48"/>
<ListBox x:Name="lbxTimeZoneList" HorizontalAlignment="Center" VerticalAlignment="Top" Background="#FF1D3245" Foreground="#FFE8EDF9" FontSize="18" Width="700" Height="400" Margin="0,80,0,0" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionMode="Single"/>
<Button x:Name="btnTZSelect" Content="Select Time Zone" Height="65" Width="200" HorizontalAlignment="Center" VerticalAlignment="Bottom" FontSize="18" Padding="10"/>
</Grid>
</Window>
"@
#replace some default attributes to support powershell
[string]$XAMLPayload = $XAMLPayload -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window'
#=======================================================
# LOAD ASSEMBLIES
#=======================================================
#[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | out-null #creating Windows-based applications
#[System.Reflection.Assembly]::LoadWithPartialName('WindowsFormsIntegration') | out-null # Call the EnableModelessKeyboardInterop; allows a Windows Forms control on a WPF page.
If(Test-WinPE -or Test-IsISE){[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Application') | out-null} #Encapsulates a Windows Presentation Foundation application.
#[System.Reflection.Assembly]::LoadWithPartialName('System.ComponentModel') | out-null #systems components and controls and convertors
#[System.Reflection.Assembly]::LoadWithPartialName('System.Data') | out-null #represent the ADO.NET architecture; allows multiple data sources
[System.Reflection.Assembly]::LoadWithPartialName('presentationframework') | out-null #required for WPF
[System.Reflection.Assembly]::LoadWithPartialName('PresentationCore') | out-null #required for WPF
#convert to XML
[xml]$XMLPayload = $XAMLPayload
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $XMLPayload)
try{$TZSelectUI=[Windows.Markup.XamlReader]::Load( $reader )}
catch{
Write-LogEntry ("Unable to load Windows.Markup.XamlReader. {0}" -f $_.Exception.Message) -Severity 3 -Outhost
Exit $_.Exception.HResult
}
#===========================================================================
# Store Form Objects In PowerShell
#===========================================================================
#take the xaml properties and make them variables
$XMLPayload.SelectNodes("//*[@Name]") | %{Set-Variable -Name "ui_$($_.Name)" -Value $TZSelectUI.FindName($_.Name)}
Function Get-FormVariables{
if ($global:ReadmeDisplay -ne $true){
Write-Verbose "To reference this display again, run Get-FormVariables"
$global:ReadmeDisplay=$true
}
Write-Verbose "Displaying elements from the form"
Get-Variable ui_*
}
If($DebugPreference){Get-FormVariables}
#====================
#Form Functions
#====================
Function Set-StatusKey{
param(
[parameter(Mandatory=$False)]
[ValidateSet('HKLM','HKCU')]
[string]$Hive = 'HKCU',
[parameter(Mandatory=$True)]
[string]$Name,
[parameter(Mandatory=$True)]
[string]$Value
)
Begin
{
If(!(Test-Path "$($Hive):\SOFTWARE\PowerShellCrack\TimeZoneSelector") ){
New-Item -Path "$($Hive):\SOFTWARE" -Name "PowerShellCrack" -ErrorAction SilentlyContinue | Out-Null
New-Item -Path "$($Hive):\SOFTWARE\PowerShellCrack" -Name 'TimeZoneSelector' -ErrorAction SilentlyContinue | Out-Null
}
}
Process
{
Try{
Set-ItemProperty -Path "$($Hive):\SOFTWARE\PowerShellCrack\TimeZoneSelector" -Name $Name -Value $Value -Force -ErrorAction Stop | Out-Null
}
Catch{
Write-LogEntry ("Unable to set status key name [{0}] with value [{1}]. {2}" -f $Name,$Value,$_.Exception.Message) -Severity 3 -Outhost
}
}
End
{
Set-ItemProperty -Path "$($Hive):\SOFTWARE\PowerShellCrack\TimeZoneSelector" -Name "LastRan" -Value (Get-Date) -Force -ErrorAction SilentlyContinue | Out-Null
}
}
Function Start-TimeSelectorUI{
<#TEST VALUES
$UIObject=$TZSelectUI
$UpdateStatusKeyHive=$RegHive
$UpdateStatusKeyHive="HKLM"
#>
[CmdletBinding()]
param(
$UIObject,
[string]$UpdateStatusKeyHive
)
If($PSBoundParameters.ContainsKey('UpdateStatusKeyHive')){Set-StatusKey -Hive $UpdateStatusKeyHive -Name Status -Value "Running"}
Try{
#$UIObject.ShowDialog() | Out-Null
# Credits to - http://powershell.cz/2013/04/04/hide-and-show-console-window-from-gui/
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
# Allow input to window for TextBoxes, etc
[Void][System.Windows.Forms.Integration.ElementHost]::EnableModelessKeyboardInterop($UIObject)
#for ISE testing only: Add ESC key as a way to exit UI
$code = {
[System.Windows.Input.KeyEventArgs]$esc = $args[1]
if ($esc.Key -eq 'ESC')
{
$UIObject.Close()
[System.Windows.Forms.Application]::Exit()
#this will kill ISE
[Environment]::Exit($ExitCode);
}
}
$null = $UIObject.add_KeyUp($code)
$UIObject.Add_Closing({
[System.Windows.Forms.Application]::Exit()
})
$async = $UIObject.Dispatcher.InvokeAsync({
#make sure this display on top of every window
$UIObject.Topmost = $true
# Running this without $appContext & ::Run would actually cause a really poor response.
$UIObject.Show() | Out-Null
# This makes it pop up
$UIObject.Activate() | Out-Null
#$UI.window.ShowDialog()
})
$async.Wait() | Out-Null
## Force garbage collection to start form with slightly lower RAM usage.
[System.GC]::Collect() | Out-Null
[System.GC]::WaitForPendingFinalizers() | Out-Null
# Create an application context for it to all run within.
# This helps with responsiveness, especially when Exiting.
$appContext = New-Object System.Windows.Forms.ApplicationContext
[void][System.Windows.Forms.Application]::Run($appContext)
}
Catch{
If($PSBoundParameters.ContainsKey('UpdateStatusKeyHive')){Set-StatusKey -Hive $UpdateStatusKeyHive -Name Status -Value 'Failed'}
Write-LogEntry ("Unable to load Windows Presentation UI. {0}" -f $_.Exception.Message) -Severity 3 -Outhost
Exit $_.Exception.HResult
}
}
function Stop-TimeSelectorUI{
<#TEST VALUES
$UIObject=$TZSelectUI
$UpdateStatusKeyHive="$RegHive\$RegPath"
$UpdateStatusKeyHive="HKLM:\SOFTWARE\PowerShellCrack\TimeZoneSelector"
#>
[CmdletBinding()]
param(
$UIObject,
[string]$UpdateStatusKeyHive,
[string]$CustomStatus
)
If($CustomStatus){$status = $CustomStatus}
Else{$status = 'Completed'}
Try{
If($PSBoundParameters.ContainsKey('UpdateStatusKeyHive')){Set-StatusKey -Hive $UpdateStatusKeyHive -Name Status -Value $status}
#$UIObject.Close() | Out-Null
$UIObject.Close()
}
Catch{
If($PSBoundParameters.ContainsKey('UpdateStatusKeyHive')){Set-StatusKey -Hive $UpdateStatusKeyHive -Name Status -Value 'Failed'}
Write-LogEntry ("Failed to stop Windows Presentation UI properly. {0}" -f $_.Exception.Message) -Severity 2 -Outhost
#Exit $_.Exception.HResult
}
}
function Set-NTPDateTime
{
[CmdletBinding()]
param(
[string] $sNTPServer
)
$StartOfEpoch=New-Object DateTime(1900,1,1,0,0,0,[DateTimeKind]::Utc)
[Byte[]]$NtpData = ,0 * 48
$NtpData[0] = 0x1B # NTP Request header in first byte
$Socket = New-Object Net.Sockets.Socket([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Dgram, [Net.Sockets.ProtocolType]::Udp)
$Socket.Connect($sNTPServer,123)
$t1 = Get-Date # Start of transaction... the clock is ticking...
[Void]$Socket.Send($NtpData)
[Void]$Socket.Receive($NtpData)
$t4 = Get-Date # End of transaction time
$Socket.Close()
$IntPart = [BitConverter]::ToUInt32($NtpData[43..40],0) # t3
$FracPart = [BitConverter]::ToUInt32($NtpData[47..44],0)
$t3ms = $IntPart * 1000 + ($FracPart * 1000 / 0x100000000)
$IntPart = [BitConverter]::ToUInt32($NtpData[35..32],0) # t2
$FracPart = [BitConverter]::ToUInt32($NtpData[39..36],0)
$t2ms = $IntPart * 1000 + ($FracPart * 1000 / 0x100000000)
$t1ms = ([TimeZoneInfo]::ConvertTimeToUtc($t1) - $StartOfEpoch).TotalMilliseconds
$t4ms = ([TimeZoneInfo]::ConvertTimeToUtc($t4) - $StartOfEpoch).TotalMilliseconds
$Offset = (($t2ms - $t1ms) + ($t3ms-$t4ms))/2
[String]$NTPDateTime = $StartOfEpoch.AddMilliseconds($t4ms + $Offset).ToLocalTime()
Try{
Write-LogEntry ("Synchronizing with NTP server [{0}]." -f $sNTPServer) -Severity 4 -Outhost
Write-LogEntry ("Attempting to change date and time to: [{0}]..." -f $NTPDateTime) -Severity 4 -Outhost
Set-Date $NTPDateTime -ErrorAction Stop | Out-Null
Write-LogEntry ("Successfully updated date and time!") -Severity 4 -Outhost
}
Catch{
Write-LogEntry ("Unable to set date and time: {0}" -f $_.Exception.Message) -Severity 2 -Outhost
}
}
Function Get-GeographicData {
[CmdletBinding()] #This provides the function with the -Verbose and -Debug parameters
param(
[string]$IpStackAPIKey,
[string]$BingMapsAPIKey
)
#determine if device is intune managed
#if it is, it will parse log to determine if this script it being ran by intune
#and remove API sensitive data
$intuneManagementExtensionLogPath = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\IntuneManagementExtension.log"
If(Test-Path $intuneManagementExtensionLogPath -ErrorAction SilentlyContinue){
$IntuneManaged = $true
}else {
$IntuneManaged = $false
}
#attempt connecting online if both keys exist
If($PSBoundParameters.ContainsKey('IpStackAPIKey') -and $PSBoundParameters.ContainsKey('BingMapsAPIKey'))
{
Write-LogEntry "Checking GEO Coordinates by IP for time zone..." -Severity 4 -Outhost
#Write-Verbose "IPStack API: $IpStackAPIKey"
#Write-Verbose "Bing Maps API: $BingMapsAPIKey"
#grab public IP and its geo location
try {
$IPStackURI = "http://api.ipstack.com/check?access_key=$($IpStackAPIKey)"
If($DebugPreference){
Write-LogEntry ("Initializing Ipstack REST URI: {0}" -f $IPStackURI) -Severity 4 -Outhost
}Else{
Write-LogEntry ("Initializing Ipstack REST URI: {0}" -f ($IPStackURI.replace($IpStackAPIKey,'<sensitive data>') ) ) -Severity 4 -Outhost
}
$geoIP = Invoke-RestMethod -Uri $IPStackURI -ErrorAction Stop
}
Catch {
Write-LogEntry ("Error obtaining coordinates or public IP address. {0}" -f $_.Exception.Message) -Severity 2 -Outhost
}
Finally{
If($IntuneManaged){
Write-LogEntry ("Clearing sensitive data in Intune Management Extension log...") -Severity 4 -Outhost
# Hide the api keys from logs to prevent manipulation API's
Try{
(Get-Content -Path $intuneManagementExtensionLogPath).replace($IpStackAPIKey,'<sensitive data>') |
Set-Content -Path $intuneManagementExtensionLogPath -ErrorAction SilentlyContinue | Out-Null
}Catch{
Write-LogEntry ("Unable to remove IpStack API key from intune log file: {0}" -f $_.exception.message) -Severity 3 -Outhost
}
}
}
#determine geo location's timezone
try {
Write-LogEntry ("Discovered [{0}] is located in [{1}] at coordinates [{2},{3}]" -f $geoIP.ip,$geoIP.country_name,$geoIP.latitude,$geoIP.longitude) -Severity 4 -Outhost
$bingURI = "https://dev.virtualearth.net/REST/v1/timezone/$($geoIP.latitude),$($geoIP.longitude)?key=$($BingMapsAPIKey)"
If($DebugPreference){
Write-LogEntry ("Initializing BingMaps REST URI: {0}" -f $bingURI) -Severity 4 -Outhost
}Else{
Write-LogEntry ("Initializing Ipstack REST URI: {0}" -f ($bingURI.replace($BingMapsAPIKey,'<sensitive data>') ) ) -Severity 4 -Outhost
}
$BingApiResponse = Invoke-RestMethod -Uri $bingURI -ErrorAction Stop
$GEOTimeZone = $BingApiResponse.resourceSets.resources.timeZone.windowsTimeZoneId
$GEODateTime = $BingApiResponse.resourceSets.resources.timeZone.ConvertedTime | Select -ExpandProperty localTime
}
catch {
Write-LogEntry ("Error obtaining response from Bing Maps API. {0}" -f $_.Exception.Message) -Severity 2 -Outhost
}
Finally{
If($IntuneManaged){
Write-LogEntry ("Clearing sensitive data in Intune Management Extension log...") -Severity 4 -Outhost
# Hide the api keys from logs to prevent manipulation API's
Try{
(Get-Content -Path $intuneManagementExtensionLogPath).replace($BingMapsAPIKey,'<sensitive data>') |
Set-Content -Path $intuneManagementExtensionLogPath -ErrorAction SilentlyContinue | Out-Null
}Catch{
Write-LogEntry ("Unable to remove BingMaps API key from intune log file: {0}" -f $_.exception.message) -Severity 3 -Outhost
}
}
}
}
If($GEOTimeZone)
{
Write-LogEntry ("Discovered geographic time zone: {0}" -f $GEOTimeZone) -Severity 4 -Outhost
$SelectedTimeZone = $Global:AllTimeZones | Where id -eq $GEOTimeZone
}Else
{
Write-LogEntry ("No geographic time was provided, using current time zone instead...") -Severity 4 -Outhost
$SelectedTimeZone = $Global:CurrentTimeZone
$GEOTimeZone = $SelectedTimeZone.Id
}
#build GEO data object
$GeoData = "" | Select DateTime,Id,DisplayName,StandardName
$GeoData.DateTime = $GEODateTime
$GeoData.Id = $GEOTimeZone
$GeoData.DisplayName = $SelectedTimeZone.DisplayName
$GeoData.StandardName = $SelectedTimeZone.StandardName
#return data object
return $GeoData
}
Function Update-DeviceTimeZone{
<#TEST VALUES
$SelectedTZ=$ui_lbxTimeZoneList.SelectedItem
$DefaultTimeZone=(Get-TimeZone).DisplayName
#>
[CmdletBinding()]
param(
[string]$SelectedTZ
)
#update time zone if different than detected
$SelectedTimeZoneObj = $Global:AllTimeZones | Where {$_.DisplayName -eq $SelectedTZ}
If($SelectedTZ -ne $Global:CurrentTimeZone.DisplayName)
{
Try{
Write-LogEntry ("Attempting to change time zone to: {0}..." -f $SelectedTZ) -Severity 4 -Outhost
Set-TimeZone $SelectedTimeZoneObj -ErrorAction Stop | Out-Null
Start-Service W32Time | Restart-Service -ErrorAction Stop
Write-LogEntry ("Completed time zone change!" -f $SelectedTZ) -Severity 4 -Outhost
}
Catch{
#Throw $_.Exception.Message
Write-LogEntry ("Failed to set device time zone. {0}" -f $_.Exception.Message) -Severity 3 -Outhost
Exit $_.Exception.HResult
}
}Else{
Write-LogEntry "No change. Skipping time zone update" -Severity 4 -Outhost
}
}
#===========================================================================
# Actually make the UI work
#===========================================================================
#splat Params. Check if IPstack and Bingmap values DO NOT EXIST; use default timeseletions
If( ([string]::IsNullOrEmpty($IpStackAPIKey)) -or ([string]::IsNullOrEmpty($BingMapsAPIKey)) ){
$ui_txtTimeZoneTitle.Text = $ui_txtTimeZoneTitle.Text -replace "@anchor","What time zone are you in?"
$GeoTZParams = @{
Verbose=$VerbosePreference
Debug=$DebugPreference
}
}
Else{
$ui_txtTimeZoneTitle.Text = $ui_txtTimeZoneTitle.Text -replace "@anchor","Is this the time zone your in?"
$GeoTZParams = @{
ipStackAPIKey=$IpStackAPIKey
bingMapsAPIKey=$BingMapsAPIKey
Verbose=$VerbosePreference
Debug=$DebugPreference
}
}
#determine if Selector control will update status
If(!(Test-WinPE) -and ($NoControl -eq $false))
{
$UIControlParam = @{
UIObject=$TZSelectUI
UpdateStatusKeyHive=$RegHive
Verbose=$VerbosePreference
Debug=$DebugPreference
}
}Else{
$UIControlParam = @{
UIObject=$TZSelectUI
Verbose=$VerbosePreference
Debug=$DebugPreference
}
}
#Get all timezones and load it to combo box
$Global:AllTimeZones.DisplayName | ForEach-object {$ui_lbxTimeZoneList.Items.Add($_)} | Out-Null
#grab Geo Timezone
<#TEST Timezones
$TargetGeoTzObj = (Get-TimeZone -listAvailable)[9] #<---(UTC-08:00) Pacific Time (US & Canada)
$TargetGeoTzObj = (Get-TimeZone -listAvailable)[12] #<---(UTC-07:00) Mountain Time (US & Canada)
$TargetGeoTzObj = (Get-TimeZone -listAvailable)[15] #<---(UTC-06:00) Central Time (US & Canada)
$TargetGeoTzObj = (Get-TimeZone -listAvailable)[21] #<---(UTC-05:00) Eastern Time (US & Canada)
$TargetGeoTzObj = (Get-TimeZone)
#>
$TargetGeoTzObj = Get-GeographicData @GeoTZParams
#select current time zone
Write-LogEntry ("The selected time zone is: {0}" -f $TargetGeoTzObj.DisplayName) -Severity 4 -Outhost
$ui_lbxTimeZoneList.SelectedItem = $TargetGeoTzObj.DisplayName
#scrolls list to current selected item
#+3 below to center selected item on screen
$ui_lbxTimeZoneList.ScrollIntoView($ui_lbxTimeZoneList.Items[$ui_lbxTimeZoneList.SelectedIndex+3])
#when button is clicked changer time
$ui_btnTZSelect.Add_Click({
Try{
#Set time zone
#Set-TimeZone $ui_lbxTimeZoneList.SelectedItem
Update-DeviceTimeZone -SelectedTZ $ui_lbxTimeZoneList.SelectedItem
#build registry key for time selector
If($null -ne $UIControlParam.UpdateStatusKeyHive){Set-StatusKey -Hive $RegHive -Name TimeZoneSelected -Value $ui_lbxTimeZoneList.SelectedItem}
#update the time and date
If($SyncNTP)
{
Set-NTPDateTime -sNTPServer $Global:NTPServer -Verbose:$VerbosePreference
If($null -ne $UIControlParam.UpdateStatusKeyHive){Set-StatusKey -Hive $RegHive -Name SyncedToNTP -Value $Global:NTPServer}
}
Else{
Write-LogEntry ("No NTP server specified. Skipping date and time update.") -Severity 4 -Outhost
}
}Catch{
Write-LogEntry ("Unable to change timezone: {0}" -f $_.exception.message) -Severity 3 -Outhost
'TimeZone:' + $ui_lbxTimeZoneList.SelectedItem | Set-Content $env:PUBLIC\timezone.txt
'NTPServer:' + $Global:NTPServer | Add-Content $env:PUBLIC\timezone.txt
}
Finally{
#always close the UI
Stop-TimeSelectorUI @UIControlParam
#If(!$isISE){Stop-Process $pid}
}
})
#===========================================================================
# Main - Call the form depending on logic
#===========================================================================
<# LOGIC for UI
UI will show if:
- 'ForceInteraction' parameter set to True
- 'UI has not detected itself running before or it has failed or not completed
UI will NOT show if:
- 'ForceInteraction' parameter set to False AND 'NoUI' parameter is set to True
- Time is not different from detected Geographic time (this will only work if IpStack/Bing API are included)
- If script detected its still running OR last status is set to 'running'
UI will make changes if:
- If UI is displayed and change is selected
- NoUI is set to True
#>
# found that if script is called by Intune, the script may be running multiple times if the ESP screen process takes a while
# Only allow the script to run once if it is already being displayed
If($ForceInteraction){
#run form all the time
Write-LogEntry ("'ForceInteraction' parameter is enabled; UI will be displayed") -Severity 4 -Outhost
Start-TimeSelectorUI @UIControlParam
}
#if noUI is set; attempt to set the timezone and time without UI interaction
ElseIf($NoUI)
{
Write-LogEntry ("'NoUI' parameter is enabled; UI will NOT be displayed") -Severity 4 -Outhost
#update the time zone
Update-DeviceTimeZone -SelectedTZ $TargetGeoTzObj.DisplayName
#log changes to registry
If($null -ne $UIControlParam.UpdateStatusKeyHive){Set-StatusKey -Hive $RegHive -Name TimeZoneSelected -Value $ui_lbxTimeZoneList.SelectedItem}
#update the time and date
If($SyncNTP){
Set-NTPDateTime -sNTPServer $Global:NTPServer -Verbose:$VerbosePreference
If($null -ne $UIControlParam.UpdateStatusKeyHive){Set-StatusKey -Hive $RegHive -Name SyncedToNTP -Value $Global:NTPServer}
}Else{
Write-LogEntry ("No NTP server specified. Skipping date and time update.") -Severity 4 -Outhost
}
}
Elseif($NoControl){
Write-LogEntry ("'NoControl' is enabled; UI will be displayed without monitoring registry.") -Severity 4 -Outhost
Start-TimeSelectorUI @UIControlParam
}
ElseIf( Get-Process | Where {$_.MainWindowTitle -eq "Time Zone Selection"} ){
#do nothing
Write-LogEntry "Detected that UI process is still running. UI will not be displayed." -Severity 4 -Outhost
}
ElseIf($RunOnce){