Brendan Tompkins

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Run a .BAT file from ASP.NET

Okay, running .BAT files from ASP.NET using  the System.Diagnostics.Process object and static methods this should be easy, right?  Well, this might work for you, but it certainly won't work on my machines. And after doing lots of reasearh on the issue, it seems that other people are also having problems with this too.  

I wrestled with permissions and all sorts of other stuff, trying to get a simple batch file to run, with no luck.  I tried lauching the bat file directly, launching cmd.exe and calling the bat file using stin. No dice.  It seems that something on my machine was keeping an unattended process from running bat files.  This makes sense, but I was never able to pinpoint what was preventing this, so I came up with a workaround.

I realized that since I could sucessfully run cmd.exe, and send commands to it via stin, I could just open the batch file, and send each line to cmd.exe, which is essentially the same as running a batch file itself.  This technique works great, and I thought I'd pass along the code here.

// Get the full file path
string strFilePath = “c:\\temp\\test.bat”;

// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute =
false;
psi.RedirectStandardOutput =
true;
psi.RedirectStandardInput =
true;
psi.RedirectStandardError =
true;
psi.WorkingDirectory = “c:\\temp\\“;

// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);

// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);

// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;

// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;

// Write each line of the batch file to standard input
while(strm.Peek() != -1)
{
  sIn.WriteLine(strm.ReadLine());
}

strm.Close();

// Exit CMD.EXE
string stEchoFmt = "# {0} run successfully. Exiting";

sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
sIn.WriteLine("EXIT");

// Close the process
proc.Close();

// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();

// Close the io Streams;
sIn.Close();
sOut.Close();

// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));

That's it!   Works like a charm! 

-Brendan


Posted Thu, May 13 2004 7:31 AM by Brendan Tompkins

[Advertisement]

Comments

Lorenzo Barbieri wrote re: Run a .BAT file from ASP.NET
on Thu, May 13 2004 10:36 PM
Perhaps it was a security setting enabled by the IISLockdown Tool?
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Fri, May 14 2004 1:56 AM
Lorenzo,

I don't think so, since we're running server 2003. It could be a security setting, I agree, but I checked all the standard stuff, like permissions and that didn't seem to be the problem.
Chris Kinsman wrote re: Run a .BAT file from ASP.NET
on Fri, May 14 2004 5:01 AM
Did you try cmd /c
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Fri, May 14 2004 5:05 AM
Chris. I tried this, to no effect. It was like something low level was stopping the cmd.exe process from executing a bat file. Strange.
Eric Engler wrote re: Run a .BAT file from ASP.NET
on Mon, May 17 2004 6:53 AM
Can you run a VBScript from ASP.NET? You might try running a VBScript that, in turn, calls a batch. Something like this:

Save this as a name.vbs file and call it from your code-behine:
---------------------------
Const NOWAITFORFINISH = 0
Const WAITFORFINISH = 1
Const HIDEWINDOW = 0
Const SHOWWINDOW = 1

Dim oShell, sCommand
sCommand = "c:\path\batch.bat"
Set oShell = Wscript.CreateObject("Wscript.Shell")
oShell.Run Quote(sCommand), HIDEWINDOW, NOWAITFORFINISH

WScript.Quit(0)

Function Quote(sText)
Quote = Chr(34) & sText & Chr(34)
End Function
Matt wrote re: Run a .BAT file from ASP.NET
on Mon, May 24 2004 10:53 AM
Brendan your code works fine on my Windows 2000 server but on my Windows 2003 server I get the following error message...

Access is denied

at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at System.Diagnostics.Process.Start() at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) at cis2004.resumertf.Page_Load(Object sender, EventArgs e)

Any ideas?

Thank in advance - Matt
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Tue, May 25 2004 7:41 AM
Hi Matt,
Get yourself a copy of FileMon from Sysinternals.

http://www.sysinternals.com/

Run this on the server and look for ACCESS DENIED messages, or some other error. This can get a bit tricky to get working...

I think that the local machine's NETWORK SERVICE account has to have rights to open dirs, etc..
Dan wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 15 2004 8:51 AM
This code works great but I can't get anything to run in the batch file other than a simple net send. What account does the batch file run as? Seem like it doesn't have permissions to delete or copy files.
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 15 2004 8:53 AM
Hi Dan.. See the above comments I left for Matt.
Dan wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 16 2004 12:13 AM
Thanks Brendan,

I already did install FileMon and all it seems to tell me is if the batch file failed or not. Is there some option to see who the batch file ran as? Can you somehow change the account the batch file runs as?

I think I need mine to run as a domain account and not the local system because the files I am working with are not on the webserver.

BTY, great code!!! I don't even know C# and I was able to get it working (Just cut and paste)

Thanks,
Dan
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 16 2004 2:05 AM
Dan,

Thanks! Try TokenMon from Sysinternals. Under 2003, these batch files run as NETWORK SERVICE, AFAIK....
Dan Marth wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 16 2004 2:44 AM
Brendan,
FYI, I am running this on windows 2000 but I will take a look at TokenMon.

Thanks,
Dan
Dan Marth wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 16 2004 1:09 PM
I don't think TokenMon is going to tell me anyting since it reboots the server everytime I have TokenMon running and try to hit the webpage that calls the batch file. Reboots everytime! Any other ideas?

Thanks,
Dan
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 16 2004 1:53 PM
Ha. I've had that happen too. Well, are you sure filemon doesn't tell you the process user? Have you tried granting permissions to the NETWORK SERVICE account on the local box?

Dan Marth wrote re: Run a .BAT file from ASP.NET
on Thu, Jun 17 2004 12:26 AM
This is what I get from filemom....Looks like it might be running as system but if I give system full access......still no dice!!!

343 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Access: All
344 7:21:19 AM System:8 FASTIO_QUERY_BASIC_INFO C:\RCS SUCCESS Attributes: D
345 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
346 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
347 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Directory Access: Traverse
348 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS BUFFER OVERFLOW FileNameInformation
349 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS SUCCESS FileNameInformation
350 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS\V14\DATA66\DATA SUCCESS Options: Open Access: All
351 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA SUCCESS FileBasicInformation
352 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS\V14\DATA66\DATA SUCCESS
353 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS\V14\DATA66\DATA SUCCESS
354 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
355 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
356 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Access: All
357 7:21:19 AM System:8 FASTIO_QUERY_BASIC_INFO C:\RCS SUCCESS Attributes: D
358 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
359 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
360 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS SUCCESS Options: Open Directory Access: Traverse
361 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS BUFFER OVERFLOW FileNameInformation
362 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS SUCCESS FileNameInformation
363 7:21:19 AM System:8 IRP_MJ_CREATE C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS Options: Open Access: All
364 7:21:19 AM System:8 FASTIO_QUERY_NETWORK_OPEN_INFO C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS Attributes: D
365 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS FileEaInformation
366 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS FileStreamInformation
367 7:21:19 AM System:8 IRP_MJ_QUERY_INFORMATION C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS FileObjectIdInformation
368 7:21:19 AM System:8 IRP_MJ_QUERY_SECURITY C:\RCS\V14\DATA66\DATA\HotHits.bat BUFFER OVERFLOW
369 7:21:19 AM System:8 IRP_MJ_QUERY_SECURITY C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS
370 7:21:19 AM System:8 FASTIO_READ C:\RCS\V14\DATA66\DATA\HotHits.bat FAILURE Offset: 0 Length: 4096
371 7:21:19 AM System:8 IRP_MJ_READ C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS Offset: 0 Length: 4096
372 7:21:19 AM System:8 IRP_MJ_CLOSE C:...\\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS
373 7:21:19 AM System:8 FASTIO_READ C:\RCS\V14\DATA66\DATA\HotHits.bat END OF FILE Offset: 79 Length: 4017
374 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS\V14\DATA66\DATA\HotHits.bat SUCCESS
375 7:21:19 AM System:8 IRP_MJ_CLEANUP C:\RCS SUCCESS
376 7:21:19 AM System:8 IRP_MJ_CLOSE C:\RCS SUCCESS
377 7:21:20 AM System:8 IRP_MJ_WRITE* C: SUCCESS Offset: 11112448 Length: 4096
378 7:21:20 AM System:8 IRP_MJ_WRITE* C: SUCCESS Offset: 12288 Length: 4096
379 7:21:20 AM System:8 IRP_MJ_WRITE* C: SUCCESS Offset: 0 Length: 4096

As far as permissions, the everyone domain group has full permissions so that should cover everything but I did try adding the NETWORK account and it didn't work. I couldn't find a NETWORK SERVICE account? Only network.
Dan Marth wrote re: Run a .BAT file from ASP.NET
on Thu, Jun 17 2004 1:34 AM
It looks like the only way it will work is if the batch file is located and runs all commands on the webserver.....that seems to work fine.


Trying to copy, or in my case run a scanlog program on another server, just isn't going to work. Am I correct?

Thanks for all the help,
Dan
Dan Marth wrote re: Run a .BAT file from ASP.NET
on Mon, Jul 5 2004 1:17 AM
Brendan,

