从批处理文件运行 PowerShell 脚本

PowerShell 脚本是一个使用 .ps1 扩展名的文本文件,其中包含一组命令。PowerShell 按顺序执行这些命令。

批处理文件是使用 .bat 扩展名的文本文件。它还包含一组按顺序执行的命令。

这些命令可以通过打开 .bat 文件来执行。本教程将教你从批处理文件运行 PowerShell 脚本。

我们创建了一个 PowerShell 脚本 myscript.ps1,其中包含以下命令。

Write-Host "Your script is executed successfully."

我们还创建了一个批处理文件 test.bat 来运行上述 PowerShell 脚本。我们将使用批处理文件 test.bat 运行 PowerShell 脚本 myscript.ps1

使用 -File 参数从批处理文件运行 PowerShell 脚本

你可以使用 -File 参数调用 PowerShell 脚本。这是从命令提示符运行 PowerShell 脚本的简单命令。

test.bat 文件中使用以下命令来运行 PowerShell 脚本。 @echo off 命令禁用回显或阻止显示批处理文件内容。

pause 命令会停止批处理文件的执行,直到你按下除 CtrlShiftNumberLock 之外的任何键。

@echo off
powershell -File C:\New\myscript.ps1
pause

输出:

Your script is executed successfully.
Press any key to continue . . .

使用 RemoteSigned 作为 -ExecutionPolicy 从批处理文件运行 PowerShell 脚本

你可以将 RemoteSigned 设置为 -ExecutionPolicy 以从批处理文件运行 PowerShell 脚本。 -ExecutionPolicy 参数指定 PowerShell 执行策略。

@echo off
powershell -ExecutionPolicy RemoteSigned -File C:\New\myscript.ps1
pause

输出:

Your script is executed successfully.
Press any key to continue . . .

使用 Bypass 开关从批处理文件运行 PowerShell 脚本

你还可以使用 Bypass 作为执行策略从批处理文件运行 PowerShell 脚本。

@echo off
powershell -ExecutionPolicy Bypass -File C:\New\myscript.ps1
pause

输出:

Your script is executed successfully.
Press any key to continue . . .

或者,你也可以运行以下命令。

@echo off
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\New\myscript.ps1'"
pause

输出:

Your script is executed successfully.
Press any key to continue . . .

通过以管理员身份打开 PowerShell 从批处理文件运行 PowerShell 脚本

以下命令以管理员身份打开 PowerShell 以运行 PowerShell 脚本。当你打开批处理文件并选择时,输出将显示在 Windows PowerShell 上。

@echo off
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\New\myscript.ps1""' -Verb RunAs}"
ps1'"
pause

输出:

Your script is executed successfully.