【问题标题】:Powershell ps1 script runs bat file but CMD screen closes after executionPowershell ps1 脚本运行 bat 文件但 CMD 屏幕在执行后关闭
【发布时间】:2020-05-29 19:29:28
【问题描述】:

这是我的代码:

set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait

set-location C:\

在 powershell 中执行时,系统会打开命令提示符窗口并执行 bat 文件而不会出现问题。问题是窗口关闭了,如果成功我看不到是否有错误。

我想保持 CMD 窗口打开。

我也试过在bat文件末尾:

:END
cmd /k

但没有运气。

【问题讨论】:

  • Pause 可以解决问题。 powershell 也支持大多数 cmd 命令。所以你不需要从 powershell 调用 cmd。您可以直接在 powershell 上运行,甚至可以将其转换为 powershell。这样,您可以执行错误处理等

标签: powershell batch-file cmd


【解决方案1】:

首先,除非您特别需要在新窗口中运行批处理文件,否则不要使用Start-Process - 使用直接调用,这是隐含的同步,并允许您捕获或重定向输出

# Invoke the batch file synchronously (wait for it to exit)
# and capture its (standard) output in variable $A
# To print the batch file's output to the console instead, just use:
#    .\refresh.bat
$A = .\refresh.bat

更多信息请参见this answer

还要注意Start-Process 永远不允许您直接捕获被调用程序的输出(您只能使用-RedirectStandardOutput-RedirectStandardOutput 将其重定向到文件);您的特定命令在$A 中捕获nothing[1];添加-PassThru 确实会返回一些东西,但不是程序的输出,而是一个进程信息对象(System.Diagnostics.Process)。

如果您确实需要在新窗口中运行批处理文件并希望保持该窗口打开

Start-Process -Wait -FilePath cmd -ArgumentList '/k .\refresh.bat'

依靠位置参数绑定,上面可以简化为:
Start-Process -Wait cmd '/k .\refresh.bat'


[1] 严格来说,$A 被分配了 [System.Management.Automation.Internal.AutomationNull]::Value 单例,在大多数情况下其行为类似于 $null

【讨论】:

    【解决方案2】:

    感谢 mklement0 的帖子给了我想要的解决方案。我就是这样解决的。

    set-location [PATH]
    $A = Start-Process -FilePath .\refresh.bat -Wait -NoNewWindow
    set-location C:\
    

    -NoNewWindow 允许我在同一个 powershell 窗口中运行我的批处理以获取 bat 文件的反馈。这样,如果有错误,我就会有错误,如果没有错误,就会有成功状态。

    谢谢!

    【讨论】:

    • 很高兴听到我的回答很有帮助 - 请注意,更简单的替代方法是使用直接调用而不捕获输出:.\refresh.bat 本身就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多