运行 PowerShell 脚本

PowerShell 脚本是保存在 .ps1 扩展文件中的命令集合。PowerShell 执行写在 .ps1 文件中的命令。

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

Write-Host "Your script is executed successfully."

输出:

Your script is executed successfully.

执行 myscript.ps1 时应显示上述输出。本教程将介绍运行 PowerShell 脚本的不同方法。

在 PowerShell 中使用 ./script_name 运行 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 脚本

你可以使用绕过开关来运行 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.