从命令行管道输出写一个文件?

时间:2014-01-11 02:39:29

标签: vb.net output pipe

所以,自从我不得不在VB.NET中编码并且我真的生锈以来已经好几年了。我正在尝试将bcedit.exe的输出写入我打算稍后阅读的文件。这是在x64系统上,我需要以管理员身份运行该命令。除了没有写入文件外,工作正常。

这是我到目前为止的内容

Private Sub BCDEdit(strWhich As String)' This sub runs the Windows bcdedit program, with a paramater, edit the boot.ini file.

    Dim p As System.Diagnostics.Process
    Dim pStartInfo As System.Diagnostics.ProcessStartInfo

    pStartInfo = New System.Diagnostics.ProcessStartInfo()

    With pStartInfo
        .FileName = Environment.SystemDirectory.ToString() & "\bcdedit.exe"
        .Verb = "runas"
        .Arguments = strWhich
        .WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
        .UseShellExecute = True
    End With

    p = System.Diagnostics.Process.Start(pStartInfo)

    p.WaitForExit()

End Sub

我用

来调用sub
BCDEdit("> " & Environment.GetEnvironmentVariable("TEMP") & "\DUMP.tmp".ToString())

似乎有一半的斗争与.UseShellExecute的值有关,我需要将其设置为True以便命令提示符保持隐藏状态,但是,如果我将其设置为{{ 1}}我可以稍微使用False并将其读取到内存中(尽管我仍然没有得到输出的实际管道,但也没有。)

从提升的命令提示符执行.RedirectStandardOutput工作正常,因此在翻译中丢失了一些东西。

任何?

1 个答案:

答案 0 :(得分:2)

我怀疑重定向修饰符不会被识别为参数。您可能必须通过重定向捕获它并将其输出到文件的标准输出流来手动重定向输出。

此外,您似乎已将其向后移动,UseShellExecute应该为false以使用System.Diagnostics.ProcessWindowStyle.Hidden。根据{{​​3}}

这是一个简单的例子:

    Dim newprocess As New Process()
    With newprocess.StartInfo
        .CreateNoWindow = True
        .FileName = Environment.SystemDirectory.ToString() & "\bcdedit.exe"
        .Verb = "runas"
        .RedirectStandardOutput = True
        .UseShellExecute = False
    End With
    'Change the False to True to append instead of overwrite
    Dim sw As New IO.StreamWriter(Environment.GetEnvironmentVariable("TEMP") & "\DUMP.tmp", False)
    newprocess.Start()
    Dim sr As IO.StreamReader = newprocess.StandardOutput
    While Not sr.EndOfStream
        sw.WriteLine(sr.ReadLine)
    End While
    sw.Close()
    sr.Close()

不确定为什么'runas'不能用于该应用程序,但我对此做了更多思考并找到了可行的解决方案:

    Dim newprocess As New Process()
    With newprocess.StartInfo
        .CreateNoWindow = True
        .Verb = "runas"
        .FileName = "cmd"
        .Arguments = "/c bcdedit > " & Environment.GetEnvironmentVariable("TEMP") & "\DUMP.tmp"
        .UseShellExecute = True
    End With
    newprocess.Start()

基本上,它在管理员模式下使用命令处理器以标准输出修饰符('>')运行bcdedit。

相关问题