【问题标题】:Trap output from powershell command in VB.net在 VB.net 中捕获 powershell 命令的输出
【发布时间】:2023-03-25 13:14:01
【问题描述】:

您好,我正在开发一些 VB.net 应用程序来管理我的 Exchange 2010 服务器上的分发列表。此代码调用具有 2 个参数的 ps1 脚本及其工作。我唯一的问题是我想捕获 PowerShell.Invoke() 的输出。执行后 PowerShellCommandResults 总是为空 集合中没有记录。
也许问题来自于从 ps1 文件中捕获,但我真的不知道在哪里可以解决我的问题

谢谢

Dim PowerShell As Management.Automation.PowerShell = PowerShell.Create()
Dim PowerShellCommand As New PSCommand()
Dim PowerShellCommandResults As Collection(Of PSObject)

PowerShellCommand.AddCommand("c:\scripts\connect.ps1")

PowerShellCommand.AddCommand("c:\scripts\newld.ps1")
PowerShellCommand.AddArgument("test@cscapitale.qc.ca")
PowerShellCommand.AddArgument("Distribution liste test")

Try
            PowerShellCommandResults = PowerShell.Invoke()
            Dim sw As New StreamWriter("C:\" & Now.ToLongDateString & ".txt")
            For Each line In PowerShellCommandResults
                sw.WriteLine(line.ToString)
            Next

            sw.Dispose()
            PowerShell.Dispose()
 Catch ex As Exception

 End Try

【问题讨论】:

    标签: powershell output vb.net-2010


    【解决方案1】:

    您是否尝试过改用Powershell.Invoke(IEnumerable, IList) 签名?我通常使用 C#,所以我可能不完全正确...

    ' Old and busted: PowerShellCommandResults = PowerShell.Invoke()
    ' New hotness:
    PowerShell.Invoke(Nothing, PowerShellCommandResults)
    
    ' Everything below here is unchanged
    Dim sw As New StreamWriter("C:\" & Now.ToLongDateString & ".txt")
    For Each line In PowerShellCommandResults
        sw.WriteLine(line.ToString)
    Next
    

    替代答案:尝试使用PowerShellCommand.AddScript("C:\Scripts\Connect.ps1")

    替代答案:确保 connect.ps1newld.ps1 脚本输出到管道,而不是主机。

    # Bad: Explicitly writes to the host, and skips pipeline output
    Write-Host "Some value"
    
    # Good: A string, or variable on its own will be output on the pipeline
    "Some Value"
    $OtherVariable
    

    【讨论】:

    • thx 问题是我的脚本没有返回到管道!
    猜你喜欢
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2017-02-26
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多