如何從命令提示符處執行 PowerShell 指令碼?


要從命令提示符處執行 PowerShell 指令碼,我們可以使用下面的命令。

示例

例如,我們有一個指令碼 TestPS.ps1 先啟動後臺處理程式服務,然後將檔案複製到另外一個位置。我們需要使用命令提示符來呼叫此指令碼。

C:\> PowerShell.exe -command "C:\temp\TestPS.ps1"

上述命令類似於執行單個 PowerShell 命令。此處我們提供了指令碼路徑。

輸出

C:\>PowerShell.exe -command "C:\temp\TestPS.ps1"
VERBOSE: Performing the operation "Start-Service" on target "Print Spooler (Spooler)".
Status Name DisplayName
------ ----- ----------
Running Spooler Print Spooler
VERBOSE: Performing the operation "Copy File" on target "Item: C:\Temp\EnvVariable.txt
Destination: C:\Temp\Test\EnvVariable.txt".

您也可以使用下面的命令,

C:\> PowerShell.exe Invoke-Command -ScriptBlock { "C:\temp\TestPS.ps1"}

當您使用第三方工具或遠端呼叫此命令時,本地計算機可能會阻止指令碼執行。在這種情況下,您需要透過設定執行策略來啟用指令碼執行。

PowerShell.exe -ExecutionPolicy Unrestricted -command "C:\temp\TestPS.ps1"

更新日期:30-Mar-2021

23K+ 瀏覽量

開啟職業生涯

完成課程,獲得認證

開始
廣告