如何在Windows终端的PowerShell选项卡中运行PowerShell脚本(.ps1)?

4
我尝试过使用 Windows 终端(wt.exe)打开脚本,但是它显示了以下错误:
[error 0x800700c1 when launching `"C:\Users\hjdom\OneDrive\Desktop\All desktop stuff\Python Game\RunGame.ps1"']

我非常需要它能在Windows终端中运行,因为它允许您在脚本结束后继续输入命令。我正在使用该脚本来运行一个Python文件。

这是ps1脚本包含的内容:

python ./pythonfiles/startgame.py

非常感谢! - BlueFalconHD

1
请编辑您的问题,显示完整的 wt.exe 命令行,并澄清您从哪里调用它。 - mklement0
2个回答

10

Windows终端(wt.exe)不是一个命令行 shell。

它是命令行 shell(powershell、bash、cmd、python、perl等)的宿主。您需要告诉 WT.exe 要使用哪个命令行 shell 来调用您的脚本。

例如,cmd.exe 或通过 WinKey Run:

输入:

wt d:\temp\hello.ps1

这将会失败,伴随着……

[error 0x800700c1 when launching `d:\temp\hello.ps1']

尽管Windows终端以WT设置中的默认shell启动,但请执行以下操作...
wt.exe powershell D:\Scripts\hello.ps1

之所以能这样工作,是因为你告诉了wt.exe使用哪个shell来执行你的脚本。

根据您的评论进行更新。

但是运行脚本完成后,如何防止终端关闭?

你的目标shell需要提供一个方法来实现。Powershell(Windows和Core)通过-NoExit开关提供这种功能。

powershell /?

PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
    [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
    [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
    [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
    [-ConfigurationName <string>]
    [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
    [-Command { - | <script-block> [-args <arg-array>]
                  | <string> [<CommandParameters>] } ]

wt.exe powershell -NoProfile -NoLogo -NoExit D:\Scripts\hello.ps1

wt.exe pwsh -NoProfile -NoLogo -NoExit D:\Scripts\hello.ps1

如果您在调用其他 shell(如 bash、python、perl 等),那么它们也需要提供该功能。

1
但是,我该如何防止脚本运行完毕后终端关闭呢?我希望您能够输入命令。 - BlueFalconHD

1

对于想要在Windows终端中个性化其PowerShell终端或在Windows终端中打开PowerShell时运行脚本的所有人,必须执行以下操作:

您必须将所需的脚本作为参数传递给PowerShell来运行。换句话说,您使用powershell.exe作为运行脚本的媒介,而不是脚本运行的媒介。这意味着一旦所选脚本执行完成,powershell.exe也会停止,因为可执行文件的功能已传递给脚本。为了防止这种情况发生,您必须将属性“PowerShell -NoExit”传递给参数。

例如:


%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe PowerShell -NoExit %SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\PowerShell_Startup_Ascii_Art.ps1

这将防止PowerShell在脚本执行完成后关闭。


1
这正是我需要的答案!但我确实需要稍作调整。我正在使用Windows终端,而此命令适用于其中一个条目的设置中的命令行。命令字符串中必须删除“PowerShell”一词。在我的示例中,“py39”是我的虚拟环境的目录。"C:\Program Files\PowerShell\7\pwsh.exe" -NoExit %USERPROFILE%\py39\Scripts\Activate.ps1 - Mark
1
很高兴我能帮到你。如果你感兴趣,可以在以下链接中查看一个很酷的实现,以便在Windows终端上自定义横幅:https://superuser.com/a/1735410/1718628 - teodor mihail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接