Представьте себе следующий действительно простой пакетный файл с именем "hello.bat"
@ECHO OFF
echo Hello
Вы можете позвонить и посмотреть «Привет», используя:
'Will hold the results of the batch
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run
P.StartInfo.FileName = "c:\scripts\hello.bat"
'My script doesn't take argument but this is where you would pass them
P.StartInfo.Arguments = ""
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to see the output
P.StartInfo.RedirectStandardOutput = True
'Start your batch
P.Start()
'Read the entire contents of the outout
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine("Batch produced : " & Output)
Редактировать
Вот версия, которая не запускает пакет, а выполняет несколько стандартных команд. Мы начинаем с запуска командной оболочки для передачи вещей. Одна вещь, которая отстой, состоит в том, что сложно выполнить команду, прочитать вывод и затем выполнить другую команду. Приведенный ниже код запускает две команды подряд и выводит весь результат в строку. Если вам нужно запустить команду, обработать, запустить другую команду, я думаю, вам придется подключить что-то к StandardError и посмотреть коды возврата. Прежде чем сделать это, убедитесь, что вы прочитали о проблеме с блокировкой и о том, как другие места решают ее, подключив потоки, например как здесь . Вероятно, более простой способ - обернуть это в подпрограмму и вызвать подпрограмму один раз для каждой команды.
'Will hold all of the text
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run the standard command shell
P.StartInfo.FileName = "cmd.exe"
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to read/write to it
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
'Start your batch
P.Start()
'Send your various commands
P.StandardInput.WriteLine("dir c:\")
P.StandardInput.WriteLine("ipconfig /all")
'Very important, send the "exit" command otherwise STDOUT will never close the stream
P.StandardInput.WriteLine("exit")
'Read the entire stream
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine(Output)
Редактировать 2
У меня проблемы с командой «запрос пользователя» в целом, я не могу заставить ее что-либо возвращать для имен пользователей с пробелами в них, даже если я заключаю имя в кавычки. Но вот версия, в которой вместо этого используется «quser», которая, насколько я знаю, делает то же самое.
'Will hold all of the text
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run the standard command shell
P.StartInfo.FileName = "cmd.exe"
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to read/write to it
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
'Start your batch
P.Start()
'Send your various commands
'Array of servers
Dim arrServers() As String = New String() {"SERVER1", "SERVER2"}
'Loop through array, wrap names with quotes in case they have spaces
For Each S In arrServers
P.StandardInput.WriteLine(String.Format("quser ""{0}"" /SERVER:{1}", Me.txtBoxUsername.Text, S))
Next
'Very important, send the "exit" command otherwise STDOUT will never close the stream
P.StandardInput.WriteLine("exit")
'Read the entire stream
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine(Output)