Is there anyway I could get a VB version of this code? It is working great but I don't know CSharp and I am having an hell of a time trying to add a drop down box that a user can select a program, hit submit, and the path to the batch file will use the selected program (which is a different path).

So I am going to have 60 different paths to the batch file (which will scan the log files in those directories).

“c:\\Hot Hits\\test.bat”;
“c:\\Classical\\test.bat”;
“c:\\Jazz\\test.bat”;
and so on....I just can get it to work in CSharp (I can't even get a button to work).

Thanks,
Dan
Dan Marth wrote re: Run a .BAT file from ASP.NET
on Tue, Jul 6 2004 1:35 AM
Brenden,

Please disregard, I got it working in CSharp with the help of some nice guy on aspmessageboard. Working great!!!

Thanks,
Dan
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Tue, Jul 6 2004 2:42 AM
Dan - Good. BTW, anyone know of any tools to port from C# to VB?
Dan wrote re: Run a .BAT file from ASP.NET
on Tue, Jul 20 2004 9:31 AM
Brenden,

Is there anyway to get the batchfile to run from a certain directory? I am using some old scanlog program that doesn't always work if it isn't run from the same directory as the log files it is scanning. It seems like it keeps running the batch file from C:\WINNT even if I put a CD in the batch file....see below?


C:\WINNT>CD C:\RCSFiles\HHI

C:\WINNT>scanlog.exe /p /2 /U1 *.HHI

C:\WINNT># c:\RCSFiles\HHI\ScanLog.bat run successfully. Exiting
Dan Marth wrote re: Run a .BAT file from ASP.NET
on Tue, Jul 20 2004 11:53 AM
Sorry about the mis-spelling of your name.
Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Wed, Jul 21 2004 2:11 AM
Dan,

You could try setting this line to your directory, but I'm not positive it works.. I seem to remember having trouble with this.

psi.WorkingDirectory = “c:\\temp\\“;
TrungGap wrote re: Run a .BAT file from ASP.NET
on Thu, Jul 22 2004 11:04 AM
Hi all,

I was having problem executing a batch file on Windows 2003 Server also. The code seems to execute fine on Windows 2000 Server. After playing around with it, I discovered the cause what was causing the problem, but still haven't fully understand why. Anyway, hopefully this little tibbits would help somebody.

This piece of code works perfectly on Win2K Server:

Process myProcess = new Process();
myProcess.StartInfo.WorkingDirectory = Request.MapPath("resources/files");

myProcess.StartInfo.FileName = Request.MapPath("resources/files/build.bat");
myProcess.StartInfo.Arguments = Request["Language"];
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.Start();

myOutput = myProcess.StandardOutput.ReadToEnd();

myProcess.WaitForExit();

However that didn't work on Win2K3 Server. The problem was if any commands in the batch file result in an error, it would exit. Thus in the batch had some del's to make sure the directory is clean, if it didn't delete anything, then it would exit.

To get around this, I had to redirect the standard error:

myProcess.StartInfo.RedirectStandardError = true;

Brendan Tompkins wrote re: Run a .BAT file from ASP.NET
on Thu, Jul 22 2004 12:44 PM
Nice! Thanks!
Mike wrote re: Run a .BAT file from ASP.NET
on Mon, Aug 9 2004 3:18 AM
I am having the same problem! Has anyone found a solution to this? I cannot seem to run a BAT file from ASP.NET, however, running it directly on the server works fine. I am sure it is a permissions issue, but I am not sure how to work around it!

Thanks,
mike
Oliver wrote re: Run a .BAT file from ASP.NET
on Fri, Sep 10 2004 7:46 AM
Having the same problem on Win2k3 server. All directories have full permissions for Everyone (development server :)). Still no success. The .bat file runs fine locally, but does nothing when called from an ASP.NET process.
Any help is greatly appreciated.
Yaheya Quazi wrote re: Run a .BAT file from ASP.NET
on Fri, Sep 17 2004 8:01 AM
You need to give access to IUSR_machinename account Read and Execture permission to cmd.exe also you have to add the following to your web.config file

<identity impersonate="true" />

Thanks!
Serge wrote re: Run a .BAT file from ASP.NET
on Thu, Sep 30 2004 9:53 AM
Brendan,
Thanks for beatifull solution of the problem.

There are no need to read any batch file if you want to run the static command.
Instead of :
while(strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
you can write:

sIn.WriteLine(strCmd);
Where strCmd is any command valid in command prompt. For example:
string strCmd = @"findstr /i /m " + "stringToFind" + " " + strDirectory + "\\*.*";
Return a file list contained "stringToFind".
Serge
Michael wrote re: Run a .BAT file from ASP.NET
on Thu, Oct 14 2004 12:35 PM
Brendan,

Thanks for this ... MS should be shot for making it so difficult to run a simple batch file !

-- Michael
Sunil wrote re: Run a .BAT file from ASP.NET
on Fri, Oct 15 2004 9:41 AM
Try this!! Works fine on W2K

Process myCmd = null;
ProcessStartInfo qOptions = new ProcessStartInfo(@"cmd.exe",@"/k C:/trigger.bat");
qOptions.WindowStyle = ProcessWindowStyle.Hidden;
qOptions.RedirectStandardOutput = false; // set to "true" to enable logging
qOptions.UseShellExecute = true; // set to true to make silent/background

myCmd = Process.Start(qOptions);
myCmd.WaitForExit();
viki wrote re: Run a .BAT file from ASP.NET
on Tue, Oct 26 2004 1:50 PM
Hi,
i was trying to run an application(for e.g., notepad) thru the batch file.But my application hangs, i could see the notepad process running in the task manager, but i could not see the command window or notepad.

If my batch file has del or copy command it works eventhough i could not see the command window.

i have set integrated windows authentication and identity impersonate=true.

could u please shed a light on this
Somayeh wrote re: Run a .BAT file from ASP.NET
on Sat, Oct 30 2004 12:05 AM
hello
i have few questions about this code.
from where this batch file will be executed?i mean does it execute the batch file on the server or on the clients???
i guess it runs on the server..but if i want to have a batch file on the server and i want it to be execute everytime a user send a request to that page..what should i do??
i want the batch file to be executed on the client and do something on the client machin.
Ramesh wrote re: Run a .BAT file from ASP.NET
on Mon, Nov 1 2004 10:15 PM
Thanx I will try and then send another reply
HELP wrote re: Run a .BAT file from ASP.NET
on Wed, Nov 10 2004 12:25 AM
i run process.start("send.bat","net-software test" for net send message "test" for net-software computer . but this code runing in win 2000 server and cant run in win 2003 server
Dariwe wrote re: Run a .BAT file from ASP.NET
on Fri, Nov 12 2004 6:26 PM
I am having issues on winxp sp2. Everything is golden on win2k3 and xpsp1, but on 2 sp2 machines the debugger goes through the function where it is processing the batch file as expected, but the batch file just is not run. Any ideas?
Kien wrote re: Run a .BAT file from ASP.NET
on Wed, Nov 17 2004 3:27 AM
For win2k3 users (like me) suffering with permissions and security, try http://www.eggheadcafe.com/articles/20030703.asp. Just this morning this helped me solve my permissions issue problem with an intranet app.
Jan Landen wrote re: Run a .BAT file from ASP.NET
on Thu, Nov 18 2004 1:26 AM
Thank you Brendan!

It was a bit difficult to handle process standard io redirection to me...

Your code was great help to me to learn the basics....

-Jan
MadRiverLizard wrote re: Run a .BAT file from ASP.NET
on Mon, Dec 13 2004 11:56 PM
How would I modify this so that the process uses command line arguments (c:\bat.bat 2004 1)?
lastdragon wrote re: Run a .BAT file from ASP.NET
on Mon, Dec 20 2004 9:34 AM
none of the above suggestions seem to work
Jason wrote re: Run a .BAT file from ASP.NET
on Sun, Dec 26 2004 3:57 PM
Anyone know how i can make it into a dataset. ie. ability to make each line a record in a virtual datasource? for datagrid use, etc.

Jason
Alex wrote re: Run a .BAT file from ASP.NET
on Mon, Dec 27 2004 10:34 AM
In my case (Win 2003) it was completely permissions problem. I added Everyone with read writ execute permissions and it worked. I am going to take out permissions for everyone and add needed once.
Utkal Sharma wrote re: Run a .BAT file from ASP.NET
on Thu, Jan 6 2005 12:23 PM
Oh boy.... Getting this thing working was like climbing Mount Everest. The code to run through cmd.exe was good but only if the processing which is done in .BAT file is small. In my case it may take 1-2 hour and so the cmd.exe was locking after the Script-timeout for aspx page is reached. In that case we have to make UseShellExecute = true so that it runs in background. Sunil's code(Below) works fine in such case.

Process myCmd = null;
ProcessStartInfo qOptions = new ProcessStartInfo(@"cmd.exe",@"/k C:/trigger.bat");
qOptions.WindowStyle = ProcessWindowStyle.Hidden;
qOptions.RedirectStandardOutput = false; // set to "true" to enable logging
qOptions.UseShellExecute = true; // set to true to make silent/background

myCmd = Process.Start(qOptions);
Marck NOOB wrote re: Run a .BAT file from ASP.NET
on Wed, Feb 9 2005 11:38 AM
Is that possible to someone please write a full aspx page, calling a bat file ??

Please help me, I am very boob! :D
Ivan Belov wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 14 2005 1:45 PM
Thanks for snippet, Brendan! Helped me to solve related problem. Great job! :))
Tim Riester wrote re: Run a .BAT file from ASP.NET
on Wed, Jul 20 2005 8:51 AM
AAAAACCCCKKK!!! I implemented this code in VB.NET on my web app and it runs great on my local web server which is Windows XP. When I move it to the production server which is W2K3, the batch files don't run. I've tried giving the Network Service acct on the machine full control over the batch files and the c drive, but still getting the same results of the batch files not being able to run. Any help would be appreciated. Thanks.

