用一行指令在 Windows 上安裝 PowerShell 6

Jun 23, 2019 • 花費 2 分鐘

在 Windows 10 和 Windows Server 2019 里的 PowerShell 都是預設使用 WMF 5.1 為基礎的 5.1 版本。更早期至 Windows 7 SP1 好像是 2.0 版本 …

PowerShell 6 (又稱 PowerShell Core) 則是一個以開源,跨平台(Windows, Linux, macOS),異質系統及雲端平台為目標來設計的版本。

PowerShell 6.X 現在仍然是和 Windows PowerShell 5.1 並行的版本,不能由 5.1 直接升級上去。

你可以很簡單地在 Microsoft Docs 里學會使用 PowerShell Core。

但其實只要一行指令,就可以下載新的 PowerShell Core 安裝檔了.

打開 PowerShell 5.1 (With Administrator)

PS C:\Users\Me\HostName> iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

這里解析一下:

  • 首先 https://aka.ms/install-powershell.ps1 是一段 ps1 的程式碼
  • 用 irm,也就是 Invoke-RestMethod,是內置的 Cmdlet,用來發一個 HTTP/HTTPS Request 給指定的 RESTful Web service
  • 把回傳回來的值定義成一個 variables -> $(),再 calling 這個 variables -> &{}
  • calling 的同時傳入參數 -UseMSI,最後用 iex,就是 Invoke-Expression 這個 Cmdlet 執行 command block 的內容。

簡單來說是官方寫好了一支 PowerShell script,你去 Request 下來執行就好 …

所以可以直接去看 https://aka.ms/install-powershell.ps1 里面那 4 百多行程式碼,學習及了解如何寫一份 PowerShell script。

然後會發現有多個參數可以設置:

  • -Destination : 安裝路徑,預設在 $env\LOCALAPPDATA\Microsoft\powershell

  • -Preview : 安裝最新的 preview 版本

  • -Quite : MSI installer 的安靜模式

  • -Daily : 去 https://powershell.myget.org/F/powershell-core-daily 上取得每天的 build 版本

  • -DoNotOverwrite : 不要覆寫安裝路徑上己有的版本

  • -AddToPath :

    • 在 Windows 上把安裝路徑的絕對路徑加入 User 的 Path 環境變數中.
    • 在 Linux 上創造一個指向 $Destination/pwsh 的 symlink : /usr/bin/pwsh
    • 在 macOS 上創造一個指向 $Destination/pwsh 的 symlink : /usr/local/bin/pwsh

所以如果你想安裝新的 Preview 版本,以及下載至 User Me 的 Desktop 路徑上, 不使用 Installer:

PS C:\Users\Me\HostName> iex "& { $(irm https://aka.ms/install-powershell.ps1) } -Destination C:\Users\Me\Desktop\powershell -Preview"

然後就到 preview/ 目錄下使用最新的 preview 版本。

那 Linux/macOS 呢 ?

如果我們是第一次在 Linux/macOS 安裝 PowerShell Core 呢?

聰明的你讀到這邊就知道官方早就準備好各個作業系統/平台的安裝 scripts,位於 Github 上面

看得出來官方陸續為使用者寫安裝 scripts

所以在 Linux 上,只要你有權限及連網的環境,直接 curl 下來就可以了:

$ sudo bash <$(curl -s https://raw.githubusercontent.com/PowerShell/PowerShell/master/tools/install-powershell.sh)

接下來有空整理如何把 Windows 上的 PowerShell 變得好用一點,如何管理及撰寫 PowerShell script, PowerShell module 等話題.

題外話

aka.ms 這個 domain name 屬於美國東岸右方的一個 “英屬” 小群島 : Montserrat 😂

#PowerShell#Windows#2019

😱 外國 Google 工程師 WFH (Work From Home) 時的配置 ...

如何有格調地告訴別人你的 Email address

comments powered by Disqus