如何從命令行運行 PowerShell 腳本和更多

如果你是新手想要學習 PowerShell 指令碼語言,並想要知道如何執行 PowerShell 指令碼,你來到了正確的部落格文章。本文將是一個教程,涵蓋了執行指令碼的常見方法以及可能出現的一些問題。

先決條件

本文將為你提供有關如何在本地計算機上運行 PowerShell 的步驟。如果你想跟著做,請確保在開始閱讀本文之前,已經具備以下先決條件。

  • A Windows 10 computer with Administrator privileges.
  • Windows PowerShell 版本需為 5 或更高。你也可以使用 PowerShell v7。本教程將專注於 Windows PowerShell,因為 Windows 操作系統已經預先安裝了它。
  • 任何文本編輯器

處理執行原則

如果這是你第一次嘗試執行 Windows PowerShell 指令碼,你可能會遇到一個常見問題。PowerShell 可能會返回一條錯誤消息,指出腳本“無法加載,因為在此系統上禁用了運行腳本”。

PS> .\GetServices.ps1
 File C:\Temp\GetServices.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
 https:/go.microsoft.com/fwlink/?LinkID=135170.
 At line:1 char:1
 .\GetServices.ps1
 ~~~~~ CategoryInfo          : SecurityError: (:) [], PSSecurityException
 FullyQualifiedErrorId : UnauthorizedAccess   

當您嘗試以設定為RestrictedRemote SignedAll Signed的執行原則運行PowerShell時,PowerShell會返回上述錯誤訊息。

Restricted

Restricted是Windows用戶端電腦的預設原則設定。如果您是第一次使用PowerShell,您的預設原則可能會限制所有腳本的執行。

您仍然可以在終端中執行個別命令,但無法執行腳本檔。此限制包括任何以.ps1xml.psm1.ps1結尾的檔案。

Unrestricted

Unrestricted允許您執行任何腳本,但在執行從網路下載的腳本之前會發出警告。這通常是非Windows設備的預設原則。

Remote Signed

Remote Signed原則允許您執行任何已經數位簽署的腳本,或者在本地計算機上編寫的帶有或不帶有簽名的腳本。

如果從網路下載的腳本未經簽署,您需要解除該檔案的封鎖。您可以右鍵點擊該檔案,然後選擇內容進行解鎖。或者,您可以使用Unblock-File PowerShell命令碼解鎖該特定腳本檔。

在從網路下載的腳本上運行時,使用Remote Signed原則是一個理想的選項。

All Signed

All Signed要求所有腳本都必須由受信任的發行者進行數位簽署。這包括從網路下載和在本地計算機上編寫的腳本。

更改 PowerShell 執行原則

要更改執行原則:

  1. 系統管理員身分執行 開啟 Windows PowerShell,確保您擁有最高權限以進行原則更改。
Search PowerShell in Start Menu

2. 開啟 PowerShell 後,執行以下 PowerShell 命令以設定您的電腦執行原則。如前所述,執行原則可以是三種不同的類型之一。本教程使用的是一種既有用又安全的執行原則,即 RemoteSigned

由於本教程假設您已從網絡上下載了 GetServices.ps1 腳本文件,因此將執行原則設定為 RemoteSigned

PS> Set-ExecutionPolicy RemoteSigned

RemoteSigned 執行原則要求您在 PowerShell 在您的系統上執行從網絡上下載的每個 PowerShell 腳本之前,對其進行 加密簽名

3. 您應該會看到一個輸出,要求確認此操作。輸入 Y,然後按 Enter 確認原則更改。

Execution Policy Change
 The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the
 security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to
 change the execution policy?
 [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): 

此時,按照下一步驟來探索在您的電腦上執行 PowerShell 腳本的不同方法。

如何執行 PowerShell 腳本

要演示运行PowerShell脚本,实际上需要一个脚本文件来运行!如果您手头没有一个,下载此ZIP文件并提取其中的PS1文件。您会发现一个名为GetServices.ps1的简单脚本文件。

Write-Output "Listing Computer Services"
Get-Service

每个PowerShell脚本都应以.ps1扩展名结尾。

使用控制台

一旦您准备好脚本,有几种不同的方法可以执行PowerShell脚本文件。其中最常见的方法之一是通过PowerShell控制台。

要执行此操作:

  1. 打开如上所示的PowerShell控制台。