-Tim
Abhi wrote re: Run a .BAT file from ASP.NET
on Mon, Oct 3 2005 6:36 AM
Thanks so much Brendon, it works, and shld say 'finally it works'.
I have spent hours to get this right. Ur logic and technique are very correct. Great work.
But please do mention above ur codes that, the user account under which the ASPNET runs should have full permissions.
I created a new user login, with admin access, and added the identitity impersonate = true in webconfig file
eg : <identity impersonate = "true" userName="SingpostPrintUser" password="singpost"></identity>

It should work now...

regards
abhi
play seven card stud wrote play seven card stud
on Wed, Oct 26 2005 7:16 AM
Sudeep Ghosh wrote re: Run a .BAT file from ASP.NET
on Thu, Feb 9 2006 3:41 AM
Hi,
I am facing the same problem ... it says the following

10060 - Connection timeout
Internet Security and Acceleration Server

--------------------------------------------------------------------------------

Technical Information (for support personnel)

Background:
When the server, while acting as a gateway or proxy, contacted the upstream content server, it did not receive a timely response.



Do I have the work around for this.... I need the connection to stay longer for some back ground process to work.

Please let me know if you have found the solution to this problem.

Thanks in advance

Thanks and Regards
Sudeep
sudeep_aitian@yahoo.com
darktown wrote re: Run a .BAT file from ASP.NET
on Fri, Feb 17 2006 10:14 AM
for those who want the vb -code so badly
it took me 2 mins to convert it..


Dim strFilePath As String = "c:\\temp\\test.bat"

Dim psi As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo("cmd.exe")
psi.UseShellExecute = False
psi.RedirectStandardOutput = True
psi.RedirectStandardInput = True
psi.RedirectStandardError = True
psi.WorkingDirectory = "c:\\temp\\"

Dim proc As System.Diagnostics.Process = System.Diagnostics.Process.Start(psi)
Dim strm As System.IO.StreamReader = System.IO.File.OpenText(strFilePath)
Dim sout As System.IO.StreamReader = proc.StandardOutput
Dim sin As System.IO.StreamWriter = proc.StandardInput

While strm.Peek() <> -1
sin.WriteLine(strm.ReadLine())
End While

strm.Close()

Dim stEchoFmt As String = "# {0} run successfully. Exiting"
sin.WriteLine(String.Format(stEchoFmt, strFilePath))
sin.WriteLine("EXIT")
proc.Close()

sin.Close()
sout.Close()
Tracy Spratt wrote re: Run a .BAT file from ASP.NET
on Tue, Feb 21 2006 9:55 PM
Well, y'all are getting me closer than any other site I have found!

Since I have just a single command to run I am trying to use Serge's suggestion () of writing the command directly to the sIn but am having a bit of trouble.

A hardcoded line works fine, but whenever I try to concatenate a variable, the command string, the command fails.

this works:
sCommand = "psshutdown.exe \\172.31.255.57 -u Administrator"
this works:
sCommand ="psshutdown.exe \\" & "172.31.255.57" & " -u Administrator"
but this fails:
sCommand ="psshutdown.exe \\" & sIP & " -u Administrator"

The WriteLine() has an overload that is supposed to take string.

Any ideas what is happening?

Alternatively, how could I parameterize the bat/cmd file if I used the sIn approach? I tried passing in a SET IP= to the cmd process, but this did not seem to work. Is that a valid approach?

It is silly that something so basic should be so hard!

TIA
Tracy
Tracy Spratt wrote re: Run a .BAT file from ASP.NET
on Tue, Feb 21 2006 10:57 PM
I spoke too soon. Nothing is working on my win 2003 box. I have opened up every security resrtiction I can think of. Rats!
Tracy
Anupam Srivastava wrote re: Run a .BAT file from ASP.NET
on Mon, Feb 27 2006 6:46 AM
Hi Brendan,
Your code is really good. However I'm stuck up at a point. Could you please tell me how do I pass parameters to my batch file?? I have tried giving
psi.Arguments = "123" ( in VB)
The code works fine but my batch file does not show any effect of the passed parameter. My batch file is :
copy h1.txt+h2.txt result%1.txt /B

I want the output as result123.txt but it comes as result%1.txt.

What's wrong with my code? Is it with batch file code or VB code??

Please help.
Anupam
James wrote re: Run a .BAT file from ASP.NET
on Thu, Mar 2 2006 7:36 PM
Wow, just hit this after some searching and hair removing(insert frustration image here). This was by far the most helpful.

Thanks!
vikas kumar wrote re: Run a .BAT file from ASP.NET
on Tue, Apr 25 2006 6:00 AM
this is my question

i m making a project in which i have to run cmd.exe from client machine

i am making project in asp.net using vb.net

if any one help me out please mail me at

viks_mumu@yahoo.co.in
Deepak wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 13 2006 11:40 AM
ok..tried all of the above. this does not work. W2K3 permissions is killing me. Always getting Access Denied error. I even impersonated as xxx who is admin on the server and has full permissions on network.
Any suggestions?
percyboy wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 14 2006 2:32 AM
The codes really work!
but it doesn't support the "goto label" grammer.
Kumar wrote re: Run a .BAT file from ASP.NET
on Thu, Jun 29 2006 12:53 AM
Hi    Yaheya Quazi ,
Thanks ya,we were facing a problem while running .Bat file from local machine throgh ASP.NET application on W2k3 server.But your inputs are great in this issue and we are now able to run the .Bat file on the W2k3 server.


Thanks
Kumar
P. Ravichandran wrote re: Run a .BAT file from ASP.NET
on Fri, Jul 7 2006 5:43 AM
On the above given code is not working properly in the ASPX page.  But is working on the Windows Application.  In ASPX page we need to close the input file before close the process.  Here i give the solution.

ProcessStartInfo ProObj = new ProcessStartInfo("cmd.exe");
ProObj.UseShellExecute = false;
ProObj.RedirectStandardOutput = true;
ProObj.RedirectStandardInput = true;
ProObj.RedirectStandardError = true;

Process proc = System.Diagnostics.Process.Start(ProObj);
StreamReader Sr = File.OpenText(@"E:\test.bat");
StreamReader sOut = proc.StandardOutput;
StreamWriter sIn = proc.StandardInput;

while(Sr.Peek() != -1)
{
         sIn.WriteLine(Sr.ReadLine());
}
Sr.Close(); //We must close it Here not after the process closing
sIn.WriteLine("EXIT");
sIn.Close();
proc.Close();
string result = sOut.ReadToEnd();
sOut.Close();
Response.Write(result);
Ipun wrote re: Run a .BAT file from ASP.NET
on Fri, Jul 7 2006 1:14 PM
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
no code works...............
Morgan wrote re: Run a .BAT file from ASP.NET
on Thu, Jul 13 2006 7:29 AM
In windows 2003 you need to give Execute permissions to cmd.exe for your application pool user.
I also added a
psi.WindowStyle = ProcessWindowStyle.Hidden
but i dont know if its required.
Sashanan wrote re: Run a .BAT file from ASP.NET
on Mon, Jul 24 2006 3:58 AM
This code solved my problem, at least. Thanks for sharing.
JOse wrote re: Run a .BAT file from ASP.NET
on Wed, Jul 26 2006 11:43 AM
dsa
Sara wrote re: Run a .BAT file from ASP.NET
on Wed, Aug 9 2006 3:17 PM
Hi there, I am constantly running in problem for calling a batchfile through asp.net. I read your whole article which apparently helped a lot of ppl but unfortunately not me.
I wrote this 3 lines code in VB.Net and it works perfectly fine.
       Dim proc As New System.Diagnostics.Process
       proc.StartInfo.FileName = "c:\\MyImport\\Convergys.bat"
       proc.Start()
I tried by all means to run through asp.net(working on server)...No luck at all.I load my batch file on server as well but didnt work.I have all permissions as per my Network guy.
It just doesnt call batch file thru asp.net.
I dont know how to give all permissions to ASPNET thing. May be that the problem i am having....Dont know.
My boss is really mad at me and I want some body's help really soon.
I appreciate for your time.
Thanks
Tonny wrote re: Run a .BAT file from ASP.NET
on Mon, Aug 21 2006 7:06 AM
Hi, I'm moving an old conventional .asp application from iis5/w2k to iis6/win2003 and think that i have similar troubles as the .net scenario.

