Skip to content

Instantly share code, notes, and snippets.

@aubique
Last active January 13, 2025 00:33
Show Gist options
  • Save aubique/871ad87ef7a801d17942ca3974cd9909 to your computer and use it in GitHub Desktop.
Save aubique/871ad87ef7a801d17942ca3974cd9909 to your computer and use it in GitHub Desktop.
WSL2 setup config files
#!/usr/bin/env -S powershell.exe -ExecutionPolicy Bypass
<#
.SYNOPSIS
Change the location of the each user folder using SHSetKnownFolderPath function
.PARAMETER RemoveDesktopINI
The RemoveDesktopINI argument removes desktop.ini in the old user shell folder
.EXAMPLE
UserShellFolder -UserFolder Desktop -FolderPath "$env:SystemDrive:\Desktop" -RemoveDesktopINI
.LINK
https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
.NOTES
User files or folders won't me moved to a new location
#>
function UserShellFolder
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateSet("Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos")]
[string]
$UserFolder,
[Parameter(Mandatory = $true)]
[string]
$FolderPath,
[Parameter(Mandatory = $false)]
[switch]
$RemoveDesktopINI
)
<#
.SYNOPSIS
Redirect user folders to a new location
.EXAMPLE
KnownFolderPath -KnownFolder Desktop -Path "$env:SystemDrive:\Desktop"
#>
function KnownFolderPath
{
[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"
}
$UserShellFoldersRegistryNames = @{
"Desktop" = "Desktop"
"Documents" = "Personal"
"Downloads" = "{374DE290-123F-4565-9164-39C4925E467B}"
"Music" = "My Music"
"Pictures" = "My Pictures"
"Videos" = "My Video"
}
$UserShellFoldersGUIDs = @{
"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}"
}
# Contents of the hidden desktop.ini file for each type of user folders
$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
$CurrentUserFolderPath = Get-ItemPropertyValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersRegistryNames[$UserFolder]
if ($CurrentUserFolder -ne $FolderPath)
{
if ((Get-ChildItem -Path $CurrentUserFolderPath | Measure-Object).Count -ne 0)
{
Write-Error -Message ($Localization.UserShellFolderNotEmpty -f $CurrentUserFolderPath) -ErrorAction SilentlyContinue
}
# Creating a new folder if there is no one
if (-not (Test-Path -Path $FolderPath))
{
New-Item -Path $FolderPath -ItemType Directory -Force
}
# Removing old desktop.ini
if ($RemoveDesktopINI.IsPresent)
{
Remove-Item -Path "$CurrentUserFolderPath\desktop.ini" -Force
}
KnownFolderPath -KnownFolder $UserFolder -Path $FolderPath
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name $UserShellFoldersGUIDs[$UserFolder] -PropertyType ExpandString -Value $FolderPath -Force
# Save desktop.ini in the UTF-16 LE encoding
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
Custom preset file for "Sophia Script for Windows 11"
Version: 6.8.0
Date: 29.12.2024
Modified: 2025-01-10 19:40
#>
#Requires -RunAsAdministrator
#Requires -Version 5.1
[CmdletBinding()]
param
(
[Parameter(Mandatory = $false)]
[string[]]
$Functions
)
Clear-Host
$Host.UI.RawUI.WindowTitle = "Sophia Script for Windows 11 v6.8.0 | Made with $([System.Char]::ConvertFromUtf32(0x1F497)) of Windows | $([System.Char]0x00A9) farag, Inestic & lowl1f3, 2014$([System.Char]0x2013)2025"
# Checking whether all files were expanded before running
$ScriptFiles = @(
"$PSScriptRoot\Localizations\en-US\Sophia.psd1",
"$PSScriptRoot\Localizations\fr-FR\Sophia.psd1",
"$PSScriptRoot\Localizations\ru-RU\Sophia.psd1",
"$PSScriptRoot\Localizations\uk-UA\Sophia.psd1",
"$PSScriptRoot\Module\Sophia.psm1",
"$PSScriptRoot\Manifest\Sophia.psd1"
)
if (($ScriptFiles | Test-Path) -contains $false)
{
Write-Information -MessageData "" -InformationAction Continue
Write-Warning -Message "There are no files in the script folder. Please, re-download the archive and follow the guide: https://github.com/farag2/Sophia-Script-for-Windows?tab=readme-ov-file#how-to-use."
Write-Information -MessageData "" -InformationAction Continue
exit
}
Remove-Module -Name Sophia -Force -ErrorAction Ignore
try
{
Import-LocalizedData -BindingVariable Global:Localization -UICulture $PSUICulture -BaseDirectory $PSScriptRoot\Localizations -FileName Sophia -ErrorAction Stop
}
catch
{
Import-LocalizedData -BindingVariable Global:Localization -UICulture en-US -BaseDirectory $PSScriptRoot\Localizations -FileName Sophia
}
# Checking whether script is the correct PowerShell version
try
{
Import-Module -Name $PSScriptRoot\Manifest\Sophia.psd1 -PassThru -Force -ErrorAction Stop
}
catch [System.InvalidOperationException]
{
Write-Warning -Message $Localization.UnsupportedPowerShell
exit
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Preset configuration starts here
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if ($Functions)
{
Invoke-Command -ScriptBlock {InitialActions}
foreach ($Function in $Functions)
{
Invoke-Expression -Command $Function
}
# The "PostActions" and "Errors" functions will be executed at the end
Invoke-Command -ScriptBlock {PostActions; Errors}
exit
}
#region Protection
InitialActions -Warning
#endregion Protection
#region Privacy & Telemetry
DiagTrackService -Disable
DiagnosticDataLevel -Minimal
ErrorReporting -Disable
FeedbackFrequency -Never
ScheduledTasks -Disable
SigninInfo -Disable
LanguageListAccess -Disable
AdvertisingID -Disable
WindowsWelcomeExperience -Hide
WindowsTips -Disable
SettingsSuggestedContent -Hide
AppsSilentInstalling -Disable
WhatsNewInWindows -Disable
TailoredExperiences -Disable
BingSearch -Disable
StartRecommendationsTips -Hide
StartAccountNotifications -Hide
#endregion Privacy & Telemetry
#region UI & Personalization
ThisPC -Hide
CheckBoxes -Disable
HiddenItems -Enable
FileExtensions -Show
MergeConflicts -Show
OpenFileExplorerTo -ThisPC
FileExplorerCompactMode -Disable
OneDriveFileExplorerAd -Hide
SnapAssist -Disable
FileTransferDialog -Detailed
RecycleBinDeleteConfirmation -Disable
QuickAccessRecentFiles -Hide
QuickAccessFrequentFolders -Hide
TaskbarAlignment -Center
TaskbarWidgets -Hide
TaskbarSearch -Hide
SearchHighlights -Hide
TaskViewButton -Show
SecondsInSystemClock -Hide
TaskbarCombine -Always
UnpinTaskbarShortcuts -Shortcuts Edge, Store
TaskbarEndTask -Disable
ControlPanelView -LargeIcons
WindowsColorMode -Dark
AppColorMode -Dark
FirstLogonAnimation -Disable
JPEGWallpapersQuality -Max
ShortcutsSuffix -Disable
PrtScnSnippingTool -Disable
AppsLanguageSwitch -Disable
AeroShaking -Enable
Cursors -Dark
FolderGroupBy -None
NavigationPaneExpand -Disable
StartRecommendedSection -Hide
#endregion UI & Personalization
#region OneDrive
OneDrive -Uninstall
#endregion OneDrive
#region System
StorageSense -Enable
Hibernation -Disable
Win32LongPathLimit -Disable
BSoDStopError -Enable
AdminApprovalMode -Never
DeliveryOptimization -Disable
WindowsManageDefaultPrinter -Disable
WindowsFeatures -Disable
WindowsCapabilities -Uninstall
UpdateMicrosoftProducts -Enable
RestartNotification -Hide
RestartDeviceAfterUpdate -Disable
ActiveHours -Automatically
WindowsLatestUpdate -Disable
PowerPlan -Balanced
NetworkAdaptersSavePower -Disable
#InputMethod -French
Set-UserShellFolderLocation -Default
LatestInstalled.NET -Enable
WinPrtScrFolder -Default
RecommendedTroubleshooting -Default
FoldersLaunchSeparateProcess -Enable
ReservedStorage -Disable
F1HelpPage -Disable
NumLock -Disable
CapsLock -Disable
StickyShift -Disable
Autoplay -Disable
ThumbnailCacheRemoval -Enable
SaveRestartableApps -Disable
NetworkDiscovery -Disable
DefaultTerminalApp -WindowsTerminal
InstallVCRedist
InstallDotNetRuntimes -Runtimes NET8x64, NET9x64
PreventEdgeShortcutCreation -Disable
RegistryBackup -Disable
#endregion System
#region WSL
Install-WSL
#endregion WSL
#region Start menu
StartLayout -Default
StartLayout -ShowMorePins
#endregion Start menu
#region UWP apps
UninstallUWPApps -ForAllUsers
CortanaAutostart -Disable
#endregion UWP apps
#region Gaming
XboxGameBar -Disable
XboxGameTips -Disable
GPUScheduling -Disable
#endregion Gaming
#region Scheduled tasks
CleanupTask -Register
SoftwareDistributionTask -Register
TempTask -Register
#endregion Scheduled tasks
#region Microsoft Defender & Security
NetworkProtection -Enable
PUAppsDetection -Enable
DefenderSandbox -Enable
DismissSmartScreenFilter
EventViewerCustomView -Enable
PowerShellModulesLogging -Enable
PowerShellScriptsLogging -Enable
AppsSmartScreen -Disable
SaveZoneInformation -Disable
WindowsScriptHost -Enable
WindowsSandbox -Enable
DNSoverHTTPS -Enable -PrimaryDNS 1.0.0.1 -SecondaryDNS 1.1.1.1
LocalSecurityAuthority -Enable
#endregion Microsoft Defender & Security
#region Context menu
MSIExtractContext -Show
CABInstallContext -Show
EditWithClipchampContext -Hide
EditWithPhotosContext -Hide
PrintCMDContext -Hide
CompressedFolderNewContext -Hide
MultipleInvokeContext -Enable
UseStoreOpenWith -Hide
OpenWindowsTerminalContext -Hide
OpenWindowsTerminalAdminContext -Disable
#endregion Context menu
#region Update Policies
UpdateLGPEPolicies
#endregion Update Policies
PostActions
Errors
#!/usr/bin/env -S powershell.exe -ExecutionPolicy Bypass
function Add-EnvPath {
param(
[Parameter(Mandatory=$true)]
[string] $Path,
[ValidateSet('Machine', 'User', 'Session')]
[string] $Container = 'Session'
)
if ($Container -ne 'Session') {
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
$persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
if ($persistedPaths -notcontains $Path) {
$persistedPaths = $persistedPaths + $Path | where { $_ }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
}
$envPaths = $env:Path -split ';'
if ($envPaths -notcontains $Path) {
$envPaths = $envPaths + $Path | where { $_ }
$env:Path = $envPaths -join ';'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment