The process tried to write to a nonexistent pipe vb.net - vb.net

I'm currently writing a sub in vb.net that is supposed to create and/or erase tasks in the task scheduler that comes with windows 10. The creation part works fine, but when I try to erase the task I get this error in the visual studio console: "The process tried to write to a nonexistent pipe", and the task is (of course) still there. I've looked for a solution but can't find anything similar. Here is the code:
Private Sub SimpleButton2_Click(sender As Object, e As EventArgs) Handles sbAutoRun.Click
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
End Sub
Private Sub CMDAutomate()
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
Dim sTime As String = teAutoRun.Time.ToString("HH:mm")
Dim sCmdCommand As String = "SCHTASKS /CREATE /SC DAILY /TN ""MyTasks\task"" /TR ""'" & My.Application.Info.DirectoryPath & "\program.exe' Auto"" /ST " & sTime & " /RL HIGHEST"
Dim sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"""
My.Settings.AutoRun = ceAutoRun.Checked
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.CreateNoWindow = True '<---- if you want to not create a window
StartInfo.UseShellExecute = False 'required to redirect
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
If My.Settings.AutoRun And Not My.Settings.AutoRunExists Then
SW.WriteLine(sCmdCommand)
My.Settings.AutoRunExists = True
Console.WriteLine(sCmdCommand)
ElseIf My.Settings.AutoRun And My.Settings.AutoRunExists Then
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
SW.WriteLine(sCmdCommand)
Else
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
My.Settings.AutoRunExists = False
Console.WriteLine(sCmdCommand2)
End If
SW.WriteLine("exit") 'exits command prompt window
SW.Close()
SR.Close()
My.Settings.Save()
End Sub
Thanks..
Ps: The commands work fine when entered by hand in the cmd.

Update: Changed this
sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"""
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
and wrote it like this
sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"" /F"
SW.WriteLine(sCmdCommand2)
Now it works fine.

Related

Process.Start() with "manage-bde.exe" crashing in VB.NET

I'm trying to start manage-bde.exe as a new process in VB.net but when it tries to start the proc, Bitlocker crashes. Could anyone please tell me what I'm doing wrong here? This code was converted from C# where it works all day long....
Code:
Private Sub btnLock_Click(sender As Object, e As EventArgs) Handles btnLock.Click
Dim drvSelected As String = cmbDriveSelect.SelectedValue.ToString()
Dim sysDirWithBDE As String = Environment.SystemDirectory + "\manage-bde.exe"
Dim lockStatus As String = String.Empty
' This is the code for the base process
Dim myProcess As New Process()
' Start a new instance of this program
Dim myProcessStartInfo As New ProcessStartInfo(sysDirWithBDE, " -lock " + drvSelected.Remove(2))
'Set Use Shell to false so as to redirect process run info to application
myProcessStartInfo.UseShellExecute = False
myProcessStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myProcessStartInfo
Try
myProcess.Start()
lblDriveLockMsg.Show()
Catch err As Exception
lblDriveLockMsg.Text = err.Message
End Try
'Read the standard output of the process.
lockStatus = myProcess.StandardOutput.ReadToEnd()
If lockStatus.Contains("code 0x80070057") Then
lblDriveLockMsg.Text = "Drive selected is not Bit Locker encrypted"
ElseIf lockStatus.Contains("code 0x80070005") Then
lblDriveLockMsg.Text = "Drive selected is in use by an application on your machine, force dismounting might result in data loss, please check and close any applications using the drive"
Else
lblDriveLockMsg.Text = lockStatus
End If
myProcess.WaitForExit()
myProcess.Close()
End Sub

Using cmd in VB, using commands and receiving output

I need to know, if you could help me, how to insert commands in vb then they run in cmd and i get the output.
I need to do "net localgroup Administradores a58465 /add" and get the error message if there is one.
Solution: `Dim myProcess As Process = New Process
Dim s As String
myProcess.StartInfo.FileName = "c:\windows\system32\cmd.exe"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.Start()
Dim sIn As System.IO.StreamWriter = myProcess.StandardInput
Dim sOut As System.IO.StreamReader = myProcess.StandardOutput
Dim sErr As System.IO.StreamReader = myProcess.StandardError
'sIn.AutoFlush = True
sIn.Write("cls" & System.Environment.NewLine)
sIn.Write("net user" & System.Environment.NewLine)
sIn.Write("exit" & System.Environment.NewLine)
s = sOut.ReadToEnd()
If Not myProcess.HasExited Then
myProcess.Kill()
End If
LB1.Text = s
LB1.Visible = True
sIn.Close()
sOut.Close()
sErr.Close()
myProcess.Close()`
Check out Process.Start. http://msdn.microsoft.com/en-us/library/0w4h05yb(v=vs.110).aspx
Also look for the ProcessStartInfo class, which will give you options on how to kick off an external process.
Console input and output can be made available to your program through ProcessStartInfo.

Installing an application based from the installer path using process.start