Cmd.exe can start an .exe or .com but when it comes to scripts (.cmd .bat) nothing happens. Not even an error message.

A sample asp code:
 Dim WSH
 Set WSH = server.CreateObject("Wscript.Shell")
 'RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\foo\calc.exe" ' Works perfectly
 RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\foo\calc.cmd" ' Script does not start
 'RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\WINDOWS\SYSTEM32\calc.exe" ' Actually works
 'RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C whoami > C:\foo\hello.txt" ' Writes "NT Authority/NETWORK SERVICE"
 Run = WSH.Run(RunString, 0, false)

I'll probably end up writing a .exe that does what the .cmd script does.
Tonny wrote re: Run a .BAT file from ASP.NET
on Tue, Aug 22 2006 4:08 AM
Hi again.

It turns out that my colleague had the exact same cmd.exe problem as me and i suspect the same goes for .net. Microsoft sended a trace/debug tool to him and asked him to create some logs. Appearantly this cmd.exe behavior isn't intended.

Workaround 1:  Make the webuser member of local administrators
Workaround 2:  Call a .vbs instead and let it call the cmd.exe

Of course don't use solution 1 for anonymous access (IUSR, IWAM, Network service). Here's a sample for my .vbs workaround:

Dim WSH, ErrorLevel
Set WSH = CreateObject("Wscript.Shell")
RunString = "C:\WINDOWS\SYSTEM32\CMD.EXE /D /C C:\foo\MyScript.cmd" & _
" """ & wscript.arguments.item(0) & """" & _
" """ & wscript.arguments.item(1) & """" & _
" """ & wscript.arguments.item(2) & """" & _
" """ & wscript.arguments.item(3) & """"
ErrorLevel = WSH.Run(RunString, 0, false)
Set WSH = Nothing
Wscript.Quit ErrorLevel

Hope this can be of some inspiration to the asp.net problem.
Dennis wrote re: Run a .BAT file from ASP.NET
on Mon, Aug 28 2006 9:27 AM

Passing parameters to a batch file

This is the first thing that came to my mind after running the cool solution.

the trick was devised from the code itself: if you can write to input stream  the command line from the batch file, why not write a command with a batch file  + parameters. I e

 System.IO.StreamWriter sIn = proc.StandardInput;

       // Write a line with batch file and parameters to standard input

       sIn.WriteLine("build.bat "  +  param);

...

Thus a bat file with

dir %1

command can be controlled with parameters (/b /s /? etc)

http://localhost:3206/VisualStudio/Default.aspx?param=/b

The result is

C:\_dennis\VisualStudio>dir /b

App_Data

build.bat

Default.aspx

Default.aspx.cs

Dino wrote re: Run a .BAT file from ASP.NET
on Sat, Sep 9 2006 9:03 AM

Can someone tell me if the same issue exists with classic ASP under SBS2K3? And perhaps provide an example?

I am trying to run commands executables and batch files etc from classic asp and seem to be getting the same issues "Access denied" etc, I've tried the IUSR_ permissons thing but not had any luck yet, will have another go, and alter webconfig as well (first time i read that advice was here ;).

Actually one problem is I don't seem to be able to run a batch file from the command line at all? I can create it, click it in file explorer, and it runs fine, but if I open a command prompt, navigate to that directory, and type its name I get " 'test.bat' is not recognized as an internal or external command, operable program or batch file." So what going on here? Why cant I just run the batch file from the command line?

Many thanks for any help.

Dino wrote re: Run a .BAT file from ASP.NET
on Sat, Sep 9 2006 9:52 AM

Ok have the batch file running from command line now! but having made the relevant IUSR permission changes, I can access the batch file from asp but it does not actually execute. For example i have a simple batch file that just echos some text to a text file (IUSR has read execute permisssions to the batch file and cmd.exe and full permissions to the text file). If intentionally use the wrong batch filename i get the appropriate error, now with teh correct batch file name i get no error, but equally no execution, nothing appears in the text file?

Samir wrote re: Run a .BAT file from ASP.NET
on Tue, Sep 12 2006 2:30 PM

Dino, did you resolve it yet? I have the same problem...

Gear wrote re: Run a .BAT file from ASP.NET
on Wed, Sep 20 2006 2:17 PM

God, I've been struglying with it since 2 days now.

I did everything imaginable to make ASP.NET 2.0 execute a simple batchfile and I always get Access Denied

I tell you,  IIS, ASP.NET ACCOUNT, Impersonation, URLSCAN, Permissions etc...etc...etc, all you can imagine have been tested.  So what else now

Windows 2000 server running IIS5.0

ASP.NET 2.0.50727

C# app which uses Process.Start() to start the batch file

Always get Access Denied.

BUT.......... I can copy files to the directory, Create file to the directory, can do a lot of things but not executing a simple batch file

Yeah right

geardoom3@gmail.com

Mahesh wrote re: Run a .BAT file from ASP.NET
on Fri, Sep 22 2006 7:55 AM
Gennady wrote re: Run a .BAT file from ASP.NET
on Wed, Sep 27 2006 11:38 PM

When ASP.NET is running under IIS 6 (Windows 2003) in native mode, the IIS 6 process model is used and settings in this section (<processModel from %windir%\Microsoft.NET\Framework\v1.1.4322\CONFIG\ machine.config) are ignored.  Please use the IIS administrative UI to configure things like process identity and cycling for the IIS worker process for the desired application.

If you change it to Local System for Application Pull in IIS and for "ASP.NET State Service" service account in services you will be able to run anything from ASP.NET

Maurilio Martini wrote re: Run a .BAT file from ASP.NET
on Tue, Oct 10 2006 4:15 AM

Great Stuff!! [}}:-))

Mick T wrote re: Run a .BAT file from ASP.NET
on Thu, Nov 16 2006 4:03 PM

I've been messing with this sort of thing so I can remotely do things like opening an MP3 or running an EXE. What I would like is to be able to have a window pop up on my screen (the servers screen) and be able to send keys to it through ASP.Net but the process belongs to the ASPNET user not the user logged in. I'm using XP SP2.

Is there any way for me to either log on as the ASPNET user or have the process belong to the logged in user (or some other way).

Thanks

Mick

Lynda wrote re: Run a .BAT file from ASP.NET
on Mon, Dec 4 2006 2:32 PM

The information here is great.  I used it to successfully run a bat file from CMD.exe for both XP Pro and Server 2003.  I am having one issue and would appreciate anyone's thoughts and suggestions on how to resolve.

My web application runs a package software which can be started from command line.  I saved this line as my bat file.  When I double click the bat file on Server 2003, the package runs indicated with the creation of an output file.  When I run it from my web app, the name of the software shows in Task Manager but the output file is not created. When I run my web app on my XP pro device native (http:\\localhost\...), the process works and the output file is created.  I have Visual Studio installed on my XP Pro device.

To confirm that the process is working on Server 2003, I wrote another bat file that copies one file to another.  I ran that bat file from web application on Server 2003 and the copied file is created.  It appears that this code is working on Server 2003.

What would cause this to not work on Server 2003 for that package software?  Any suggestions on where to look or how to resolve this issue would be appreciated.

Thanks!

DINESH wrote re: Run a .BAT file from ASP.NET
on Fri, Dec 15 2006 12:31 AM

DEAR ALL,

I HAVE WRITTEN A CODE IN VB TO EXECUTE AN EXE FILE THE CODE IS AS FOLLOWS

       'Create process to create a user in Linux machine

       Dim myProcessStartInfo As New ProcessStartInfo()

       myProcessStartInfo.WorkingDirectory = "C:\"

       myProcessStartInfo.FileName = "c:\plink.exe"

       myProcessStartInfo.RedirectStandardOutput = True

       myProcessStartInfo.RedirectStandardInput = False

       myProcessStartInfo.UseShellExecute = False

       myProcessStartInfo.Arguments = "-pw " & Login1.Password & " " & Login1.UserName & "@192.168.116.77 ls "

       'Start the process

       Dim myProcess As Process

       Dim myStreamReader As IO.StreamReader

       myProcess = Process.Start(myProcessStartInfo)

       myProcess.WaitForExit(2000)

       If myProcess.HasExited Then

           e.Authenticated = True

           myStreamReader = myProcess.StandardOutput

           Dim myString As String = myStreamReader.ReadToEnd

           Label1.Text = myString

           Session("UserName") = Login1.UserName

           Session("Password") = Login1.Password

           myStreamReader.Close()

       Else

           e.Authenticated = False

           Label1.Text = "Could Not Completed in Allocated Time Slot !!!"

           myProcess.Kill()

       End If

       myProcess.Close()

I am Executing a plink.exe file this works 100% perfectly in "View in Browser" mode but wen i execute it like "http://localhost/.....aspx" it says "Could Not Completed in Allocated Time Slot !!!" This is really really frustrating can someone please help.

Further I have added <identity impersonate="true"/> in my web.config and in IIS document Security I have ticked allow anonymus access and given ASPNET Administrator level authority What Else I can do other Than hang my self !!!

Naags wrote re: Run a .BAT file from ASP.NET
on Sat, Dec 16 2006 3:45 AM

Hi,

i was trying to run an application(for e.g., notepad) thru the batch file.But my application hangs, i could see the notepad process running in the task manager, but i could not see the command window or notepad.

If my batch file has del or copy command it works eventhough i could not see the command window.

i have set integrated windows authentication and identity impersonate=true.

could u please shed a light on this

Code Smith wrote re: Run a .BAT file from ASP.NET
on Sat, Dec 16 2006 3:47 AM

Hi,

i was trying to run an web application(for e.g., notepad) thru the batch file which developed using C#, asp.net.But my web application hangs, i could not see the command window or notepad when running from IIS Virtual Directory (http://localhost/app/filename.aspx).

i have set integrated windows authentication and identity impersonate=true.

could u please shed a light on this

Thanks

Dinesh wrote re: Run a .BAT file from ASP.NET
on Sun, Dec 17 2006 9:57 PM

Hi Guys,

I found an answer that would help most of you I think, It works for me. You give the following command before starting the process.

Dim _password As New System.Security.SecureString

Dim password As String

password = <Your Password As String>

'This Part is important cause you cannot directly assign string variable to security string

       For Each c As Char In password

           _password.AppendChar(c)

       Next

       Dim myProcessStartInfo As New ProcessStartInfo()

       myProcessStartInfo.LoadUserProfile = True

       myProcessStartInfo.LoadUserProfile = True

       myProcessStartInfo.UserName = "Administrator"(Any User Name in Server)

       myProcessStartInfo.Password = _password

Topcat wrote re: Run a .BAT file from ASP.NET
on Wed, Jan 3 2007 3:43 PM

Good job! this is exactly what I needed.

Jeff wrote re: Run a .BAT file from ASP.NET
on Fri, Jan 5 2007 12:11 AM

OK, one native difference in 2000 vs. 2003 server is that in 2000 the o/s allowed

you to recognize c:\ g:\ , etc. - whatever logical drive mapping, BUT

in 2003 Server, the difference is that, unless you use very specific interactive

login credentials, you must use UNC path instead of "logical drive mapping."

So.. fo processes without discreet 'interactive context' (like when jsmith logs

in interactively), try using \\servername\path\file.bat

and when piping out use \\servername\path\file.bat > \\servername\path\file.txt

"path" being a valid UNC path of course.

That is one big problem I have seen.

Cheers!

Jeff

Zen wrote re: Run a .BAT file from ASP.NET
on Fri, Jan 12 2007 10:49 AM

I hope this helps, it worked for me. I can now execute batch and exe. All I did was create a new application pool and assign it Local System as user and waaalaaa......

Check this article out.

http://west-wind.com/weblog/posts/2153.aspx

John wrote re: Run a .BAT file from ASP.NET
on Thu, Jan 25 2007 10:25 AM

I used a same code to call a bat file remotely I don't received any  error, but the bat file do not execute !!!

I used

objProc.StartInfo.WorkingDirectory= "\\<someIPAdderss\\c$"

objProc.StartInfo.FileName ="\\<someIPAdderss>\\c$\Test.bat"

redsv wrote re: Run a .BAT file from ASP.NET
on Thu, Feb 1 2007 11:58 PM

Hi All,

In my .bat file i have a command line which returns some sysout.

that sysout i want to capture from vb.net.

is it possible?

if i use below code, it is returning only the commanline which is there in bat file.

Dim listfiles As System.Diagnostics.Process

listfiles = System.Diagnostics.Process.Start(psi)

Streamreader = listfiles.StandardOutput

please help

Ray wrote re: Run a .BAT file from ASP.NET
on Tue, Feb 27 2007 8:04 AM

I am trying to run the batch file which contains

(CScript LCSAddACEs.wsf /usersfile:userfile.txt /acesfile:acesFile.txt>PrintFile.txt).

This does adding the domain/domains to the specifed user.

1.with windows application ran successfully.added domain to specified user.

2.With web application(ASP.NET) not ran sucessfully.not able add domain to specified user.

Anybody has idia on this? If need more information on this issue let me know i will provide

Thanks in advance.

Ray

Yinon wrote re: Run a .BAT file from ASP.NET
on Sat, Mar 3 2007 6:53 AM

10x a lot ... finaly it works ... :))

W@nderlust wrote re: Run a .BAT file from ASP.NET
on Fri, Mar 9 2007 10:00 AM

OK, for the ones having troubles running an EXE OR BAT on an ASP.NET, in W2k3, here is what worked for me:

1) In the IIS, right click on the Application Pool where you have the website running, select Properties, and then under "Identity tab", change the security account to "LOCAL SYSTEM" (where says Predefined).

2) In ASP.NET use this code:

       ProcessStartInfo psi = new ProcessStartInfo(@"C:\TheExe.exe");

       psi.UseShellExecute = false;

       psi.RedirectStandardOutput = true;

       psi.RedirectStandardInput = true;

       psi.RedirectStandardError = true;

       psi.WindowStyle = ProcessWindowStyle.Hidden;

       psi.WorkingDirectory = @"C:\TheWorkingDirectory";

       psi.Arguments = @"The Arguments For The Exe";

       Process proc = Process.Start(psi);

(Of course changing the name of your exe, working directory, and arguments).

Hope this helps. If not, write something to a DB and make a windows service to check the DB, and if the DB changed, then fire your exe from the C# service. That was PLAN B!! :D :D :D

Enjoy.

CryyL wrote re: Run a .BAT file from ASP.NET
on Fri, Mar 9 2007 11:40 AM

It worked for me! Thanks W@nderlust! Good post.

snickss wrote re: Run a .BAT file from ASP.NET
on Tue, Mar 27 2007 9:40 AM

I am having problems with running this code on W2K3. I was getting Access Denied errors, but after adding permissions for IUSR to the bat file the error now is "Could not read key from registry". I tried to track down the registry key the bat is trying to access, but there were hundreds of them.

Any help would be appreciated.

Thanks.

MarkyTheMark wrote re: Run a .BAT file from ASP.NET
on Mon, Apr 2 2007 10:11 AM

W@nderlust you're a saviour! I have spent hours on this to no avail!

seems so easy when you thinkabout it,but I still can't get my batch file to run funcions cross-servers?

any further thoughts anyone?

thanks all

Shashanka wrote re: Run a .BAT file from ASP.NET
on Wed, Apr 11 2007 6:29 PM

Hi,

  I used this

actually the batch file is not opening but it shows that it is running

to open what should i do ??

i got this type of message

Microsoft Windows 2000 [Version 5.00.2195]

(C) Copyright 1985-2000 Microsoft Corp.

C:\WINNT>\\gmindia\Goldmine\gmw6.exe

C:\WINNT># C:\Documents and Settings\idml\Desktop\a.bat run successfully. Exiting

C:\WINNT>EXIT

  Emp Name :

Shashanka wrote re: Run a .BAT file from ASP.NET
on Thu, Apr 12 2007 10:23 PM

Hi ALL,

Thanks

It is solved

<B><a href="http:\\www.website.com\flower\shashanka.exe">Click here for the exe/bat file called A.</a></A></B>

Regards

Shashanka

Rob wrote re: Run a .BAT file from ASP.NET
on Tue, May 1 2007 10:01 AM

I don't know why all the other 15000 different ways to run a batch file I've seen out there don't work, but this one did the trick.  Thanks!

Vinayak.N wrote re: Run a .BAT file from ASP.NET
on Fri, Jun 1 2007 12:15 AM

iam trying for past one week to run an exe from ASP.NET. it start an process as Network service but not as an administrator. if i double click on exe it run the process as administrator and exe works. i tried all the ways like runnig as exe, as bat file, using impersonation passing user name and password. do any one have solution.

ananda wrote re: Run a .BAT file from ASP.NET
on Sat, Jun 2 2007 1:29 AM

Hi,

I want to execute the command

mysql -u root -p  databasename > filename.sql

in order to take the backup of the mysql database

how can i do this

Rak wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 5 2007 7:48 AM

Nice bit of code there Brendan - I now finally figured out why I can't create my Oracle database on IIS through a web application, output provied a lot of information!

Using the following code I had before, I was able to execute the batch without any problems:

ProcessStartInfo pInfo = new ProcessStartInfo(@"C:\createdb.bat");

pInfo.WindowStyle = ProcessWindowStyle.Normal;

pInfo.UseShellExecute = false;

int ExitCode = -1;

try

{

   Process process = Process.Start(pInfo);

   while (process.HasExited == false)

   {

       process.Refresh();

       Thread.Sleep(1000);

   }

   ExitCode = process.ExitCode;

   process.Close();

}

catch (Exception exp)

{

   // Error

}

Imran wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 5 2007 10:59 AM

Just i want to pass date as parameter to my batch file.

Below is my code:

psi.Arguments = "3/13/2007";

In my batch file

XCOPY C:\Sample\EdFi c:\Imran\Build /D:%%1

The files are not copied to destination folder.

Can anyone help on this.

larry miller wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 5 2007 7:05 PM

how can i get the output into a different window so as not to disturb the current page they are on.  (using asp.net, c#)

sowmya wrote re: Run a .BAT file from ASP.NET
on Mon, Jun 18 2007 2:43 AM

how can i give the remote machine's path as working directory???

Anju wrote re: Run a .BAT file from ASP.NET
on Sun, Jun 24 2007 9:28 AM

will somebody tell me how to pass arguments while executing vbs especially while using the following format Dim strFilePath As String = "c:\\temp\\test.bat"

Dim psi As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo("cmd.exe")

psi.UseShellExecute = False

psi.RedirectStandardOutput = True

psi.RedirectStandardInput = True

psi.RedirectStandardError = True

psi.WorkingDirectory = "c:\\temp\\"

Dim proc As System.Diagnostics.Process = System.Diagnostics.Process.Start(psi)

Dim strm As System.IO.StreamReader = System.IO.File.OpenText(strFilePath)

Dim sout As System.IO.StreamReader = proc.StandardOutput

Dim sin As System.IO.StreamWriter = proc.StandardInput

While strm.Peek() <> -1

sin.WriteLine(strm.ReadLine())

End While

strm.Close()

Dim stEchoFmt As String = "# {0} run successfully. Exiting"

sin.WriteLine(String.Format(stEchoFmt, strFilePath))

sin.WriteLine("EXIT")

proc.Close()

sin.Close()

sout.Close()

i have been trying to execute a vbs which creates subdomain thru asp.net but its not working i am using windows 2003 and iis 6 ..

The vbs works when executed thru cmd prompt but not thru asp.net .

Please suggest a solution

thank u

jagadish d wrote re: Run a .BAT file from ASP.NET
on Mon, Jun 25 2007 6:03 AM

am try to run a series of batch files through a web application. For each batch file to run there are seperate functions. Below posted is the function for to run one batch file. After one batch file is executed the thread exits with an exception without executing next code in the page. I think internally the page execution end occurs. How to avoid this?

i., the thread exit with this exception

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll

Any help would be appraciated.

<P>

try

{

string strFilePath =  + "c:\\test\\test.bat";

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(strFilePath);

psi.UseShellExecute = false;

psi.RedirectStandardOutput = true;

psi.RedirectStandardInput = true;

psi.RedirectStandardError = true;

psi.WorkingDirectory = "c:\\inetpub\\wwwroot\\test\\bin\\";System.Diagnostics.Process proc = new System.Diagnostics.Process();

proc.StartInfo = psi;

proc.Start();

while (!proc.HasExited)

{

proc.Refresh();

Thread.Sleep(1000);

}

proc.Close();

}

catch (Exception ex)

{

}

Sam wrote re: Run a .BAT file from ASP.NET
on Tue, Jun 26 2007 6:14 AM

This looks great and this is exactly what i need but...

Could someone please tell me how to use this code?

do i need to compile it? what software do i need for it.

(i have IIS up and running and have knowledge of building webpages)

The last time i programmed something was way back in time.

(borland C and pasqal :- )

Thanks in advance !!!

Ian wrote re: Run a .BAT file from ASP.NET
on Thu, Jun 28 2007 10:53 AM

before you waste time check this post out, it really a good starting point.

support.microsoft.com/default.aspx

Ian wrote re: Run a .BAT file from ASP.NET
on Thu, Jun 28 2007 10:54 AM

   try this for instance

protected void Page_Load(object sender, EventArgs e)

   {

       string filepath = Server.MapPath("me.bat");

       Response.Write("cmd.exe /c " + filepath);

       System.Diagnostics.Process.Start("cmd.exe", "/c "  + filepath );

   }

santosh wrote re: Run a .BAT file from ASP.NET
on Wed, Jul 18 2007 2:15 AM

my bat file appears to run fine as the output lines shows each line of my bat file being executed. However, i don't get the result that i get normally while executing the bat file manually. The bat file simply dumps a mysql database. I have provided full control to the application. Can anyone help?

santosh wrote re: Run a .BAT file from ASP.NET
on Thu, Jul 19 2007 1:25 AM

it works fine now. the application did not have the permission to write the dump file on the specified location.

Anyway, does anybody know how I can pass arguments to the bat file.

Raj wrote re: Run a .BAT file from ASP.NET
on Fri, Jul 20 2007 6:24 AM

Hi I am trying to start bat file which is executed properly in .net development server and not in iis

can any one suggest the best way.

i tried all the above process, codes are fine but things are not working properly in iis. i am using windows xp professional

thanks

Raj

Everyone should have at least one Gotchi! » Executable mittels ASP.net ausf??hren wrote Everyone should have at least one Gotchi! &raquo; Executable mittels ASP.net ausf??hren
on Sun, Jul 22 2007 5:56 AM

Pingback from  Everyone should have at least one Gotchi!  &raquo; Executable mittels ASP.net ausf??hren

Cheng Zhang wrote re: Run a .BAT file from ASP.NET
on Sat, Jul 28 2007 1:15 PM

Thanks so much for your sharing! It really works. It rocks!

Rajani Karthik wrote re: Run a .BAT file from ASP.NET
on Wed, Aug 1 2007 6:34 AM

Hey.......I got it. thanks everyone

Ryan wrote re: Run a .BAT file from ASP.NET
on Fri, Aug 3 2007 2:13 PM

Thanks W@nderlust!!

margiex wrote 在asp.net中调用process.start执行程序
on Tue, Aug 14 2007 9:50 AM

试了N次,发现不行,原来需要设置运行iis进程用户的权限,比较麻烦,MS的站点上有一篇说明:support.microsoft.com/.../555134%E5%86%8D%E6%89%BE...

Mark wrote re: Run a .BAT file from ASP.NET
on Tue, Sep 4 2007 10:41 PM

The example from W@nderlust works for me. I did not try the other examples.

Thanks W@nderlust

RIck wrote re: Run a .BAT file from ASP.NET
on Tue, Oct 9 2007 2:57 PM

I have tried all of the above examples and I am still having problems executing a batch file on Server 2003. Everything works fine on my local machine but when I move it to the server I don't receive anything when I click on a link to call the batch file. Any other suggestions? This information has been very helpful

sharad wrote re: Run a .BAT file from ASP.NET
on Wed, Oct 17 2007 4:49 PM

it seems like all the above solutions work when you the ASP.NET application running on the server and you access it locally.

I want to to run a exe when the user navigates to a particular screen or clicks on a button. Is there anyone who can help me out ?

jyu wrote re: Run a .BAT file from ASP.NET
on Tue, Oct 23 2007 12:36 PM

I am running Window XP Pro SP 2

The code works fine if i use VS 2005 built in development web server, however, if I were to run it under IIS 5.1, the code will not work, as i see in the task manager that the cmd.exe is executed by ASPNET, but nothing happens.

I am trying to use the .bat to generate some XML for me.  using VS 2005 built in web development server, my XML are generated when my .aspx is executed.  

But under the IIS 5.1  it doesn't generate the XML for me.  

I did impersonate to an admin account and gave full permission to to access cmd.exe and the folder that contains my aspx page.

Any help is apperciated.  Thank you.

kk wrote re: Run a .BAT file from ASP.NET
on Fri, Oct 26 2007 1:33 AM

Hi, I tried all the examples above. But i am not able to run the bat file. im using Win xp.

Jacob wrote re: Run a .BAT file from ASP.NET
on Mon, Nov 19 2007 10:00 AM

If I hadnt found this site i might have killed myself

Tharaka wrote re: Run a .BAT file from ASP.NET
on Fri, Nov 30 2007 10:23 PM

i have one problem,i have create batch file its working sucessfully but another machine access by my machine it doesn't work ,probelm is workingdirectory, i wont to know about how to give path in working directory using IP ADDRESS

Ronald_from_Colombia wrote re: Run a .BAT file from ASP.NET
on Thu, Jan 17 2008 11:48 AM

Hi Brendan! Thanks a lot for giving me the information content in this article. This really helped me!

Peter kellner wrote re: Run a .BAT file from ASP.NET
on Thu, Feb 14 2008 10:07 PM

Hi and thanks,

When I run this in debug mode, it works, but when I run it without debug, it leaves the command window open and hangs.  I'm running several commands in a row. it's just the third one that hangs.

Thanks, -Peter at Peterkellner dot net.

Kel wrote re: Run a .BAT file from ASP.NET
on Tue, Mar 4 2008 5:57 PM

support.microsoft.com/.../221081

It's been a while since I addressed a similar issue, but as I recall I wanted to run the Windows Media Encoder VB Script (WMCmd.vbs) with customized parameters from a IIS sever via PHP, essentially creating a transcoding VOD media server.  

IIRC, the above article was key to resolving the ACCESS DENIED problem between IIS and VBS.  Ultimately I had to use PSEXE to launch "Cscript.exe wmvmd.vbs 'filename'"  so that PHP would regain control immediately instead of waiting for the vbs script to finish, which could be hours for a movie.

I'm currently trying to figure out how to use a remote UNC filename (\\remote_machine\share\filename) with the script instead of local filename.  

Krishna wrote re: Run a .BAT file from ASP.NET
on Wed, Mar 5 2008 8:54 AM

This code piece is really great, but what if our bat file itself requires paramters runtime?

my requirement is that its a file copy over internet and hence i have to pass the folder selected, currently in the bat file i have it as %1, %2 like that when executed from command prompt it has no issues, but i am not able to pass the same from here

thanks

kite wrote re: Run a .BAT file from ASP.NET
on Tue, Mar 11 2008 9:05 AM

thanks

Nick wrote re: Run a .BAT file from ASP.NET
on Tue, Apr 15 2008 4:18 PM

Just want to say thank you all here!

My co-worker write a web app that have some call to bcp.exe, one server working fine but after move to another server it always get access denied error.

My instinct tell me that BCP.exe is not running, so I start to check the necessary permission for running BCP.exe, no finding…

Second thought is the process never start properly, so I google system.diagnostics with access denied, turns out lot's of developer have the same pain as me…

Someone said that's a windows 2003 thing and on windows 2000 it work just fine, but our server are both 2003...

After comparing machine.config file, .net configuration runtime policy, identity impersonate value,  etc.  still no clue.

Finally after go through this thousand lines blog, I got the tip to check cmd.exe.

It turns out the new server do not have properly permission setup on cmd.exe (the web app pool use a domain account identity, this account does not have any permission granted on cmd.exe)

Andrei wrote re: Run a .BAT file from ASP.NET
on Tue, May 6 2008 11:08 AM

Your problems will be solved without any complications if you set the application pool to run under LocalSystem. When running the batch it will try to impersonate another user and this is the only accound that has this right.

Marius Lardizabal - IT Consulting » Blog Archive » Running a Shell Script via ASP.Net wrote Marius Lardizabal - IT Consulting &raquo; Blog Archive &raquo; Running a Shell Script via ASP.Net
on Thu, May 8 2008 2:27 PM

Pingback from  Marius Lardizabal - IT Consulting  &raquo; Blog Archive   &raquo; Running a Shell Script via ASP.Net

Krishna wrote re: Run a .BAT file from ASP.NET
on Fri, May 9 2008 3:11 PM

this does not seem to be working on win2k3 SP2. I checked this and it is failing, below is mentioned the entire gist:

I have a requirement of doing some copy commands over the network servers (over a same domain)using a web based GUI, hence designed it using aspx form and simply calling cmd.exe by instantiating a new Process, all permissions have been given administrative rights both under the IIS level and also under the NTFS level. I can see from task manager (in server) that cmd.exe gets launched but then it shows a message - "The application failed to initialize properly (0xc0000142). Click on OK to terminate the application." in server because of which copy commands are not getting executed. Pasted below is the code part of it. This is being developed on Windows 2003 SP2

Assistance will be highly appreciated.

Beleaguered programmer....

protected string StartProcess(string Arguments, string WorkingDir)

   {

     // Start the process

     string strDomain = "<PUT_UR_DOMAIN>";

     string strUserName = "PUT_UR_USERNAME";

     string strPassword = "PUT_UR_PWD";

     string strReturnMesages = "";

     try

     {

       Process procMapPath = new Process();

       procMapPath.StartInfo.WorkingDirectory = WorkingDir;

       procMapPath.StartInfo.UseShellExecute = false;

       procMapPath.StartInfo.RedirectStandardOutput = true;

       procMapPath.StartInfo.RedirectStandardInput = true;

       procMapPath.StartInfo.RedirectStandardError = true;

       procMapPath.StartInfo.FileName = "cmd.exe";

       procMapPath.StartInfo.LoadUserProfile = true;

       procMapPath.StartInfo.CreateNoWindow = false;

       procMapPath.StartInfo.Domain = strDomain;

       procMapPath.StartInfo.UserName = strUserName;

       procMapPath.StartInfo.Password = new System.Security.SecureString();

       for (int x = 0; x < strPassword.Length; ++x)

       {

         procMapPath.StartInfo.Password.AppendChar(strPassword[x]);

       }

       procMapPath.StartInfo.Arguments = "/C " + Arguments;

       procMapPath.Start();

       while (!procMapPath.HasExited)

       {

         strReturnMesages = "Still Copying...";

         System.Threading.Thread.Sleep(2000);

       }

       procMapPath.Close();

       strReturnMesages = "Files Copied..." + Environment.NewLine;

     }

     catch (Exception ex)

     {

       strReturnMesages = ex.Source + " --- " + ex.Message + Environment.NewLine;

     }

     return strReturnMesages;

   }

one more thing i have also tried giving cmd.exe by giving full permissions to "Everyone" in the server, still of no use.

Not sure how come examples mentioned are working for them:

www.velocityreviews.com/.../t117223-run-cmdexe-from-aspx-page.html

forums.microsoft.com/.../ShowPost.aspx

Also tried System.IO and with associated File.Copy commands, there is no provision for supplying user name and password with these calls, hence this also fails across network folders, however I understand when provided as UNC conventions these should work, but then again same problem would arise when trying to map the required folder.

please suggest alternatives...

run a bat file without permission wrote run a bat file without permission
on Mon, May 12 2008 8:50 PM

Pingback from  run a bat file without permission

sandeep wrote re: Run a .BAT file from ASP.NET
on Wed, Jun 11 2008 11:39 AM

Thanks Yaar!

You saved my lots of time.

Harinath Mallepally wrote re: Run a .BAT file from ASP.NET
on Thu, Jun 19 2008 2:36 AM

Hi, your approach is working fine. I used domain user credentials (who is an admin in the win 2k3 machine) to app pool and its working fine.

Nimish Agarwal wrote re: Run a .BAT file from ASP.NET
on Sat, Jun 21 2008 4:34 PM

Hi, I have tried implementing the code given above by Bredan Tompkins.

My task is that I have to transfer files from one webserver to another web server every 6 hours.

When I am executing the copy command through command prompt the files are getting transferred from one webserver to another.

But when I try to execute the same command through the above code sample. It is not copying any files to the other web server. The results says: 0 file(s) copied.

Both the servers are on the same domain.

It is really important for me to transfer files to other web server for syncronization. Any help would be greatly appreciated.

Thomas wrote re: Run a .BAT file from ASP.NET
on Wed, Jul 2 2008 2:24 PM

Hi Brendan,

Nice piece of code..

I tried to implement this in one of my applications. I inserted one more line to hide the command window -

proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

But here I want to display the error messages(if any) thrown by windows\system32\cmd.exe. The common try...catch block is not catching it. Any suggestion?

Mubarak wrote re: Run a .BAT file from ASP.NET
on Thu, Jul 17 2008 5:02 PM

You are the Man :)

I was having the same problem using Console application. I tried all possible ideas that I can think of but no luck. This workes for me.

Thank you :)

Miesie wrote re: Run a .BAT file from ASP.NET
on Tue, Aug 26 2008 6:19 AM

You must give the rights to whole path.

i.e. c:\p1\p2\p3

you must give rights to every fucking folder p1,p2 and p3 (also c:\ root (?)).

mxdev wrote re: Run a .BAT file from ASP.NET
on Tue, Sep 2 2008 4:49 PM

1. change local policies for APSNET user:

in WinXP: run secpol.msc

go to Local Policies->User Rights Assignment

find "Deny log on locally" and remove ASPNET user from it.

then find "Deny logon locally" and remove ASPNET user from it.

read here:

mxdev.blogspot.com/.../asp-net-run-application-exe-from-aspnet.html

H wrote re: Run a .BAT file from ASP.NET
on Tue, Sep 9 2008 10:12 AM

Many thanks Brendan,

Such a treat when something just works!!

Preeti wrote re: Run a .BAT file from ASP.NET
on Thu, Sep 18 2008 8:13 AM

Hi ,

Please help me in solving the problem. I am tring to execute a batch file through ASP.NET on W2K3 IIS6.0 it doesnt work. The code works perfectly fine on W2K IIS5.1 server though.

Thanks  LOT IN ADVANCE.

Ozz wrote re: Run a .BAT file from ASP.NET
on Thu, Oct 2 2008 5:06 AM

Hi,

I am trying to execute batch file which is creating another file. I am using C# asp.net 2.0 and windows 2000 server.

I can start notepad or calc  with batch file but it doesn't process to create a new file. I used impersonation and all permissions seems ok.

Does anyone tell me what else I can do. It is very urgent.

JJ wrote re: Run a .BAT file from ASP.NET
on Tue, Oct 7 2008 11:46 AM

Does anyone try to execute a batch file in windows 2003. Tried all the above options.. Nothing works. Please help me

Rakshith wrote re: Run a .BAT file from ASP.NET
on Thu, Oct 16 2008 5:28 AM

I have created a Web page in C# ASP.net that can be accessed with in campus, and through that i want to select a batch file from the PC who have accessed the page, is it possible . is there any changes to be done in web.config file. please sugget.

Raghu wrote re: Run a .BAT file from ASP.NET
on Tue, Jan 13 2009 8:26 AM

hi,

i am running perl script using the bat file. the program runs perfect in sql server authentication but when i try to run the same program using windows authentication the process is not started and it works perfect in the debug mode in visual C#. but i have hosted the application in the server machine. from the inetmanger it is not running properly. is there any permission issue is there, so that i can enable it to run,

Ron wrote re: Run a .BAT file from ASP.NET
on Wed, Jan 14 2009 4:38 AM

ur sample not working!

lazi wrote re: Run a .BAT file from ASP.NET
on Fri, Jan 16 2009 10:48 AM

Great job! Thanks!

M wrote re: Run a .BAT file from ASP.NET
on Sun, Jan 25 2009 12:06 PM

Hi,

I am having the same problem as Krishna running this in Windows 2003 Server SP2.

The call to cmd.exe fails with "The application failed to initialize properly (0xc0000142). Click on OK to terminate the application."

Any ideas?

P wrote re: Run a .BAT file from ASP.NET
on Wed, Jan 28 2009 10:20 AM

I have similar problem on Vista. IIS6 on a Vista!

Vinit wrote re: Run a .BAT file from ASP.NET
on Thu, Apr 2 2009 7:55 AM

Thanks, I have been wondering for this for last 2 hours and your solution worked like a charm(as you said). Thanks once again.

Abhishek wrote re: Run a .BAT file from ASP.NET
on Tue, Aug 25 2009 4:45 AM

Hi Brendan,

I  am using your code to run a batch file. When i run my applicaiton in debug mode, its successfully run the batch file but when i deploye it on IIS, its able to read the fiel but not able to run the bat file, and also not giving any error message.

Please help me out .

abhishek wrote re: Run a .BAT file from ASP.NET
on Tue, Aug 25 2009 4:46 AM

Hi Brendan,

I  am using your code to run a batch file. When i run my applicaiton in debug mode, its successfully run the batch file but when i deploye it on IIS, its able to read the fiel but not able to run the bat file, and also not giving any error message.

Please help me out .

Zak Willis wrote re: Run a .BAT file from ASP.NET
on Tue, Nov 24 2009 9:57 AM

Hi, the answer is simple, well, not that simple. I had a similar problem trying to run a command line tool, offered to us by Bloomberg. I got a variety of errors, including permission denied, cannot read output. The end result was very simple. You need to redirect the standard input - which is the same as manually typing commands into command prompt. You could do following:- in Windows Environment variables, set an environment variable with the path of your batch file. You could also run an indiviual "Path" command.

Here is a simple example.

Process pr = new Process();

           pr.StartInfo.UseShellExecute = false;

           pr.StartInfo.FileName = fileExecutable;

           pr.StartInfo.RedirectStandardInput = true;

           pr.StartInfo.RedirectStandardOutput = true;

           pr.StartInfo.RedirectStandardError = true;

           pr.Start();

           StreamWriter swrtrIn = pr.StandardInput;

           StreamReader swrtrErr = pr.StandardError;

           swrtrErr.AutoFlush = true;

           swrtrIn.WriteLine();

           swrtrIn.WriteLine("PATH " + pathCommandExecutable);

swrtrIn.WriteLine("executable " + Options);

           swrtrIn.WriteLine(sbuild.ToString());

           swrtrIn.Close();

           StreamReader swrtrOut = pr.StandardOutput;

           string results = swrtrOut.ReadToEnd();

           pr.Close();

           swrtrOut.Close();

           string errorstring = swrtrErr.ReadToEnd();

           swrtrErr.Close();

Chris wrote re: Run a .BAT file from ASP.NET
on Mon, Jan 11 2010 4:57 PM

This is a good chunk of code. I modified so I could see any errors thrown on the command line. So you can use the below to invoke a batch file and read from stderr to see if any error messages were thrown:

public static bool StartDataSync(string BatchSyncFileName, int AgencyID, int SyncFileID, DateTime StartDate, DateTime EndDate)

{

bool RetVal = true;

System.IO.StreamReader strm = null;

System.IO.StreamReader sOut = null;

System.IO.StreamReader sError = null;

System.IO.StreamWriter sIn = null;

System.Diagnostics.Process proc = null;

try

{

// Get the full file path

string Path = System.Configuration.ConfigurationSettings.AppSettings["SyncFilesPath"];

string FullFilePath = Path + BatchSyncFileName;

// Create the ProcessInfo object

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");

psi.UseShellExecute = false;

psi.RedirectStandardOutput = true;

psi.RedirectStandardInput = true;

psi.RedirectStandardError = true;

psi.CreateNoWindow = true;

psi.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory.ToString();

// Start the process

proc = System.Diagnostics.Process.Start(psi);

// Open the batch file for reading

strm = System.IO.File.OpenText(FullFilePath);

// Attach the output for reading

sOut = proc.StandardOutput;

// attach the standard error stream for reading

sError = proc.StandardError;

// Attach the in for writing

sIn = proc.StandardInput;

sIn.AutoFlush = true; // automatically write to the stream after every Write(), WriteLine() call.

// Write each line of the batch file to standard input

while(strm.Peek() != -1)

{

string Text = strm.ReadLine();

Text = Text.Replace("<AgencyDataUserID>", Convert.ToString(AgencyDataUserID));

Text = Text.Replace("<datastartdate>", StartDate.ToShortDateString());

Text = Text.Replace("<dataenddate>", EndDate.ToShortDateString());

sIn.WriteLine(Text);

}

// close batch file reader.

strm.Close();

// exit cmd.exe

sIn.WriteLine("exit");

// Close the stdin stream.

sIn.Close();

// we leave stdout open so we can check it for errors. stderr and stdout seem to be linked.

// check if we had any errors in our commands we passed to cmd.exe

int index = sError.Peek();

if(index != -1)

{

string Error = sError.ReadToEnd();

throw new System.Exception(Error);

}

sOut.Close();

// int index = sOut.Peek();

// if(index != -1)

// throw new System.Exception(sOut.ReadToEnd());

// wait for the cmd.exe process to close

bool Closed = proc.WaitForExit(60 * 1000);

// process failed to close in a timely manner, throw error

if(!Closed)

{

try

{

proc.Kill();

}

catch(System.Exception)

{

// ignore kill exceptions.

}

throw(new System.Exception("sync process hung or did not queue fast enough."));

}

}

catch(System.Exception ex)

{

// close streams

if(strm != null)

strm.Close();

if(sOut != null)

sOut.Close();

if(sIn != null)

sIn.Close();

if(proc != null) // close process

proc.Close();

// log error

Common.ErrorHelper.WriteErrorToEventLog("Error executing sync:\n" + ex.Message + "\n\n" + ex.StackTrace);

RetVal = false;

}

return RetVal;

}

leo_rw wrote re: Run a .BAT file from ASP.NET
on Thu, Feb 4 2010 5:33 AM

I've problem to like abhishek. I can execute psshutdown in debug mode, but when i deploy to IIS in Windows XP, psshutdown timed out, and application hang. I've been searching the problem and i've found that the eula of Sysinternal is the problem. Because it first time load, then user must accept the eula first. To accept the eula, we must edit in registry.

********************

Windows Registry Editor Version 5.00

' Usage of psshutdown.exe authorized for all profils

[HKEY_USERS\.DEFAULT\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

' Usage of psshutdown.exe authorized for local SYSTEM

[HKEY_USERS\S-1-5-18\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

' Usage of psshutdown.exe authorized for local service (nt authority)

[HKEY_USERS\S-1-5-19\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

' Usage of psshutdown.exe authorized for network service (nt authority)

[HKEY_USERS\S-1-5-20\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

[HKEY_USERS\S-1-5-21-839522115-492894223-2147179587-1007\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

*********************

You can save the text above to .reg file then execute it. The last text is S-1-5-21-839522115-492894223-2147179587-1007 depend on your aspnet user. You have to search in your registry where the aspnet user.

After you add the registry, you can execute bat file from asp.net.

Have a nice try......

leo_rw wrote re: Run a .BAT file from ASP.NET
on Thu, Feb 4 2010 5:34 AM

I've problem to like abhishek. I can execute psshutdown in debug mode, but when i deploy to IIS in Windows XP, psshutdown timed out, and application hang. I've been searching the problem and i've found that the eula of Sysinternal is the problem. Because it first time load, then user must accept the eula first. To accept the eula, we must edit in registry.

********************

Windows Registry Editor Version 5.00

' Usage of psshutdown.exe authorized for all profils

[HKEY_USERS\.DEFAULT\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

' Usage of psshutdown.exe authorized for local SYSTEM

[HKEY_USERS\S-1-5-18\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

' Usage of psshutdown.exe authorized for local service (nt authority)

[HKEY_USERS\S-1-5-19\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

' Usage of psshutdown.exe authorized for network service (nt authority)

[HKEY_USERS\S-1-5-20\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

[HKEY_USERS\S-1-5-21-839522115-492894223-2147179587-1007\Software\Sysinternals\PsShutdown]

"EulaAccepted"=dword:00000001

*********************

You can save the text above to .reg file then execute it. The last text is S-1-5-21-839522115-492894223-2147179587-1007 depend on your aspnet user. You have to search in your registry where the aspnet user.

After you add the registry, you can execute bat file from asp.net.

Have a nice try......

Add a Comment

(required)  
(optional)
(required)  
Remember Me?