【问题标题】:Powershell Console output not availablePowershell 控制台输出不可用
【发布时间】:2021-06-11 09:57:28
【问题描述】:

我正在尝试从 excel 运行 pwershell 脚本,我可以这样做并且它可以工作,但是 powershell 窗口不显示来自脚本中 write-host 命令的信息。如果我从 cmd 提示符运行文件,我会在控制台窗口中看到所有写入主机文本,如下所示。

从命令提示符运行 Powershell
[]

但是,如果我使用 excel 中的此代码。

Sub RunAndGetCmd()

    strCommand = "Powershell -File ""C:\PSFiles\TestOutput.ps1"""
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec(strCommand)

End Sub

我在控制台窗口中没有显示任何文本,只有一个闪烁的光标,如下所示

从 excel 运行相同的 Powershell

我知道脚本运行并完成了所有操作,但我想在脚本运行时输出文本,这样我就可以看到它已经走了多远。

非常感谢任何想法。

【问题讨论】:

    标签: vba powershell


    【解决方案1】:

    WScript.ShellExec 命令重定向 stdin、stdout 和 stderr 流,以便您可以从应用程序访问它们。因此,外部应用程序写入标准输出的任何内容(例如,在 PowerShell 中使用 write-host)都会被重定向,而不是显示在外部应用程序的窗口中。

    如果您希望在应用程序窗口中显示输出,您可以改用Run 方法 - 例如

    Option Explicit
    
    Sub RunAndGetCmd()
    
        Dim strCommand As String
        Dim WshShell As Object
    
        strCommand = "Powershell -File ""C:\PSFiles\TestOutput.ps1"""
    
        Set WshShell = CreateObject("WScript.Shell")
        WshShell.Run strCommand
    
    End Sub
    

    但如果你这样做,你还不如只使用内置的 VBA Shell 函数:

    Option Explicit
    
    Sub RunAndGetCmd()
    
        Dim strCommand As String
    
        strCommand = "Powershell -File ""C:\PSFiles\TestOutput.ps1"""
    
        VBA.Shell strCommand
    
    End Sub
    

    另请注意,您可能需要在命令中使用-ExecutionPolicy RemoteSigned,以防机器将其设置为受限:

    strCommand = "Powershell -ExecutionPolicy RemoteSigned -File ""C:\PSFiles\TestOutput.ps1"""
    

    【讨论】:

    • 感谢您的回答,我使用了第一个建议,因为当我尝试了第二个建议时,我遇到了病毒防护问题,说我正在尝试运行恶意宏。非常感谢。在此期间,您是否知道是否有一种方法可以在 Powershell 脚本执行完毕之前一直留在代码中?
    • @BrendanMcDonnell - Run 方法的文档描述了一个可选的 bWaitOnReturn 参数,它可能会满足您的要求...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2018-12-30
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多