HOWTO · PowerShell

如何執行 PowerShell 腳本

本教程將教你如何運行 PowerShell 腳本。

本頁內容

PowerShell 腳本是一組命令,保存在擴展名為 .ps1 的文件中。PowerShell 執行寫在 .ps1 文件中的命令。

我們創建了一個名為 myscript.ps1 的 PowerShell 腳本,該腳本包含以下命令。

Write-Host "Your script is executed successfully."

輸出:

Your script is executed successfully.

當執行 myscript.ps1 時,應顯示上述輸出。本教程將介紹運行 PowerShell 腳本的不同方法。

使用 ./script_name 在 PowerShell 中運行 PowerSell 腳本

您需要位於腳本文件所在的目錄才能使用此方法。cd 命令用於更改 PowerShell 中的工作目錄。在導航到腳本文件的目錄後,運行 ./script_name

例如,我們的腳本文件位於 C:\New

cd C:\New

然後運行腳本。

./myscript.ps1

輸出:

Your script is executed successfully.

使用完整路徑在 PowerShell 中運行 PowerShell 腳本

在此方法中,您不需要更改工作目錄。您可以提供腳本文件的完整路徑來運行它。

C:\New\myscript.ps1

輸出:

Your script is executed successfully.

使用 cmd.exe 運行 PowerShell 腳本

您可以從命令提示符運行 PowerShell 腳本。-noexit 參數不是必須的。它保持控制台打開,因為 PowerShell 在腳本完成後會退出。

powershell -noexit C:\New\myscript.ps1

輸出:

Your script is executed successfully.

使用 -File 參數在 cmd.exe 中運行 PowerShell 腳本

-File 參數允許您從另一個環境(如 cmd.exe)調用腳本。

powershell -File C:\New\myscript.ps1

輸出:

Your script is executed successfully.

使用 bypass 開關在 cmd.exe 中運行 PowerShell 腳本

您可以使用 bypass 開關在不修改默認腳本執行策略的情況下運行 PowerShell 腳本。

powershell -executionpolicy bypass -File C:\New\myscript.ps1

輸出:

Your script is executed successfully.

使用 type 命令在 cmd.exe 中運行 PowerShell 腳本

您也可以使用 type 命令在 cmd 中運行 PowerShell 腳本。

type "C:\New\myscript.ps1" | powershell -c -

輸出:

Your script is executed successfully.