Hi how can I install an application for example it was stored in C:\Temp\Filename\Filename\abc.exe and using process.start. Here's my code
Dim wi = WindowsIdentity.GetCurrent()
Dim wp = New WindowsPrincipal(wi)
Dim path = "C:\Temp\Unzip\IDGo800_Minidriver_32.zip\IDGo800_Minidriver_32"
Dim runAsAdmin As Boolean = wp.IsInRole(WindowsBuiltInRole.Administrator)
If Not runAsAdmin Then
' The following properties run the new process as administrator
Dim startInfo As New ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase)
startInfo.FileName = "C:\Windows\System32\cmd.exe"
startInfo.Arguments = "msiexec /i " & path & "\IDGo800_Minidriver_64.msi"" ALLUSERS=1 /qn /norestart"""
startInfo.WindowStyle = ProcessWindowStyle.Normal
startInfo.UseShellExecute = True
startInfo.Verb = "runas"
Dim myProcess As Process = Nothing
Try
myProcess = Process.Start(startInfo)
Do
If myProcess.HasExited Then
Console.WriteLine("Install complete")
End If
Loop While Not myProcess.WaitForExit(1000)
Catch ex As Exception
MsgBox(ex)
End Try
End If
Go the answer already.
startInfo.Arguments = "/c msiexec /i " & path & "\IDGo800_Minidriver_64.msi"" ALLUSERS=1 /qn /norestart"""

How to Copy CMD Results into Textbox on VB.Net Project

I'm working on a Project by VB.net and i'm using CMD to excute commands i want to Know how to copy the Results of the CMD into a textbox on my Main Form
Take a look at the accepted answer here: Get the output of a shell Command in VB.net. That is probably what you need.
Also, here is a version of the code that puts the result into the textbox:
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
txtOutput.Text = sOutput 'txtOutput being the output textbox.
I hope this helps.
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
'Created a file in batch with 2 lines as shown below:
echo off
ipconfig
' save this file as ipconfig.bat or whatever name u want.
' if you didn't want that you could use any command on there like this:
echo off
dir/s
or
echo off
cd\
dir/s
pause

How to run batch commands with dynamic statements?

I am writing code in VB.NET 2.0 and want to run batch commands for FTP using FTP -s:filename command.
I have a Batch file FTP.TXT for FTP Upload. It has the following statements:
OPEN <FPT SERVER IP>
USERNAME
PASSWORD
ASC
CD FOLDERNAME
PUT D:\DRFT000009.TXT FTPDRFTIN.DRFT000009
BYE
I have to dynamically change the filename in the Batch File. Now either I can create a Batch file at runtime and then read it or I got a code to set the input stream of the Process object. But its not working as desired.
This code runs fine but here I read a static batch file FTP.TXT from the computer:
Public Sub FTP4()
Dim psi As ProcessStartInfo
Dim totalerror As String = ""
psi = New ProcessStartInfo()
psi.FileName = "FTP.EXE"
psi.Arguments = " -s:D:\FTP.TXT"
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = True
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = process.Start(psi)
Dim error2 As String = process.StandardError.ReadToEnd()
totalerror = totalerror & error2
process.WaitForExit()
Response.Write(totalerror)
End Sub
But I want somehow to get the FTP done with custom file name for each request. This is what I tried which is not working:
Public Sub FTP5()
Dim totalerror As String = ""
Dim BatchScriptLines(6) As String
Dim process As New Process
process.StartInfo.FileName = "FTP.EXE"
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.Start()
process.BeginOutputReadLine()
Using InputStream As System.IO.StreamWriter = process.StandardInput
InputStream.AutoFlush = True
BatchScriptLines(0) = "OPEN <FPT IP ADDRESS>"
BatchScriptLines(1) = "USERNAME"
BatchScriptLines(2) = "PASSWORD"
BatchScriptLines(3) = "ASC"
BatchScriptLines(4) = "CD SFCD40DAT"
BatchScriptLines(5) = "PUT D:\DRFT000006.TXT FTPDRFTIN.DRFT000006"
BatchScriptLines(6) = "BYE"
For Each ScriptLine As String In BatchScriptLines
InputStream.Write(ScriptLine & vbCrLf)
Next
End Using
Dim error2 As String = process.StandardError.ReadToEnd()
totalerror = totalerror & error2
process.WaitForExit()
Response.Write(totalerror)
End Sub
Please advise how I can get the "FTP -s:filename" command executed in this case. Basically I want to do something similar to single line batch file execution which I not able to do.
Being a simple text file with a clear format, you could rewrite the file passing the parameters that need to be dynamically changed
Public Sub FTP4()
' Of course I assume that, at this point your program knows the exact values '
' to pass at the procedure that rebuilds the file'
PrepareFTPFile("D:\DRFT000006.TXT", "USERNAME", "PASSWORD")
' Now you call the original code.....
Dim psi As ProcessStartInfo
Dim totalerror As String = ""
psi = New ProcessStartInfo()
psi.FileName = "FTP.EXE"
psi.Arguments = " -s:D:\FTP.TXT"
....
End Sub
Public Sub PrepareFTPFile(fileToUpload as String, username as string, userpass as string)
Using sw = new StreamWriter("D:\FTP.TXT", False)
sw.WriteLine("OPEN <FPT IP ADDRESS>")
sw.WriteLine(username)
sw.WriteLine(userpass)
sw.WriteLine("ASC")
sw.WriteLine("CD SFCD40DAT")
sw.WriteLine("PUT " + fileToUpload + " FTPDRFTIN." + Path.GetFileNameWithoutExtension(fileToUpdload))
sw.WriteLine("BYE")
End Using
End Sub