您好,我正在开发一个 vb.net 程序,该程序将调用一些 powershell 脚本和命令来管理 Exchange 2010。目前,我正在使用 System.Diagnostics.process 一次调用我的脚本。这里是工作代码的例子
Public Sub execPowershell(ByVal File As String, ByVal Argument As String)
Dim objProcess As System.Diagnostics.Process
Try
objProcess = New System.Diagnostics.Process()
objProcess.StartInfo.FileName = "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe "
objProcess.StartInfo.Arguments = " -executionpolicy bypass " & File & " " & Argument
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
objProcess.StartInfo.RedirectStandardError = True
objProcess.StartInfo.UseShellExecute = False
objProcess.StartInfo.WorkingDirectory = "c:\scripts"
objProcess.Start()
'Wait until the process passes back an exit code
'Dim toto As String = objProcess.StandardError.ReadToEnd()
objProcess.WaitForExit()
Catch
'MessageBox.Show("Could not start process " & ProcessPath, "Error")
End Try
End Sub
我想要做的是打开一个powershell提示符并通过streamwriter运行多个命令。
像这样的东西,但似乎 powershell 提示符没有收到命令。如果我对dos提示“cmd”做同样的事情,它的工作原理
Public Sub execPowershelltest()
Dim objProcess As New Process
Dim startinfo As New ProcessStartInfo
Try
startinfo.FileName = "powershell" 'starts powershell window
startinfo.RedirectStandardInput = True
startinfo.RedirectStandardOutput = True
startinfo.RedirectStandardError = True
startinfo.UseShellExecute = False 'required to redirect
startinfo.WindowStyle = ProcessWindowStyle.Normal
startinfo.WorkingDirectory = "c:\windows"
objProcess.StartInfo = startinfo
objProcess.Start()
Dim sw As StreamWriter = objProcess.StandardInput
sw.WriteLine("md c:\toto")
sw.WriteLine("md c:\powershellbysentence")
sw.WriteLine("md c:\toto2")
sw.Close()
'Wait until the process passes back an exit code
'Dim toto As String = objProcess.StandardError.ReadToEnd()
Dim toto As String = objProcess.StandardError.ReadToEnd
objProcess.WaitForExit()
Catch
'MessageBox.Show("Could not start process " & ProcessPath, "Error")
End Try
End Sub
提前谢谢