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.

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