How can I use VB.NET to execute a batch file on another computer? - vb.net

In vb.net 2008 I want to execute a batch file that resides on another computer.
There is no error, but nothing happens.
Here is the code:
Dim pStart As New System.Diagnostics.Process
Dim startInfo As New System.Diagnostics.ProcessStartInfo(serverpath & "\file.bat")
startInfo.RedirectStandardOutput = True
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.UseShellExecute = False
pStart = System.Diagnostics.Process.Start(startInfo)
pStart.WaitForExit()
pStart.Close()

To run a process on a remote computer you can use Sysinternals free psexec.
You can call it with the proper parameters and having the required permissions like you are doing in your sample code.

I've never tried to create a Process using a batch file as the executable. I've always had to use cmd.exe as the program. This has worked for me in the past:
Dim startInfo As New System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " & serverpath & "\file.bat")
The "/c" as part of the argument list tells cmd.exe to exit after the batch file has completed.
If you are going to use RedirectStandardOutput, you really do want to use RedirectStandardError, and then also subscribe to the events of the Process class for catching data on those streams (OutputDataReceived and ErrorDataReceived). Otherwise you will have no way to debug your batch script.

This reads like a permissions problem. I would troubleshoot it that way if you haven't ruled it out yet.
Have you tried running the same batch file from the local computer?
If it is a permissions issue you can solve it either copying the file locally before executing it or map a drive to the remote computer where the file is and then execute the batch file from the new path.
Additionally, we don't really know what's in the batch file that could be causing an issue. I would either post the batch file or if you can't post the batch file use a batch file that you can post. Example a batch file would write the current date time to a file.

Related

using environment variables in excel

So I am using this code in excel to read environment parameters on startup:
Dim ExcelArgs As String
Dim arg As String
ExcelArgs = Environ("ExcelArgs")
MsgBox ExcelArgs
If InStr(UCase(ExcelArgs), "CREO") >= 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("CREO") Then
arg = Split(ExcelArgs, ",")(1)
Call Creo.addNewPartToPartslist(arg)
End If
Application.DisplayAlerts = True
End If
and this line in my batch script:
echo "Launch excel"
Set "ExcelArgs=CREO,DXFWITHOUTDRW
"C:\Program Files (x86)\Microsoft Office\OFFICE16\Excel.exe" /r "%APPDATA%\Microsoft\Excel\XLSTART\PERSONAL.XLSB"
exit 0
The problem is that if i run the batch file once, keep excel open change the excelargs to CREO,wqhatever in batch file and rerun batch file the excelargs, dos not get updated!!!
So my theory is that excel either caches out the environment variable or that if it is being used by one instance the batch script can not set it
link with some info about passing arguments to excel:
https://superuser.com/questions/640359/bat-file-to-open-excel-with-parameters-spaces
Usually excel sees if there is a previous instance running and let this instance handle the file opening.
Is this important? Yes, in your case both requests to open the file are handled by the same excel process.
How does it make a difference? Environment variables are not shared. Each process has it own environment block that is initialized when the process is created (can be a customized block or a copy of the environment of the parent process) and once the environment is created for a process, only this process can change its environment.
In your case, when you start excel the new process gets a copy of the environment block of the cmd process. Later, when you change the cmd environment, the already running excel instance sees no changes in environment and, as the new request to open excel is converted to a request to the previous process, there is not a new process with a new copy of the cmd environment with the changes.
The only way I see to make it work is to force excel to start a new process (that will inherit the changes in the cmd instance) instead of reusing the previous one.
But this depends on the excel version. As far as I know, the 2013 version includes an /x switch to force separate process usage. For previous versions, maybe this question, or this one could help you.
Excel is open
Then i start the batch script:
The it does not open it as read only by default, but prompt me instead, not a big issue but a bit annoying, and it also make it impossible to loop through to run the batch several times for different input parameters.
A bit unsure how I should post this, couldnt paste images in comments, and to edit the the original question, which was how to start excel with enviroment variable in new instance (/x did the trick), but now /r does not work, Should I post as new question and refer to this one or can I leave it as an answer?

VB.NET run BATCH from current directory

I have a windows batch file which I want to execute using vb.net however the batch as well as the VB.net exe that will execute it are run from the cd rom which means tat i want my vb.net to run the batch from current directory (as both will be placed in the current directory, on CD)
How can I achive this?
You need to create an instance of ProcessStartInfo class, set the property WorkingDir and FileName (eventually also the Arguments property) and pass this instance to the Start static method or the Process class.
Dim pi = new ProcessStartInfo()
pi.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath)
pi.FileName = "your_batch_file_name"
pi.Arguments = "arguments that you want to pass to the batch file"
Process.Start(pi)
Keep in mind that if you run from a CD then your current working directory is not writeable

VB code for batch file creation and execution not working

I'm working on some VB code that creates a batch file, starts that batch file, then deletes the file. Everything works fine until the file delete part.
My.Computer.FileSystem.WriteAllText("C:\test.bat", "#echoe off & start firefox http://www.mixedmartialarts.com http://news.google.com/ & exit", True)
Shell("C:\test.bat", AppWinStyle.Hide)
Kill("C:\test.bat")
Use a new thread to continuously check if cmd.exe is running using a while statement. When cmd.exe is no longer running delete the batch file.
Also the best way to open a url is Process.Start("http://www.url.com")

