在VB.net中获取shell命令的输出

时间:2012-01-10 19:20:08

标签: vb.net windows shell

我有一个VB.net程序,我在其中调用Shell函数。我想从文件中获取从此代码生成的文本输出。但是,这不是执行代码的返回值,所以我真的不知道如何。

此程序是一项服务,但可以访问磁盘没问题,因为我已经记录了其他信息。整个服务有多个线程,所以我还必须确保在写入文件时它尚未被访问。

3 个答案:

答案 0 :(得分:28)

您将无法捕获Shell的输出。

您需要将此更改为流程,并且需要从流程中捕获Standard Output(可能还有错误)流。

以下是一个例子:

        Dim oProcess As New Process()
        Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
        oStartInfo.UseShellExecute = False
        oStartInfo.RedirectStandardOutput = True
        oProcess.StartInfo = oStartInfo
        oProcess.Start()

        Dim sOutput As String
        Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
            sOutput = oStreamReader.ReadToEnd()
        End Using
        Console.WriteLine(sOutput)

要获得标准错误:

'Add this next to standard output redirect
 oStartInfo.RedirectStandardError = True

'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
        sOutput = oStreamReader.ReadToEnd()
End Using

答案 1 :(得分:9)

只需将输出传输到文本文件?

MyCommand > "c:\file.txt"

然后阅读文件。

答案 2 :(得分:0)

    Dim proc As New Process

    proc.StartInfo.FileName = "C:\ipconfig.bat"   
    proc.StartInfo.UseShellExecute = False
    proc.StartInfo.RedirectStandardOutput = True
    proc.Start()
    proc.WaitForExit()

    Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
    For Each ln As String In output
        RichTextBox1.AppendText(ln & vbNewLine)
        lstScan.Items.Add(ln & vbNewLine)
    Next

=============================================== ======================== 创建一个批处理文件,如下所示:

    echo off
    ipconfig

'确保将此批处理文件保存为ipconfig.bat或您决定选择的任何名称,但请确保将dot bat放在其末尾。