This repository was archived by the owner on Aug 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathWin 8.1.ps1
1725 lines (1569 loc) · 75.1 KB
/
Win 8.1.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
"Windows 8.1 Setup Script" is a set of tweaks for OS fine-tuning and automating the routine tasks
.DESCRIPTION
Supported Windows 8.1: 6.3.9600 build, x64
Tested on Home/Pro/Enterprise editions
Check whether the .ps1 file is encoded in UTF-8 with BOM
The script can not be executed via PowerShell ISE
PowerShell must be run with elevated privileges
Set execution policy to be able to run scripts only in the current PowerShell session:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force
Install before executing
https://www.microsoft.com/en-us/download/details.aspx?id=42642
https://docs.microsoft.com/ru-ru/powershell/scripting/windows-powershell/wmf/setup/install-configure
Running the script is best done on a fresh install
.EXAMPLE
PS C:\> & '.\Win 8.1.ps1'
.NOTES
Version: v4.3.1
Date: 11.06.2020
Written by: farag & oZ-Zo
Thanks to all http://forum.ru-board.com members involved
Ask a question on
http://forum.ru-board.com/topic.cgi?forum=62&topic=30617#15
https://habr.com/en/post/465365/
https://4pda.ru/forum/index.php?showtopic=523489&st=42860#entry95909388
https://forums.mydigitallife.net/threads/powershell-script-setup-windows-10.81675/
https://www.reddit.com/r/PowerShell/comments/go2n5v/powershell_script_setup_windows_10/
Copyright (c) 2020 farag & oZ-Zo
.LINK
https://github.com/farag2/Setup-Windows-8.1
#>
#Requires -RunAsAdministrator
#Requires -Version 5.1
#region Check
Clear-Host
# Get information about the current culture settings
# Получить сведения о параметрах текущей культуры
if ($PSUICulture -eq "ru-RU")
{
$RU = $true
}
# Detect the OS bitness
# Определить разрядность ОС
switch ([Environment]::Is64BitOperatingSystem)
{
$false
{
if ($RU)
{
Write-Warning -Message "Скрипт поддерживает только Windows 10 x64"
}
else
{
Write-Warning -Message "The script supports Windows 10 x64 only"
}
break
}
Default {}
}
# Detect the PowerShell bitness
# Определить разрядность PowerShell
switch ([IntPtr]::Size -eq 8)
{
$false
{
if ($RU)
{
Write-Warning -Message "Скрипт поддерживает только PowerShell x64"
}
else
{
Write-Warning -Message "The script supports PowerShell x64 only"
}
break
}
Default {}
}
# Detect whether the script is running via PowerShell ISE
# Определить, запущен ли скрипт в PowerShell ISE
if ($psISE)
{
if ($RU)
{
Write-Warning -Message "Скрипт не может быть запущен в PowerShell ISE"
}
else
{
Write-Warning -Message "The script can not be run via PowerShell ISE"
}
break
}
#endregion Check
#region Begin
Set-StrictMode -Version Latest
# Сlear $Error variable
# Очистка переменной $Error
$Error.Clear()
# Set the encoding to UTF-8 without BOM for the PowerShell session
# Установить кодировку UTF-8 без BOM для текущей сессии PowerShell
if ($RU)
{
ping.exe | Out-Null
$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8
}
# Create a restore point
# Создать точку восстановления
if ($RU)
{
$Title = "Точка восстановления"
$Message = "Чтобы создайте точку восстановления, введите необходимую букву"
$Options = "&Создать", "&Не создавать", "&Пропустить"
}
else
{
$Title = "Restore point"
$Message = "To create a restore point enter the required letter"
$Options = "&Create", "&Do not create", "&Skip"
}
$DefaultChoice = 2
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
switch ($Result)
{
"0"
{
if (-not (Get-ComputerRestorePoint))
{
Enable-ComputerRestore -Drive $env:SystemDrive
}
# Set system restore point creation frequency to 5 minutes
# Установить частоту создания точек восстановления на 5 минут
New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 5 -Force
# Descriptive name format for the restore point: <Month>.<date>.<year> <time>
# Формат описания точки восстановления: <дата>.<месяц>.<год> <время>
$CheckpointDescription = Get-Date -Format "dd.MM.yyyy HH:mm"
Checkpoint-Computer -Description $CheckpointDescription -RestorePointType MODIFY_SETTINGS
New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name SystemRestorePointCreationFrequency -PropertyType DWord -Value 1440 -Force
}
"1"
{
if ($RU)
{
$Title = "Точки восстановления"
$Message = "Чтобы удалить все точки восстановления, введите необходимую букву"
$Options = "&Удалить", "&Пропустить"
}
else
{
$Title = "Restore point"
$Message = "To remove all restore points enter the required letter"
$Options = "&Delete", "&Skip"
}
$DefaultChoice = 1
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
switch ($Result)
{
"0"
{
# Delete all restore points
# Удалить все точки восстановения
Get-CimInstance -ClassName Win32_ShadowCopy | Remove-CimInstance
}
"1"
{
if ($RU)
{
Write-Verbose -Message "Пропущено" -Verbose
}
else
{
Write-Verbose -Message "Skipped" -Verbose
}
}
}
}
"2"
{
if ($RU)
{
Write-Verbose -Message "Пропущено" -Verbose
}
else
{
Write-Verbose -Message "Skipped" -Verbose
}
}
}
#endregion Begin
#region Privacy & Telemetry
# Turn off "Diagnostics Tracking Service"
# Отключить службу "Diagnostics Tracking Service"
Get-Service -ServiceName DiagTrack | Stop-Service
Get-Service -ServiceName DiagTrack | Set-Service -StartupType Disabled
# Turn off Windows Error Reporting
# Отключить отчеты об ошибках Windows
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Windows Error Reporting" -Name Disabled -PropertyType DWord -Value 1 -Force
# Change Windows Feedback frequency to "Never"
# Изменить частоту формирования отзывов на "Никогда"
if (-not (Test-Path -Path HKCU:\Software\Microsoft\Siuf\Rules))
{
New-Item -Path HKCU:\Software\Microsoft\Siuf\Rules -Force
}
New-ItemProperty -Path HKCU:\Software\Microsoft\Siuf\Rules -Name NumberOfSIUFInPeriod -PropertyType DWord -Value 0 -Force
# Turn off diagnostics tracking scheduled tasks
# Отключить задачи диагностического отслеживания
$tasks = @(
# Aggregates and uploads Application Telemetry information if opted-in to the Microsoft Customer Experience Improvement Program
# Сбор и передача данных дистанционного отслеживания приложений
"AitAgent"
# The Bluetooth CEIP (Customer Experience Improvement Program) task collects Bluetooth related statistics and information about your machine and sends it to Microsoft
# Задача программы улучшения качества Bluetooth собирает статистику по Bluetooth, а также сведения о вашем компьютере, и отправляет их в корпорацию Майкрософт
"BthSQM"
# If the user has consented to participate in the Windows Customer Experience Improvement Program, this job collects and sends usage data to Microsoft
# Если пользователь изъявил желание участвовать в программе по улучшению качества программного обеспечения Windows, эта задача будет собирать и отправлять сведения о работе программного обеспечения в Майкрософт
"Consolidator"
# Initializes Family Safety monitoring and enforcement
# Инициализация контроля и применения правил семейной безопасности
"FamilySafetyMonitor"
# Synchronizes the latest settings with the Microsoft family features service
# Синхронизирует последние параметры со службой функций семьи учетных записей Майкрософт
"FamilySafetyRefresh"
# Protects user files from accidental loss by copying them to a backup location when the system is unattended
# Защищает файлы пользователя от случайной потери за счет их копирования в резервное расположение, когда система находится в автоматическом режиме
"File History (maintenance mode)"
# The Kernel CEIP (Customer Experience Improvement Program) task collects additional information about the system and sends this data to Microsoft
# Осуществляется сбор дополнительных данных о системе, которые затем передаются в корпорацию Майкрософт
"KernelCeipTask"
# Collects program telemetry information if opted-in to the Microsoft Customer Experience Improvement Program.
# Собирает телеметрические данные программы при участии в Программе улучшения качества программного обеспечения Майкрософт
"Microsoft Compatibility Appraiser"
# The Windows Disk Diagnostic reports general disk and system information to Microsoft for users participating in the Customer Experience Program
# Для пользователей, участвующих в программе контроля качества программного обеспечения, служба диагностики дисков Windows предоставляет общие сведения о дисках и системе в корпорацию Майкрософт
"Microsoft-Windows-DiskDiagnosticDataCollector"
"NetworkStateChangeTask"
# Collects program telemetry information if opted-in to the Microsoft Customer Experience Improvement Program
# Сбор телеметрических данных программы при участии в программе улучшения качества ПО
"ProgramDataUpdater"
# This task collects and uploads autochk SQM data if opted-in to the Microsoft Customer Experience Improvement Program
# Эта задача собирает и загружает данные SQM при участии в программе улучшения качества программного обеспечения
"Proxy"
# Windows Error Reporting task to process queued reports
# Задача отчетов об ошибках обрабатывает очередь отчетов
"QueueReporting"
# Task that collects data for SmartScreen in Windows
# Задача, выполняющая сбор данных для SmartScreen в Windows
"SmartScreenSpecific"
# The USB CEIP (Customer Experience Improvement Program) task collects Universal Serial Bus related statistics and information about your machine
# При выполнении задачи программы улучшения качества ПО шины USB (USB CEIP) осуществляется сбор статистических данных об использовании универсальной последовательной шины USB и сведений о компьютере
"UsbCeip"
# Measures a system's performance and capabilities
# Измеряет быстродействие и возможности системы
"WinSAT"
)
Get-ScheduledTask -TaskName $tasks | Disable-ScheduledTask
# This idle task reorganizes the cache files used to display the start menu
# Эта задача периода бездействия реорганизует файлы кэша, используемые для отображения меню "Пуск"
Unregister-ScheduledTask -TaskName "Optimize Start Menu*" -Confirm:$false
#endregion Privacy & Telemetry
#region UI & Personalization
# Show "This PC" on Desktop
# Отобразить "Этот компьютер" на рабочем столе
if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel))
{
New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Force
}
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -PropertyType DWord -Value 0 -Force
# Do not use check boxes to select items
# Не использовать флажки для выбора элементов
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name AutoCheckSelect -PropertyType DWord -Value 0 -Force
# Show hidden files, folders, and drives
# Показывать скрытые файлы, папки и диски
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name Hidden -PropertyType DWord -Value 1 -Force
# Show more details in file transfer dialog
# Развернуть диалог переноса файлов
if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager))
{
New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager -Force
}
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager -Name EnthusiastMode -PropertyType DWord -Value 1 -Force
# Show file name extensions
# Показывать расширения для зарегистрированных типов файлов
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideFileExt -PropertyType DWord -Value 0 -Force
# Do not hide folder merge conflicts
# Не скрывать конфликт слияния папок
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideMergeConflicts -PropertyType DWord -Value 0 -Force
# Open File Explorer to: "This PC"
# Открывать проводник для: "Этот компьютер"
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name LaunchTo -PropertyType DWord -Value 1 -Force
# Do not show all folders in the navigation pane
# Не отображать все папки в области навигации
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name NavPaneShowAllFolders -PropertyType DWord -Value 0 -Force
# Show the Ribbon expanded in File Explorer
# Отображать ленту проводника в развернутом виде
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Ribbon -Name MinimizedStateTabletModeOff -PropertyType DWord -Value 0 -Force
<#
Display recycle bin files delete confirmation
Function [WinAPI.UpdateExplorer]::PostMessage() call required at the end
Запрашивать подтверждение на удаление файлов в корзину
В конце необходим вызов функции [WinAPI.UpdateExplorer]::PostMessage()
#>
$ShellState = Get-ItemPropertyValue -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState
$ShellState[4] = 51
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name ShellState -PropertyType Binary -Value $ShellState -Force
# Always show all icons in the notification area
# Всегда отображать все значки в области уведомлений
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name EnableAutoTray -PropertyType DWord -Value 0 -Force
# Unpin Microsoft Internet Explorer from taskbar
# Открепить Microsoft Internet Explorer от панели задач
$Signature = @{
Namespace = "WinAPI"
Name = "GetStr"
Language = "CSharp"
MemberDefinition = @"
// https://github.com/Disassembler0/Win10-Initial-Setup-Script/issues/8#issue-227159084
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
public static string GetString(uint strId)
{
IntPtr intPtr = GetModuleHandle("shell32.dll");
StringBuilder sb = new StringBuilder(255);
LoadString(intPtr, strId, sb, sb.Capacity);
return sb.ToString();
}
"@
}
if (-not ("WinAPI.GetStr" -as [type]))
{
Add-Type @Signature -Using System.Text
}
# Extract the "Unpin from taskbar" string from shell32.dll
# Извлечь строку "Открепить от панели задач" из shell32.dll
$unpin = [WinAPI.GetStr]::GetString(5387)
$apps = (New-Object -ComObject Shell.Application).NameSpace("shell:::{4234d49b-0245-4df3-b780-3893943456e1}").Items()
$apps | Where-Object -FilterScript {$_.Path -eq "Microsoft.InternetExplorer.Default"} | ForEach-Object -Process {$_.Verbs() | Where-Object -FilterScript {$_.Name -eq $unpin} | ForEach-Object -Process {$_.DoIt()}}
# Unpin the Microsoft Store shortcut from taskbar
# Открепить ярлык Магазина от панели задач
if (-not (Test-Path -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer))
{
New-Item -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer -Force
}
New-ItemProperty -Path HKCU:\Software\Policies\Microsoft\Windows\Explorer -Name NoPinningStoreToTaskbar -PropertyType DWord -Value 1 -Force
# Set the large icons in the Control Panel
# Установить крупные значки в Панели управления
if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel))
{
New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel -Force
}
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel -Name AllItemsIconView -PropertyType DWord -Value 0 -Force
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel -Name StartupPage -PropertyType DWord -Value 1 -Force
# Do not show "New App Installed" notification
# Не показывать уведомление "Установлено новое приложение"
if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer))
{
New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Force
}
New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Explorer -Name NoNewAppAlert -PropertyType DWord -Value 1 -Force
# Turn off JPEG desktop wallpaper import quality reduction
# Отключить снижение качества при импорте фонового изображение рабочего стола в формате JPEG
New-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name JPEGImportQuality -PropertyType DWord -Value 100 -Force
# Expand Task manager window
# Раскрыть окно Диспетчера задач
$taskmgr = Get-Process -Name Taskmgr -ErrorAction Ignore
if ($taskmgr)
{
$taskmgr.CloseMainWindow()
}
Start-Process -FilePath Taskmgr
Start-Sleep -Seconds 1
$taskmgr = Get-Process -Name Taskmgr -ErrorAction Ignore
if ($taskmgr)
{
$taskmgr.CloseMainWindow()
}
do
{
Start-Sleep -Milliseconds 100
$preferences = Get-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -ErrorAction Ignore
}
until ($preferences)
$preferences.Preferences[28] = 0
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\TaskManager -Name Preferences -PropertyType Binary -Value $preferences.Preferences -Force
# Do not add the "- Shortcut" for created shortcuts
# Нe дoбaвлять "- яpлык" для coздaвaeмыx яpлыкoв
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer -Name link -PropertyType Binary -Value ([byte[]](00,00,00,00)) -Force
# Do not display lockscreen
# Не отображать экран блокировки
if (-not (Test-Path -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization))
{
New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization -Force
}
New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization -Name NoLockScreen -PropertyType DWord -Value 1 -Force
#endregion UI & Personalization
#region System
# Turn off hibernate if device is not a laptop
# Отключить режим гибернации, если устройство не является ноутбуком
if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2)
{
POWERCFG /HIBERNATE OFF
}
# Change %TEMP% environment variable path to the %SystemDrive%\Temp
# Изменить путь переменной среды для %TEMP% на %SystemDrive%\Temp
if (-not (Test-Path -Path $env:SystemDrive\Temp))
{
New-Item -Path $env:SystemDrive\Temp -ItemType Directory -Force
}
[Environment]::SetEnvironmentVariable("TMP", "$env:SystemDrive\Temp", "User")
[Environment]::SetEnvironmentVariable("TMP", "$env:SystemDrive\Temp", "Machine")
[Environment]::SetEnvironmentVariable("TMP", "$env:SystemDrive\Temp", "Process")
New-ItemProperty -Path HKCU:\Environment -Name TMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force
[Environment]::SetEnvironmentVariable("TEMP", "$env:SystemDrive\Temp", "User")
[Environment]::SetEnvironmentVariable("TEMP", "$env:SystemDrive\Temp", "Machine")
[Environment]::SetEnvironmentVariable("TEMP", "$env:SystemDrive\Temp", "Process")
New-ItemProperty -Path HKCU:\Environment -Name TEMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name TEMP -PropertyType ExpandString -Value %SystemDrive%\Temp -Force
# Spooler restart
# Перезапуск Диспетчер печати
Restart-Service -Name Spooler -Force
Remove-Item -Path $env:SystemRoot\Temp -Recurse -Force -ErrorAction Ignore
Remove-Item -Path $env:LOCALAPPDATA\Temp -Recurse -Force -ErrorAction Ignore
# Turn on Win32 long paths
# Включить длинные пути Win32
New-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -PropertyType DWord -Value 1 -Force
# Display the Stop error information on the BSoD
# Отображать Stop-ошибку при появлении BSoD
New-ItemProperty -Path HKLM:\System\CurrentControlSet\Control\CrashControl -Name DisplayParameters -PropertyType DWord -Value 1 -Force
# Do not preserve zone information in file attachments
# Не хранить сведения о зоне происхождения вложенных файлов
if (-not (Test-Path -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Attachments))
{
New-Item -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Attachments -Force
}
New-ItemProperty -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Attachments -Name SaveZoneInformation -PropertyType DWord -Value 1 -Force
# Turn off Admin Approval Mode for administrators
# Отключить использование режима одобрения администратором для встроенной учетной записи администратора
New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -PropertyType DWord -Value 0 -Force
# Turn on access to mapped drives from app running with elevated permissions with Admin Approval Mode enabled
# Включить доступ к сетевым дискам при включенном режиме одобрения администратором при доступе из программ, запущенных с повышенными правами
New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLinkedConnections -PropertyType DWord -Value 1 -Force
# Always wait for the network at computer startup and logon
# Всегда ждать сеть при запуске и входе в систему
if (-not (Test-Path -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon"))
{
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon" -Force
}
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name SyncForegroundPolicy -PropertyType DWord -Value 1 -Force
# Turn off Windows features
# Отключить компоненты Windows
$WindowsOptionalFeatures = @(
# Windows Fax and Scan
# Факсы и сканирование
"FaxServicesClientPackage"
# Legacy Components
# Компоненты прежних версий
"LegacyComponents"
# Media Features
# Компоненты работы с мультимедиа
"MediaPlayback"
# PowerShell 2.0
"MicrosoftWindowsPowerShellV2"
"MicrosoftWindowsPowershellV2Root"
# Microsoft XPS Document Writer
# Средство записи XPS-документов (Microsoft)
"Printing-XPSServices-Features"
# Work Folders Client
# Клиент рабочих папок
"WorkFolders-Client"
# XPS Viewer
# Просмотрщик XPS
"Xps-Foundation-Xps-Viewer"
)
Disable-WindowsOptionalFeature -Online -FeatureName $WindowsOptionalFeatures -NoRestart
Write-Verbose 111 -Verbose
# Turn on updates for other Microsoft products
# Включить автоматическое обновление для других продуктов Microsoft
(New-Object -ComObject Microsoft.Update.ServiceManager).AddService2("7971f918-a847-4430-9279-4a52d1efe18d",7,"")
# Set power management scheme
# Установить схему управления питания
if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -eq 2)
{
# Balanced for laptop
# Сбалансированная для ноутбука
POWERCFG /SETACTIVE SCHEME_BALANCED
}
else
{
# High performance for desktop
# Высокая производительность для стационарного ПК
POWERCFG /SETACTIVE SCHEME_MIN
}
# Use latest installed .NET runtime for all apps
# Использовать последнюю установленную версию .NET для всех приложенийNew-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\.NETFramework -Name OnlyUseLatestCLR -PropertyType DWord -Value 1 -Force
New-ItemProperty -Path HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework -Name OnlyUseLatestCLR -PropertyType DWord -Value 1 -Force
# Do not allow the computer (if device is not a laptop) to turn off the network adapters to save power
# Запретить отключение сетевых адаптеров для экономии энергии (если устройство не является ноутбуком)
if ((Get-CimInstance -ClassName Win32_ComputerSystem).PCSystemType -ne 2)
{
$adapters = Get-NetAdapter -Physical | Get-NetAdapterPowerManagement | Where-Object -FilterScript {$_.AllowComputerToTurnOffDevice -ne "Unsupported"}
foreach ($adapter in $adapters)
{
$adapter.AllowComputerToTurnOffDevice = "Disabled"
$adapter | Set-NetAdapterPowerManagement
}
}
# Set the default input method to the English language
# Установить метод ввода по умолчанию на английский язык
Set-WinDefaultInputMethodOverride "0409:00000409"
if (-not (Test-Path -Path "HKLM:\SOFTWARE\Policies\Microsoft\Control Panel\International"))
{
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Control Panel\International" -Force
}
New-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Control Panel\International" -Name BlockUserInputMethodsForSignIn -PropertyType DWord -Value 1 -Force
New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Keyboard Layout\Preload" -Name 1 -PropertyType String -Value 00000409 -Force
New-ItemProperty -Path "Registry::HKEY_USERS\.DEFAULT\Keyboard Layout\Preload" -Name 2 -PropertyType String -Value 00000419 -Force
# Do not show user first sign-in animation
# Не показывать анимацию при первом входе в систему
New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableFirstLogonAnimation -PropertyType DWord -Value 0 -Force
# Change location of the user folders
# Изменить расположение пользовательских папок
function UserShellFolder
{
<#
.SYNOPSIS
Change location of the each user folders using SHSetKnownFolderPath function
.EXAMPLE
UserShellFolder -UserFolder Desktop -FolderPath "C:\Desktop"
.NOTES
User files or folders won't me moved to the new location
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
[string]
$UserFolder,
[Parameter(Mandatory = $true)]
[string]
$FolderPath
)
function KnownFolderPath
{
<#
.SYNOPSIS
Redirect user folders to a new location
.EXAMPLE
KnownFolderPath -KnownFolder Desktop -Path "C:\Desktop"
.NOTES
User files or folders won't me moved to the new location
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
[string]
$KnownFolder,
[Parameter(Mandatory = $true)]
[string]
$Path
)
$KnownFolders = @{
"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");
"Music" = @("4BD8D571-6D19-48D3-BE97-422220080E43", "a0c69a99-21c8-4671-8703-7934162fcf1d");
"Pictures" = @("33E28130-4E1E-4676-835A-98395C3BC3BB", "0ddd015d-b06c-45d5-8c4c-f59713854639");
"Videos" = @("18989B1D-99B5-455B-841C-AB7C74E4DDFC", "35286a68-3c57-41a1-bbb1-0eae73d76c95");
}
$Signature = @{
Namespace = "WinAPI"
Name = "KnownFolders"
Language = "CSharp"
MemberDefinition = @"
[DllImport("shell32.dll")]
public extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);
"@
}
if (-not ("WinAPI.KnownFolders" -as [type]))
{
Add-Type @Signature
}
foreach ($guid in $KnownFolders[$KnownFolder])
{
[WinAPI.KnownFolders]::SHSetKnownFolderPath([ref]$guid, 0, 0, $Path)
}
(Get-Item -Path $Path -Force).Attributes = "ReadOnly"
}
$UserShellFoldersRegName = @{
"Desktop" = "Desktop"
"Documents" = "Personal"
"Downloads" = "{374DE290-123F-4565-9164-39C4925E467B}"
"Music" = "My Music"
"Pictures" = "My Pictures"
"Videos" = "My Video"
}
$UserShellFoldersGUID = @{
"Desktop" = "{754AC886-DF64-4CBA-86B5-F7FBF4FBCEF5}"
"Documents" = "{F42EE2D3-909F-4907-8871-4C22FC0BF756}"
"Downloads" = "{7D83EE9B-2244-4E70-B1F5-5393042AF1E4}"
"Music" = "{A0C69A99-21C8-4671-8703-7934162FCF1D}"
"Pictures" = "{0DDD015D-B06C-45D5-8C4C-F59713854639}"
"Videos" = "{35286A68-3C57-41A1-BBB1-0EAE73D76C95}"
}
# Hidden desktop.ini for each type of user folders
# Скрытый desktop.ini для каждого типа пользовательских папок
$DesktopINI = @{
"Desktop" = "",
"[.ShellClassInfo]",
"LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21769",
"IconResource=%SystemRoot%\system32\imageres.dll,-183"
"Documents" = "",
"[.ShellClassInfo]",
"LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21770",
"IconResource=%SystemRoot%\system32\imageres.dll,-112",
"IconFile=%SystemRoot%\system32\shell32.dll",
"IconIndex=-235"
"Downloads" = "",
"[.ShellClassInfo]","LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21798",
"IconResource=%SystemRoot%\system32\imageres.dll,-184"
"Music" = "",
"[.ShellClassInfo]","LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21790",
"InfoTip=@%SystemRoot%\system32\shell32.dll,-12689",
"IconResource=%SystemRoot%\system32\imageres.dll,-108",
"IconFile=%SystemRoot%\system32\shell32.dll","IconIndex=-237"
"Pictures" = "",
"[.ShellClassInfo]",
"LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21779",
"InfoTip=@%SystemRoot%\system32\shell32.dll,-12688",
"IconResource=%SystemRoot%\system32\imageres.dll,-113",
"IconFile=%SystemRoot%\system32\shell32.dll",
"IconIndex=-236"
"Videos" = "",
"[.ShellClassInfo]",
"LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21791",
"InfoTip=@%SystemRoot%\system32\shell32.dll,-12690",
"IconResource=%SystemRoot%\system32\imageres.dll,-189",
"IconFile=%SystemRoot%\system32\shell32.dll","IconIndex=-238"
}
# Determining the current user folder path
# Определяем текущее значение пути пользовательской папки
$UserShellFolderRegValue = Get-ItemPropertyValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersRegName[$UserFolder]
if ($UserShellFolderRegValue -ne $FolderPath)
{
if ((Get-ChildItem -Path $UserShellFolderRegValue | Measure-Object).Count -ne 0)
{
if ($RU)
{
Write-Error -Message "В папке $UserShellFolderRegValue осталась файлы. Переместите их вручную в новое расположение" -ErrorAction SilentlyContinue
}
else
{
Write-Error -Message "Some files left in the $UserShellFolderRegValue folder. Move them manually to a new location" -ErrorAction SilentlyContinue
}
}
# Creating a new folder if there is no one
# Создаем новую папку, если таковая отсутствует
if (-not (Test-Path -Path $FolderPath))
{
New-Item -Path $FolderPath -ItemType Directory -Force
}
KnownFolderPath -KnownFolder $UserFolder -Path $FolderPath
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersGUID[$UserFolder] -PropertyType ExpandString -Value $FolderPath -Force
Set-Content -Path "$FolderPath\desktop.ini" -Value $DesktopINI[$UserFolder] -Encoding Unicode -Force
(Get-Item -Path "$FolderPath\desktop.ini" -Force).Attributes = "Hidden", "System", "Archive"
(Get-Item -Path "$FolderPath\desktop.ini" -Force).Refresh()
}
}
<#
.SYNOPSIS
The "Show menu" function using PowerShell with the up/down arrow keys and enter key to make a selection
.EXAMPLE
ShowMenu -Menu $ListOfItems -Default $DefaultChoice
.NOTES
Doesn't work in PowerShell ISE
#>
function ShowMenu
{
[CmdletBinding()]
param
(
[Parameter()]
[string]
$Title,
[Parameter(Mandatory = $true)]
[array]
$Menu,
[Parameter(Mandatory = $true)]
[int]
$Default
)
Write-Information -MessageData $Title -InformationAction Continue
$minY = [Console]::CursorTop
$y = [Math]::Max([Math]::Min($Default, $Menu.Count), 0)
do
{
[Console]::CursorTop = $minY
[Console]::CursorLeft = 0
$i = 0
foreach ($item in $Menu)
{
if ($i -ne $y)
{
Write-Information -MessageData (' {0}. {1} ' -f ($i+1), $item) -InformationAction Continue
}
else
{
Write-Information -MessageData ('[ {0}. {1} ]' -f ($i+1), $item) -InformationAction Continue
}
$i++
}
$k = [Console]::ReadKey()
switch ($k.Key)
{
"UpArrow"
{
if ($y -gt 0)
{
$y--
}
}
"DownArrow"
{
if ($y -lt ($Menu.Count - 1))
{
$y++
}
}
"Enter"
{
return $Menu[$y]
}
}
}
while ($k.Key -notin ([ConsoleKey]::Escape, [ConsoleKey]::Enter))
}
# Store all drives letters to use them within ShowMenu function
# Сохранить все буквы диска, чтобы использовать их в функции ShowMenu
if ($RU)
{
Write-Verbose "Получение дисков..." -Verbose
}
else
{
Write-Verbose "Retrieving drives..." -Verbose
}
$DriveLetters = @((Get-Disk | Where-Object -FilterScript {$_.BusType -ne "USB"} | Get-Partition | Get-Volume | Where-Object -FilterScript {($null -ne $_.DriveLetter) -and ("" -ne $_.DriveLetter)}).DriveLetter | Sort-Object)
if ($DriveLetters.Count -gt 1)
{
# If the number of disks is more than one, set the second drive in the list as default drive
# Если количество дисков больше одного, сделать второй диск в списке диском по умолчанию
$Default = 1
}
else
{
$Default = 0
}
# Desktop
# Рабочий стол
$Title = ""
if ($RU)
{
$Message = "Чтобы изменить местоположение папки `"Рабочий стол`", введите необходимую букву"
Write-Warning "`nФайлы не будут перенесены"
$Options = "&Изменить", "&Пропустить"
}
else
{
$Message = "To change the location of the Desktop folder enter the required letter"
Write-Warning "`nFiles will not be moved"
$Options = "&Change", "&Skip"
}
$DefaultChoice = 1
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
switch ($Result)
{
"0"
{
if ($RU)
{
$Title = "`nВыберите диск, в корне которого будет создана папка для `"Рабочий стол`""
}
else
{
$Title = "`nSelect the drive within the root of which the `"Desktop`" folder will be created"
}
$SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
UserShellFolder -UserFolder Desktop -FolderPath "${SelectedDrive}:\Desktop"
}
"1"
{
if ($RU)
{
Write-Verbose -Message "Пропущено" -Verbose
}
else
{
Write-Verbose -Message "Skipped" -Verbose
}
}
}
# Documents
# Документы
$Title = ""
if ($RU)
{
$Message = "Чтобы изменить местоположение папки `"Документы`", введите необходимую букву"
Write-Warning "`nФайлы не будут перенесены"
$Options = "&Изменить", "&Пропустить"
}
else
{
$Message = "To change the location of the Documents folder enter the required letter"
Write-Warning "`nFiles will not be moved"
$Options = "&Change", "&Skip"
}
$DefaultChoice = 1
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
switch ($Result)
{
"0"
{
if ($RU)
{
$Title = "`nВыберите диск, в корне которого будет создана папка для `"Документы`""
}
else
{
$Title = "`nSelect the drive within the root of which the `"Documents`" folder will be created"
}
$SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
UserShellFolder -UserFolder Documents -FolderPath "${SelectedDrive}:\Documents"
}
"1"
{
if ($RU)
{
Write-Verbose -Message "Пропущено" -Verbose
}
else
{
Write-Verbose -Message "Skipped" -Verbose
}
}
}
# Downloads
# Загрузки
$Title = ""
if ($RU)
{
$Message = "Чтобы изменить местоположение папки `"Загрузки`", введите необходимую букву"
Write-Warning "`nФайлы не будут перенесены"
$Options = "&Изменить", "&Пропустить"
}
else
{
$Message = "To change the location of the Downloads folder enter the required letter"
Write-Warning "`nFiles will not be moved"
$Options = "&Change", "&Skip"
}
$DefaultChoice = 1
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)
switch ($Result)
{
"0"
{
if ($RU)
{
$Title = "`nВыберите диск, в корне которого будет создана папка для `"Загрузки`""
}
else
{
$Title = "`nSelect the drive within the root of which the `"Downloads`" folder will be created"
}
$SelectedDrive = ShowMenu -Title $Title -Menu $DriveLetters -Default $Default
UserShellFolder -UserFolder Downloads -FolderPath "${SelectedDrive}:\Downloads"
}
"1"
{
if ($RU)
{
Write-Verbose -Message "Пропущено" -Verbose
}
else
{
Write-Verbose -Message "Skipped" -Verbose
}
}
}
# Music
# Музыка
$Title = ""
if ($RU)
{
$Message = "Чтобы изменить местоположение папки `"Музыка`", введите необходимую букву"
Write-Warning "`nФайлы не будут перенесены"
$Options = "&Изменить", "&Пропустить"
}
else
{
$Message = "To change the location of the Music folder enter the required letter"
Write-Warning "`nFiles will not be moved"
$Options = "&Change", "&Skip"
}
$DefaultChoice = 1
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, $DefaultChoice)