VB.net运行进程无法正常工作 - 命令行是什么?

时间:2015-09-09 12:28:52

标签: vb.net command-line-arguments command-prompt

在命令行,我可以运行以下命令:

openfiles /query /s \\pha-sr-myserver /v > s:\textfile.txt

运行正常并在服务器pha-sr-myserver上生成一个openfiles列表并将其输出到textfile.txt

现在我尝试在代码中重现这一点,但它不起作用:

Dim MyProcess As Process
Dim cText As String
Dim Shellcommand As String = "c:\windows\system32\openfiles.exe"
Dim ShellArgs As String = "/query /s \\pha-sr-myserver /v > S:\textfile.txt"
MyProcess = Process.Start(Shellcommand, ShellArgs)
MyProcess.WaitForExit()

这已经过了舞台,但文件永远不会产生,对于我的生活,我看不出什么是错的。 我试着用双引号等封装参数。 我这样多次炮击但是不能缝合才能使这个工作。 任何想法都会被贬低。 谢谢 格雷厄姆

3 个答案:

答案 0 :(得分:0)

您可以尝试一个简单的Shell command

Dim sComando As String
Dim Shellcommand As String = "c:\windows\system32\openfiles.exe"
sComando = """" & Shellcommand & """" & " /query /s \\pha-sr-myserver /v > S:\textfile.txt"
Shell(sComando , AppWinStyle.Normal, True)

或者也许是这个:

Dim MyProcess As Process
Dim cText As String
Dim Shellcommand As String = "c:\windows\system32\openfiles.exe"
Dim oShellArgs As ProcessStartInfo


oShellArgs = New ProcessStartInfo(Shellcommand , " /query /s \\pha-sr-myserver /v ")  ' remove this > "  "S:\textfile.txt"" ")
oShellArgs.RedirectStandardOutput = true
oShellArgs.RedirectStandardError = true
MyProcess = Diagnostics.Process.Start(oShellArgs)

MyProcess.StandardOutput.ReadToEnd() ' read this list of string

MyProcess.WaitForExit()

答案 1 :(得分:0)

openfiles.exe无法理解> S:\textfile.txt。只有cmd.exe才能理解它。您需要使用Process.Start启动cmd.exe或直接启动您的应用程序,然后重定向其标准输出以捕获它。尝试这样的事情:

Dim shellArgs As String = "/query /s \\pha-sr-myserver /v"
Dim output As String = runCommandLineApp("c:\windows\system32\openfiles.exe", Nothing, shellArgs)
'Do something with output here, such as write it to a file.

Private Function runCommandLineApp(appFileName As String, workingDirectory As String, Optional args As String = Nothing) As String
    Dim psi As New ProcessStartInfo(appFileName, args)
    psi.RedirectStandardOutput = True
    psi.UseShellExecute = False
    psi.CreateNoWindow = True
    psi.WindowStyle = ProcessWindowStyle.Hidden

    If workingFolder IsNot Nothing Then
        psi.WorkingDirectory = workingFolder
    End If

    Dim p As New Process()
    p.StartInfo = psi
    p.Start()

    Dim output As String = p.StandardOutput.ReadToEnd()

    p.WaitForExit()

    Return output

End Function

答案 2 :(得分:0)

只有cmd.exe可以将>解释为重定向。 因此,最简单的方法是从您的程序中运行cmd.exe

Dim MyProcess As Process
Dim cText As String
Dim Shellcommand As String = "cmd"
Dim ShellArgs As String = "/c openfiles /query /s \\pha-sr-myserver /v > S:\textfile.txt"
MyProcess = Process.Start(Shellcommand, ShellArgs)
MyProcess.WaitForExit()