运行 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.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。