Script for installing WSL on Windows 10 AME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

540 lines
19 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. # https://stackoverflow.com/a/34559554/
  2. function New-TemporaryDirectory {
  3. $parent = [System.IO.Path]::GetTempPath()
  4. $name = [System.IO.Path]::GetRandomFileName()
  5. New-Item -ItemType Directory -Path (Join-Path $parent $name)
  6. }
  7. Workflow Install-WSL {
  8. [CmdletBinding(DefaultParameterSetName='Installation')]
  9. param(
  10. [Parameter(Mandatory=$True,ParameterSetName='Installation',Position=0)]
  11. [ValidateSet(
  12. 'wslubuntu2004',
  13. 'wslubuntu2004arm',
  14. 'wsl-ubuntu-1804',
  15. 'wsl-ubuntu-1804-arm',
  16. 'wsl-ubuntu-1604',
  17. 'wsl-debian-gnulinux',
  18. 'wsl-kali-linux-new',
  19. 'wsl-opensuse-42',
  20. 'wsl-sles-12'
  21. )]
  22. [string]$LinuxDistribution,
  23. [Parameter(Mandatory=$False,ParameterSetName='Installation')]
  24. [switch]$FeatureInstalled,
  25. [Parameter(Mandatory=$False,ParameterSetName='Installation')]
  26. [switch]$OmitWindowsTerminal,
  27. [Parameter(Mandatory=$True,ParameterSetName='Cancelation')]
  28. [switch]$Cancel,
  29. [Parameter(Mandatory=$False,ParameterSetName='WindowsTerminal')]
  30. [switch]$InstallWindowsTerminal
  31. )
  32. # The task scheduler is unreliable in AME
  33. $ShortcutPath = Join-Path $env:AppData 'Microsoft\Windows\Start Menu\Programs\Startup\Install WSL.lnk'
  34. if ($Cancel) {
  35. $Removed = Remove-Item -LiteralPath $ShortcutPath -ErrorAction SilentlyContinue
  36. $Removed = Get-Job -Command 'Install-WSL' | Where-Object {$_.State -eq 'Suspended'} | Remove-Job -Force
  37. Write-Information 'All pending WSL installations have been canceled.'
  38. return 'done'
  39. } elseif ($InstallWindowsTerminal) {
  40. InlineScript {
  41. $ExecutionPolicy = Get-ExecutionPolicy -Scope Process
  42. Set-ExecutionPolicy RemoteSigned -Scope Process
  43. Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
  44. Set-ExecutionPolicy $ExecutionPolicy -Scope Process
  45. scoop bucket add extras
  46. scoop install windows-terminal
  47. }
  48. return 'done'
  49. }
  50. # establish directory for WSL installations
  51. $AppDataFolder = Join-Path $env:LocalAppData 'WSL'
  52. $DistrosFolder = New-Item -ItemType Directory -Force -Path $AppDataFolder
  53. $DistroFolder = Join-Path $DistrosFolder $LinuxDistribution
  54. if (Test-Path -Path $DistroFolder -PathType Container) {
  55. return Write-Error 'Cannot install a distro twice! This will waste your internet data. Uninstall the existing version first.' -Category ResourceExists
  56. }
  57. Write-Information 'Creating startup item'
  58. InlineScript {
  59. $shell = New-Object -ComObject ('WScript.Shell')
  60. $shortcut = $shell.CreateShortcut($Using:ShortcutPath)
  61. $shortcut.TargetPath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
  62. $shortcut.Arguments = "-WindowStyle Normal -NoLogo -NoProfile -Command `"& { Write-Output \`"Resuming installation...\`"; Get-Job -Command `'Install-WSL`' | Resume-Job | Receive-Job -Wait -InformationAction Continue; pause; exit }`""
  63. $shortcut.Save()
  64. }
  65. Write-Information ''
  66. Write-Information 'There will be a "Windows PowerShell" shortcut in your startup items until this'
  67. Write-Information 'script is complete. Please do not be alarmed, it will remove itself once the'
  68. Write-Information 'installation is complete.'
  69. Write-Information ''
  70. Write-Information 'Ensuring required features are enabled...'
  71. # using a named pipe to communicate between elevated process and not elevated one
  72. if ($FeatureInstalled) {
  73. $RestartNeeded = $False
  74. } else {
  75. try {
  76. # For various reasons this needs to be duplicated twice.
  77. # I hate it as much as you, but for some reason I can't put it in a function
  78. # It just refuses to work when I try to call it in the loop below
  79. $RestartNeeded = InlineScript {
  80. $PipeName = -join (((48..57)+(65..90)+(97..122)) * 80 |Get-Random -Count 12 |%{[char]$_})
  81. $Enabled = Start-Process powershell -ArgumentList "`
  82. `$Enabled = Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart -WarningAction SilentlyContinue`
  83. `$RestartNeeded = `$Enabled.RestartNeeded`
  84. `
  85. `$pipe = New-Object System.IO.Pipes.NamedPipeServerStream `'$PipeName`',`'Out`'`
  86. `$pipe.WaitForConnection()`
  87. `$sw = New-Object System.IO.StreamWriter `$pipe`
  88. `$sw.AutoFlush = `$True`
  89. `$sw.WriteLine([string]`$RestartNeeded)`
  90. `$sw.Dispose()`
  91. `$pipe.Dispose()`
  92. " -Verb RunAs -WindowStyle Hidden -ErrorAction Stop
  93. $pipe = New-Object System.IO.Pipes.NamedPipeClientStream '.',$Using:PipeName,'In'
  94. $pipe.Connect()
  95. $sr = New-Object System.IO.StreamReader $pipe
  96. $data = $sr.ReadLine()
  97. $sr.Dispose()
  98. $pipe.Dispose()
  99. $data -eq [string]$True
  100. } -ErrorAction Stop
  101. } catch {
  102. return Write-Error 'Please accept the UAC prompt so that the WSL feature can be installed, or specify the -FeatureInstalled flag to skip'
  103. }
  104. }
  105. if ($RestartNeeded) {
  106. # TODO detect if we're already waiting for a reboot specifically
  107. # Maybe this can be done by checking for the scheduled task instead?
  108. # This feels messy which is why it's disabled, and it would also detect
  109. # the currently running task
  110. # Future Logan from the future!: I think the shortcut is more easily
  111. # detected, but there are reasons you might want to run this more than
  112. # once in a row. For example if you are installing multiple distros
  113. # Should work okay...
  114. Write-Information 'Restart your computer in 30 seconds or it will explode'
  115. 'restart-needed'
  116. Suspend-Workflow
  117. # Wait for a logon where the feature is installed. This will be after at
  118. # least 1 reboot, but for various reasons (grumble grumble...) it might
  119. # be later. Every Suspend-Workflow is virtually guaranteed to be resumed
  120. # by a logon, or a manual resume (which is harmless in this case).
  121. $waiting = $True
  122. while ($waiting) {
  123. if ($FeatureInstalled) {
  124. $RestartNeeded = $False
  125. } else {
  126. try {
  127. $RestartNeeded = InlineScript {
  128. $PipeName = -join (((48..57)+(65..90)+(97..122)) * 80 |Get-Random -Count 12 |%{[char]$_})
  129. $Enabled = Start-Process powershell -ArgumentList "`
  130. `$Enabled = Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart -WarningAction SilentlyContinue`
  131. `$RestartNeeded = `$Enabled.RestartNeeded`
  132. `
  133. `$pipe = New-Object System.IO.Pipes.NamedPipeServerStream `'$PipeName`',`'Out`'`
  134. `$pipe.WaitForConnection()`
  135. `$sw = New-Object System.IO.StreamWriter `$pipe`
  136. `$sw.AutoFlush = `$True`
  137. `$sw.WriteLine([string]`$RestartNeeded)`
  138. `$sw.Dispose()`
  139. `$pipe.Dispose()`
  140. " -Verb RunAs -WindowStyle Hidden -ErrorAction Stop
  141. $pipe = New-Object System.IO.Pipes.NamedPipeClientStream '.',$Using:PipeName,'In'
  142. $pipe.Connect()
  143. $sr = New-Object System.IO.StreamReader $pipe
  144. $data = $sr.ReadLine()
  145. $sr.Dispose()
  146. $pipe.Dispose()
  147. $data -eq [string]$True
  148. } -ErrorAction Stop
  149. } catch {
  150. # I decided that this is not always true and it would be
  151. # rude to assume that. So I give the user a choice and allow
  152. # them to continue without UAC
  153. ## The user accepted the UAC prompt the first time, so they
  154. ## can do it again. They cannot specify the -FeatureInstalled
  155. ## flag at this point, unfortunately.
  156. #Write-Output 'Please accept the UAC prompt to continue installation.'
  157. # Try to get input from the user as a fallback
  158. $response = InlineScript {
  159. [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
  160. [System.Windows.Forms.Messagebox]::Show("Admin access is required to check the status of the WSL feature. If you can no longer grant admin access via UAC:`n`nIs the WSL feature installed and enabled?", 'WSL Installer', [System.Windows.Forms.MessageBoxButtons]::YesNo)
  161. }
  162. $RestartNeeded = $response -eq 7 # 7 is DialogResult.No
  163. }
  164. }
  165. if ($RestartNeeded) {
  166. Write-Information 'Looks like the WSL component is still not installed.'
  167. 'still-waiting'
  168. Suspend-Workflow
  169. } else {
  170. $waiting = $False
  171. }
  172. }
  173. }
  174. $retrying = $True
  175. while ($retrying) {
  176. $tempFile = InlineScript { New-TemporaryFile }
  177. Remove-Item -LiteralPath $tempFile
  178. $tempFile = $tempFile.FullName -replace '$','.zip'
  179. try {
  180. Write-Information ''
  181. Write-Information "Attempting to download distribution to $tempFile..."
  182. $data = InlineScript {
  183. $PipeName = -join (((48..57)+(65..90)+(97..122)) * 80 |Get-Random -Count 12 |%{[char]$_})
  184. Start-Process powershell -ArgumentList "`
  185. Try {`
  186. Invoke-WebRequest -Uri `"https://aka.ms/$Using:LinuxDistribution`" -OutFile `"$Using:tempFile`" -ErrorAction Stop -UseBasicParsing`
  187. `$Result = 'Success'`
  188. } Catch {`
  189. `$Result = `"Failed to download file: `$(`$PSItem.Message)`"`
  190. }`
  191. `
  192. `$pipe = New-Object System.IO.Pipes.NamedPipeServerStream `'$PipeName`',`'Out`'`
  193. `$pipe.WaitForConnection()`
  194. `$sw = New-Object System.IO.StreamWriter `$pipe`
  195. `$sw.AutoFlush = `$True`
  196. `$sw.WriteLine([string]`$Result)`
  197. `$sw.Dispose()`
  198. `$pipe.Dispose()`
  199. " -WindowStyle Hidden -ErrorAction Stop
  200. $pipe = New-Object System.IO.Pipes.NamedPipeClientStream '.',$PipeName,'In'
  201. $pipe.Connect()
  202. $sr = New-Object System.IO.StreamReader $pipe
  203. $data = $sr.ReadLine()
  204. $sr.Dispose()
  205. $pipe.Dispose()
  206. $data
  207. } -ErrorAction Stop
  208. if ($data -ne 'Success') {
  209. Write-Error $data -ErrorAction Stop
  210. }
  211. $retrying = $False
  212. Write-Information 'Done!'
  213. } catch {
  214. Remove-Item -LiteralPath $tempFile -ErrorAction SilentlyContinue
  215. # PSItem is contextual and can't be read from the InlineScript
  216. $theError = $PSItem.Message
  217. Write-Information "Error: $theError"
  218. $response = InlineScript {
  219. [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
  220. [System.Windows.Forms.Messagebox]::Show("The WSL package '$Using:LinuxDistribution' could not be downloaded from Microsoft's servers.`n`nError: $Using:theError`n`nYou may abort the install, and restart it at any time using the wizard. Clicking Ignore will cause a retry the next time you log in.", 'Could not download WSL package', [System.Windows.Forms.MessageBoxButtons]::AbortRetryIgnore)
  221. }
  222. if ($response -eq 3) { # Abort
  223. Write-Information 'Aborting'
  224. $retrying = $False
  225. Write-Information 'Removing startup item...'
  226. Remove-Item -LiteralPath $ShortcutPath -ErrorAction SilentlyContinue
  227. return 'aborted'
  228. } elseif ($response -eq 5) { # Ignore
  229. Write-Information 'Ignoring'
  230. 'still-waiting'
  231. Suspend-Workflow # Wait for next logon
  232. }
  233. Write-Information 'Retrying'
  234. # If retry just loop again /shrug
  235. }
  236. }
  237. Write-Information 'Removing startup item...'
  238. Remove-Item -LiteralPath $ShortcutPath -ErrorAction SilentlyContinue
  239. $tempDir = New-TemporaryDirectory
  240. Expand-Archive -LiteralPath $tempFile -DestinationPath $tempDir -ErrorAction Stop
  241. Remove-Item -LiteralPath $tempFile -ErrorAction SilentlyContinue
  242. Write-Information 'Distribution bundle extracted'
  243. $theDir = $tempDir
  244. $Executable = Get-ChildItem $tempDir | Where-Object {$_.Name -match '.exe$'} | Select-Object -First 1
  245. if ($Executable -eq $null) {
  246. $Package = Get-ChildItem $tempDir | Where-Object {$_.Name -match '_x64.appx$'} | Select-Object -First 1
  247. if ($Package -eq $null) {
  248. return Write-Error 'Could not find the package containing the installer :(' -Category NotImplemented
  249. }
  250. $Package = Rename-Item -LiteralPath ($Package.FullName) -NewName ($Package.Name -replace '.appx$','.zip') -PassThru
  251. Write-Information "Distribution package: $($Package.Name)"
  252. $InnerPackageTemp = New-TemporaryDirectory
  253. Expand-Archive -LiteralPath $Package -DestinationPath $InnerPackageTemp
  254. Remove-Item -LiteralPath $tempDir -Recurse
  255. $Executable = Get-ChildItem $InnerPackageTemp | Where-Object {$_.Name -match '.exe$'} | Select-Object -First 1
  256. $theDir = $InnerPackageTemp
  257. if ($Executable -eq $null) {
  258. return Write-Error 'Could not find an executable inside the x64 package :(' -Category NotImplemented
  259. }
  260. } else {
  261. Write-Information 'Root package contains the installer'
  262. }
  263. # this is going to have to stick around forever if the wsl install is going to stay intact
  264. $theDir = Move-Item -LiteralPath $theDir -Destination $DistroFolder -PassThru
  265. $Executable = Get-ChildItem $theDir | Where-Object {$_.Name -match '.exe$'} | Select-Object -First 1
  266. Write-Information "Executing installer: $($Executable.Name)"
  267. InlineScript { wsl --set-default-version 1 }
  268. Start-Process -FilePath ($Executable.FullName) -Wait
  269. if (!$OmitWindowsTerminal) {
  270. Write-Information 'Installing Windows Terminal...'
  271. InlineScript {
  272. $ExecutionPolicy = Get-ExecutionPolicy -Scope Process
  273. Set-ExecutionPolicy RemoteSigned -Scope Process
  274. Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
  275. Set-ExecutionPolicy $ExecutionPolicy -Scope Process
  276. scoop bucket add extras
  277. scoop install windows-terminal
  278. }
  279. }
  280. Write-Information 'Everything should be in order now. Enjoy!'
  281. # We done
  282. return 'done'
  283. }
  284. function Install-WSLInteractive {
  285. $Distros = @(
  286. [PSCustomObject]@{Slug = 'wslubuntu2004'; Name = 'Ubuntu 20.04'; Arch = 'x64'}
  287. [PSCustomObject]@{Slug = 'wsl-ubuntu-1804'; Name = 'Ubuntu 18.04'; Arch = 'x64'}
  288. [PSCustomObject]@{Slug = 'wsl-ubuntu-1604'; Name = 'Ubuntu 16.04'; Arch = 'x64'}
  289. [PSCustomObject]@{Slug = 'wsl-debian-gnulinux'; Name = 'Debian Stable'; Arch = 'x64'}
  290. [PSCustomObject]@{Slug = 'wsl-kali-linux-new'; Name = 'Kali Linux'; Arch = 'x64'}
  291. [PSCustomObject]@{Slug = 'wsl-opensuse-42'; Name = 'OpenSUSE 4.2'; Arch = 'x64'}
  292. [PSCustomObject]@{Slug = 'wsl-sles-12'; Name = 'SLES 12'; Arch = 'x64'}
  293. )
  294. $Menu = 'main'
  295. if ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544') {
  296. $Menu = 'admin'
  297. }
  298. while ($Menu -ne 'exit') {
  299. Clear-Host
  300. # 80 chars: ' '
  301. Write-Host ' :: WSL INSTALL SCRIPT FOR WINDOWS 10 AME'
  302. Write-Host ''
  303. Write-Host ' This script will help you install Windows Subsystem for Linux on your'
  304. Write-Host ' ameliorated installation of Windows 10'
  305. Write-Host ''
  306. Write-Host ' :: NOTE: Tested on Windows 10 1909, and Windows 10 AME 20H2'
  307. switch ($menu) {
  308. 'main' {
  309. Write-Host ''
  310. Write-Host ' :: Please enter a number from 1-3 to select an option from the list below'
  311. Write-Host ''
  312. Write-Host ' 1) Install a new WSL distro'
  313. Write-Host ' 2) Cancel a pending WSL installation'
  314. Write-Host ' 3) Exit'
  315. Write-Host ''
  316. Write-Host ' >> ' -NoNewLine
  317. $Input = $Host.UI.ReadLine()
  318. switch ($Input) {
  319. '1' {
  320. $Menu = 'select-distro'
  321. }
  322. '2' {
  323. $Menu = 'cancel'
  324. }
  325. '3' {
  326. $Menu = 'exit'
  327. }
  328. default {
  329. Write-Host ''
  330. Write-Host ' !! Invalid option selected' -ForegroundColor red
  331. Write-Host ''
  332. Write-Host ' Press enter to continue...' -NoNewLine
  333. $Host.UI.ReadLine()
  334. }
  335. }
  336. }
  337. 'select-distro' {
  338. Write-Host ''
  339. Write-Host ' :: Please enter a number from the list to select a distro to install'
  340. Write-Host ''
  341. $Max = 1
  342. $Distros | ForEach-Object {
  343. Add-Member -InputObject $_ -NotePropertyName Option -NotePropertyValue ([string]$Max) -Force
  344. Write-Host " $Max) $($_.Name)"
  345. $Max += 1
  346. }
  347. Write-Host " $Max) Return to main menu"
  348. Write-Host ''
  349. Write-Host ' >> ' -NoNewLine
  350. $Input = $Host.UI.ReadLine()
  351. if ($Input -eq ([string]$Max)) {
  352. $Menu = 'main'
  353. } else {
  354. $Distro = $Distros | Where-Object -Property Option -eq -Value $Input
  355. if ($Distro -eq $null) {
  356. Write-Host ''
  357. Write-Host ' !! Invalid option selected' -ForegroundColor Red
  358. Write-Host ''
  359. Write-Host ' Press enter to continue...' -NoNewLine
  360. $Host.UI.ReadLine()
  361. } else {
  362. $Menu = 'install-distro-confirm'
  363. }
  364. }
  365. }
  366. 'install-distro-confirm' {
  367. Write-Host ''
  368. Write-Host " :: WARNING: Are you sure you want to install $($Distro.Name)? (yes/no) " -NoNewLine
  369. $Input = $Host.UI.ReadLine()
  370. switch ($Input) {
  371. 'yes' {
  372. $Menu = 'install-distro'
  373. }
  374. 'no' {
  375. $Menu = 'select-distro'
  376. }
  377. default {
  378. Write-Host ''
  379. Write-Host ' !! Invalid input' -ForegroundColor Red
  380. Write-Host ''
  381. Write-Host ' Press enter to continue...' -NoNewLine
  382. $Host.UI.ReadLine()
  383. $Menu = 'select-distro'
  384. }
  385. }
  386. }
  387. 'install-distro' {
  388. Write-Host ''
  389. Write-Host "Installing $($Distro.Name)..."
  390. try {
  391. $Menu = ('result-' + (Install-WSL -LinuxDistribution ($Distro.Slug) -InformationAction Continue -ErrorAction Stop | Select-Object -First 1 -Wait))
  392. } catch {
  393. Write-Host ''
  394. Write-Host ' !! An error occurred during the installation' -ForegroundColor Red
  395. Write-Host " !! The error is: $PSItem" -ForegroundColor Red
  396. Write-Host ''
  397. Write-Host ' Your chosen distro could not be installed.'
  398. Write-Host ''
  399. Write-Host ' Press enter to continue...' -NoNewLine
  400. $Host.UI.ReadLine()
  401. $Menu = 'select-distro'
  402. }
  403. }
  404. 'cancel' {
  405. Write-Host ''
  406. Write-Host ' :: WARNING: Are you sure you want to cancel all pending installs? (yes/no) ' -NoNewLine
  407. $Input = $Host.UI.ReadLine()
  408. switch ($Input) {
  409. 'yes' {
  410. Write-Host ''
  411. Install-WSL -Cancel
  412. }
  413. 'no' {
  414. Write-Host ''
  415. Write-Host ' Returning to main menu.'
  416. }
  417. default {
  418. Write-Host ''
  419. Write-Host ' !! Invalid input' -ForegroundColor Red
  420. }
  421. }
  422. Write-Host ''
  423. Write-Host ' Press enter to continue...' -NoNewLine
  424. $Host.UI.ReadLine()
  425. $Menu = 'main'
  426. }
  427. 'admin' {
  428. Write-Host ''
  429. Write-Host ' !! This script should NOT be run as Administrator' -ForegroundColor Red
  430. Write-Host ' !! Please close this window and run the script normally' -ForegroundColor Red
  431. Write-Host ''
  432. Write-Host ' Press enter to continue...' -NoNewLine
  433. $Host.UI.ReadLine()
  434. $Menu = 'exit'
  435. }
  436. 'result-restart-needed' {
  437. Write-Host ''
  438. Write-Host ' !! WSL installation will resume once you restart Windows'
  439. Write-Host ''
  440. Write-Host ' Please ensure you stay connected to the Internet.'
  441. Write-Host ''
  442. Write-Host ' Press enter to continue...' -NoNewLine
  443. $Host.UI.ReadLine()
  444. $Menu = 'exit'
  445. }
  446. 'result-done' {
  447. Write-Host ''
  448. Write-Host ' :: Installation done!'
  449. Write-Host ''
  450. Write-Host ' The WSL feature was already installed and enabled on your system, so we were'
  451. Write-Host ' able to install your distro right away.'
  452. Write-Host ''
  453. Write-Host ' Enjoy!'
  454. Write-Host ''
  455. Write-Host ' Press enter to continue...' -NoNewLine
  456. $Host.UI.ReadLine()
  457. $Menu = 'exit'
  458. }
  459. default {
  460. Write-Host ''
  461. Write-Host " !! Invalid menu encountered ($Menu). Exiting" -ForegroundColor Red
  462. Write-Host ' !! THIS IS A BUG, PLEASE REPORT IT TO THE AME DEVS' -ForegroundColor Red
  463. $Menu = 'exit'
  464. }
  465. }
  466. }
  467. }