2. 使用Set-Location PowerShell命令或者cd别名导航到您的脚本所在的文件系统位置。本教程的脚本位于C:\Temp目录中。

PS> cd C:\Temp\

3. 使用点号(.)表示法运行脚本。PowerShell是一个还会查找命令名称的Shell。为了区分PowerShell命令和脚本,您必须在脚本之前加上一个点。这个点表示当前目录。

 PS> .\GetServices.ps1

如何通过PowerShell位置从命令行运行PowerShell脚本

如果您不能或者不愿意通过PowerShell控制台运行脚本,您也可以使用老式的命令行(命令提示符)来运行。

要通过命令提示符运行脚本,您必须首先启动 PowerShell 可执行文件(powershell.exe),并将 PowerShell 的位置设为 C:\Program Files\WindowsPowerShell\powershell.exe ,然后将脚本路径作为参数传递给它。

您可以在任何上下文中通过简单指定参数来运行带参数的脚本,就像运行 PowerShell 可执行文件时指定它们一样,如 powershell.exe -Parameter 'Foo' -Parameter2 'Bar'

一旦您打开 cmd.exe,您就可以执行 PowerShell 脚本,就像下面的示例一样。此示例正在运行引擎,并将脚本路径传递给它:C:\Temp\GetServices.ps1

请注意下面的示例正在使用 PowerShell 位置路径来运行脚本。如果文件夹不在您的 PATH 中,则必须执行此操作。

CMD> C:\Program Files\WindowsPowerShell\powershell.exe "C:\Temp\GetServices.ps1"

PowerShell 7 的 PowerShell 位置使用不同的可执行文件,通常命名为 pwsh.exe,位于 C:\Program Files\PowerShell\7\pwsh.exe

以下是一个方便的 YouTube 视频,介绍了通过批处理文件执行脚本的方法,cmd.exe 执行此操作。

使用 PowerShell ISE

如果您创建自己的脚本或编辑他人的脚本,您可能会使用脚本编辑器,如 PowerShell ISE 或者 Visual Studio (VS) Code。由于 ISE 随 Windows 附带,让我们专注于该方法进行本教程。

為了透過ISE調用腳本:

  1. 請前往開始菜單,搜索PowerShell ISE並打開。
Search PowerShell ISE in Start Menu

2. 點擊文件打開,找到您的腳本。

Open Script using File Menu

3. 在打開的腳本中,點擊綠色運行按鈕以執行該腳本。此按鈕將在底部的內置PowerShell終端中調用腳本。

Run Script using PowerShell ISE

示例腳本的輸出

A PowerShell script can sometimes return output. This happens when the script you’re executing is built to return objects which is a fundamental component of PowerShell.

如果運行示例GetServices.ps1腳本,您將看到以下內容。此腳本運行Get-Service cmdlet,返回本地Windows計算機上安裝的所有服務。

PS> .\GetScripts.ps1
Listing Computer Services
Status   Name               DisplayName
------   ----               -----------
Running  aakore             Acronis Agent Core Service
Stopped  AarSvc_1b668d      Agent Activation Runtime_1b668d
Running  AcronisActivePr... Acronis Active Protection Service
Running  AcronisCyberPro... Acronis Cyber Protection Service
Running  AcrSch2Svc         Acronis Scheduler2 Service
Running  AdobeARMservice    Adobe Acrobat Update Service
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Monitor Service
Running  AGSService         Adobe Genuine Software Integrity Se...
----Truncated----

從腳本內調用PowerShell腳本

假設您有兩個腳本,您想讓一個調用另一個。也許您有一個名為GetUser.ps1和一個名為ResetPassword.ps1的腳本。在GetUser.ps1腳本內,您想要執行ResetPassword.ps1以重置用戶密碼。

在調用腳本(GetUser.ps1)內,您可以添加一行代碼以執行另一個腳本,就像從命令行調用腳本一樣。

您可以看到下面有幾種選擇。通常,您應該選擇在同一會話或範圍內運行其他腳本,以簡化事務,除非有在另一個PowerShell會話中運行腳本的特定原因。

## 在新会话中运行另一个脚本
powershell.exe .\ResetPassword.ps1
## 在相同会话中运行另一个脚本
.\ResetPassword.ps1

Source:
https://adamtheautomator.com/run-powershell-script/