WMI remote process to copy file

Long story short, my application needs to copy a file to a remote target where UNC connections TO the target might not be possible. However UNC connections FROM the target and BACK to the server will always be possible. So the plan was to use WMI to start a remote command shell (cmd) and use the copy command to grab the file. But this doesn't work. The following command works fine when executed manually from the command line of the target:
copy \\192.168.100.12\c$\remotefile.txt c:\localfile.txt
But when I try this same command as part of the InputParameters("CommandLine") it does not work, and produces no error. Note that I can use WMI to connect to the target and remote execution works just fine as I can start calc.exe etc. Here is the code that doesn't work:
Dim ConnectionOptions As New System.Management.ConnectionOptions
With ConnectionOptions
.Username = "target\Administrator"
.Password = "password"
End With
Dim ManagementScope As New System.Management.ManagementScope("\\192.168.100.11\root\cimv2", ConnectionOptions)
Try
ManagementScope.Connect()
MsgBox("connected")
Dim ManagementPath As New System.Management.ManagementPath("Win32_Process")
Dim ManagementOptions As New System.Management.ObjectGetOptions
Dim ManagementClass As New System.Management.ManagementClass(ManagementScope, ManagementPath, ManagementOptions)
Dim InputParameters As System.Management.ManagementBaseObject = ManagementClass.GetMethodParameters("Create")
InputParameters("CommandLine") = "cmd /c copy \\192.168.100.12\c$\remotefile.txt c:\localfile.txt"
Dim OutputParameters As System.Management.ManagementBaseObject = ManagementClass.InvokeMethod("Create", InputParameters, Nothing)
MsgBox("done")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Any ideas why this isn't working? Or does anyone have a better way of doing what I'm trying to do?
Frank you should actually give yourself credit since the method you created is likely the first ever to get around WMI limitations of remote file copy! I did 3 weeks of searching for info/workaround and yours is the only one that works! If I had any points I would vote for your solution...
I created a fully working VBS & WMI script based on your method:
InputParameters("CommandLine") = "cmd /c echo myFTPCommands > c:\ftpscript.txt"
where you replace myFTPCommands as needed with whatever script you want to go into the file c:\ftpscript.bat (or .vbs, .ps1, or whatever you like). If you couldn't fit enough text in the one-line script, then append with the same method using >>. Now, you can use XCOPY, PSEXEC, COPY, or anything else to run the script you just created on the remote host's file system.
Here's my fully fleshed out VBScript using your method. Thanks again. :)
HTH,
Lizz
For security reasons, most methods of programatically connecting to a remote machine and telling it to copy a file to itself from another machine are blocked. One thing that finally worked for me is FTP. Using the above code I can do something like this:
InputParameters("CommandLine") = "ftp -s:c:\ftpscript.txt"
Which causes the ftp commandline utility to run on the remote machine, using c:\ftpscript.txt to get a list of commands from. Since there is no way to copy the ftp script file to the target (again, no UNC connection), I can first do:
InputParameters("CommandLine") = "cmd /c echo myFTPCommands > c:\ftpscript.txt"
And this works :)
UPDATE: Never thought to use XCOPY and it works perfectly:
InputParameters("CommandLine") = "cmd /c echo F | xcopy remotefile localfile"
UPDATE: XCOPY worked yesterday, now it doesn't. NOTHING has changed, so I am at a complete loss for explanation.

How to use Process.Start

I'm using process.Start to run Convert.exe. This program's purpose is to convert all files which are in the exe's folder. So when I normally use it, I copy paste a file into the same folder as Convert.exe and then run Convert.exe. Convert.exe will create a new "converted" file in the same folder.
I'm trying to automate this tedious process. A User selects a file which needs to be converted from FolderA, I copy it to the same folder where Convert.exe is and I'm using process.start(Convert.exe) to run it.
Just to be clear, this "Convert.exe" accepts NO arguments.
The problem: "Convert.exe" is not converting the files in its folder. Instead it's converting all the files in FolderA for some weird reason. I don't know why it picked that folder, I never even try to send it as an argument or nothing.
Here's the code I have:
Dim techInfo As New System.IO.FileInfo(itm.strFilePath)
techInfo.CopyTo(ConverterPath & techInfo.Name)
Dim procInfoConvert As New ProcessStartInfo
procInfoConvert.CreateNoWindow = False
procInfoConvert.Arguments = ""
procInfoConvert.FileName = ConverterPath & "Convert.exe"
Dim procConvert As Process = Process.Start(procInfoConvert)
I did a test where I copy pasted a file into the "Convert.exe" folder and then just run this code:
process.start(ConverterPath & "Convert.exe")
The exe returns nothing, same as if there was no files in the folder.
The only thing I can think of is that when process.Start is run, it copies the file to another location and runs it from there.
Any ideas anyone?
Try this:
procInfoConvert.WorkingDirectory = ConverterPath
That'll set the process up to start in the directory it's contained in, instead of the current directory.