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 中运行 PowerShell 脚本
您需要在脚本文件所在的目录中使用此方法。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.