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

About Brendan Tompkins

Brendan runs CodeBetter.Com and Devlicio.Us. He is a former MVP for Microsoft .NET and is president of Port Technology Services, a partner with Port Solution Integrators a provider of hardware and software integration services for the transportation and logistics industry.
This entry was posted in ASP.NET Tutorials, Most Popular. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Marko

    Hi

    I also was finding it difficult to get a batch file running on a remote server. I used the above but had to add the authentication to the mix (psi.domain, psi.username, and psi.password)

    psi.Domain = “”;psi.UserName = “”;SecureString password = new SecureString();foreach (char c in “”)  password.AppendChar(c);psi.Password = password;Thanks!Thanks!

  • http://www.facebook.com/CodeChief Anthony Brian Wall

    Spoke too soon, tried it on a 2008 R2 test server and it still doesn’t work. Will shift the code behind a back-end WCF service hosted in a Windows Service, which should do the trick.

  • http://www.facebook.com/CodeChief Anthony Brian Wall

    Still a problem in .NET 4 surprisingly enough. Didn’t think this trick would work and tried everything else, even calling %COMSPEC% /S /C “original command” but ONLY your workaround solves the limitation.

    Well done finding that. I’ve written that into my ProcessExtensions class as an “emulateTypedCommand” option.

    Thanks!

  • 923943u23

    i got the same problem

  • Sudheshna

    Hi,

    Thank you for you Code!!

    I have tried your code and it displayed 

    Microsoft Windows [Version
    6.1.7600]Copyright (c) 2009 Microsoft Corporation. All rights
    reserved.c:windowssystem32inetsrv>@echo offSTART
    E:VMAppvbsVMWakeupWOL.vbs# E:VMAppVMWakeup.bat run successfully.
    ExitingEXIT

    But it didn’t executed the batch filebut when I double clicking on the batch file its working.

    Please advice

    Thanks & Regards
    Sudheshna

  • Nunu Marwanto

    hai, this code running in versi debug but am publish this code not running, whay? can give me solution.
    code:
        public string RunCommand(string command)    {        string result = “”;        int ExitCode;        string output = “”;        string error = string.Empty;        ProcessStartInfo ProcessInfo;        Process Process;        ProcessInfo = new ProcessStartInfo(“cmd.exe”, “/c ” + command);        ProcessInfo.WorkingDirectory = @”D:GisKemenhubSinkronisasiSinkronisasiSinkronisasiTools”;        ProcessInfo.UserName = “Administrator”;        string pas = “4dm1ntmisd”;        ProcessInfo.Password = new System.Security.SecureString();        for (int x = 0; x < pas.Length; ++x)        {            ProcessInfo.Password.AppendChar(pas[x]);        }        ProcessInfo.CreateNoWindow = false;        ProcessInfo.UseShellExecute = false;        ProcessInfo.RedirectStandardOutput = true;        ProcessInfo.RedirectStandardError = true;        Process = Process.Start(ProcessInfo);        using (System.IO.StreamReader myOutput = Process.StandardOutput)        {            output = myOutput.ReadToEnd();        }        using (System.IO.StreamReader myError = Process.StandardError)        {            error = myError.ReadToEnd();        }        Process.WaitForExit();        ExitCode = Process.ExitCode;        Process.Close();        output = output.Replace(System.Environment.NewLine, "”);        error = error.Replace(System.Environment.NewLine, “”);        result = output + “” + error;        return result;    }
    what the hell my fucking code. pliss help me!

  • http://www.facebook.com/kourtakos Apostolis Kourtis

    Hi all day i was trying to make the code above to work on my windows 2003 server (iis 6)
    i reliezed that me page hanged due to the fact that the cmd proccess after the execution of the code didn’t close. (if i stopped the cmd through task manager the result was returned).

    Soooo i Believe i found the silliest answer to the problem…
    all i’ve done is this…

    I’ve kept all the code but with these adjustments
    i’ve created a blank batch file let’s say dummy.bat
    string strFilePath = “c:dummy.bat”;

    and at
    System.Diagnostics.ProcessStartInfo(“cmd.exe”);
    i’ve replaced with
    Dim psi As New System.Diagnostics.ProcessStartInfo(“cmd.exe”,” /c “”C:runme.bat”" “)
    (sorry VB developer :p)

    it seems to work like a charm.

    I sure that might be a more correct answer but for my need it’s ok!

    Kind Regards

  • Sharif

    hi,
    i have run a batch file form asp.net mvc  + .net 4.0 + iis7  without any problem.

  • Keith

    This wasn’t quite enough to help me trigger a console application from a VB.NET web application, but it was a step in the right direction and I did find a way to do it.

    My situation was that the console app would run perfectly fine when started manually, but wouldn’t run at all when called from the web app.  I went through folder and file permissions, IIS permissions/user emulation, and even .NET framework security settings – nothing worked.

    I created a system scheduled task that would activate the console app, set it to disabled so that it normally wouldn’t run, and set its permissions so that anyone could trigger it.  Then I changed my web app to make a system call:

    Process.Start(“C:Windowssystem32schtasks.exe”, “/run /tn Print”)

    where Print is the name I gave the scheduled task.  This still didn’t work in the live version and I found that I had to go into IIS to the application pool to which the web site was attached and change its properties.  On the Identity tab I chose “configurable” and entered a user with system permissions; then everything worked.

    Security-wise this might not be the best approach, but it worked and the apps in question are limited-function tools running on an intranet.

  • http://pulse.yahoo.com/_4HOW7LWSROA5Y52Q3Z7VS45CF4 Right

    Great work, i’m not able to execute on IIS. please solve my problem

  • Padmabarathy

    Its working fine when i am running in local.after Publishing the application its not working.
    Wat may be the Problem. Please help me on this.

  • M-nazira

    SHould we use this in  .cs file or in aspx file? I’m very new. plz help! 

  • Aicasan

    COOL!! Love ur brain!!

  • Post_id

    Great stuff, it works for me

  • Arhinoa

    I was desperated, thank you for sharing this code :-)

  • gm

    vgf

  • Ron

    Tnx for this post!
    The code works perfectly.

    Now my users can finally start there workstations remotely (WOL)!
    Tnx again!

  • ghh

    b nb

  • cosmo

    This code worked great, didn’t even have to switch to a different user before executing it from my aspx page! Think something I was doing wrong before was not setting the psi.WorkingDirectory with the directory path of the batch file I was executing. I’m using it to execute a batch file that has psexec commands in it to do some remote processing. thanx!

  • http://leowidodo.wordpress.com leo_rw

    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……

  • http://leowidodo.wordpress.com leo_rw

    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……

  • Chris

    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(““, Convert.ToString(AgencyDataUserID));
    Text = Text.Replace(““, StartDate.ToShortDateString());
    Text = Text.Replace(““, 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;
    }

  • http://www.blue-rhino.co.uk Zak Willis

    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();

  • abhishek

    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

    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 .

  • Vinit

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

  • P

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

  • M

    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?

  • lazi

    Great job! Thanks!

  • http://www.none.com Ron

    ur sample not working!

  • Raghu

    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,

  • Rakshith

    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.

  • JJ

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

  • Ozz

    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.

  • Preeti

    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.

  • H

    Many thanks Brendan,
    Such a treat when something just works!!

  • http://mxdev.biz mxdev

    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:

    http://mxdev.blogspot.com/2008/09/asp-net-run-application-exe-from-aspnet.html

  • Miesie

    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 (?)).

  • Mubarak

    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 :)

  • Thomas

    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?

  • Nimish Agarwal

    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.

  • http://www.harinath.in Harinath Mallepally

    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.

  • http://inquest.wordpress.com/ sandeep

    Thanks Yaar!

    You saved my lots of time.

  • Krishna

    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 = “ “;
    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:
    http://www.velocityreviews.com/forums/t117223-run-cmdexe-from-aspx-page.html
    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3310025&SiteID=1

    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…

  • Andrei

    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.

  • Nick

    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)

  • kite

    thanks

  • Krishna

    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

  • Kel

    http://support.microsoft.com/kb/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.

  • http://peterkellner.net Peter kellner

    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.

  • Ronald_from_Colombia

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

  • Tharaka

    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

  • Jacob

    If I hadnt found this site i might have killed myself

  • kk

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

  • jyu

    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.

  • sharad

    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 ?

  • RIck

    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

  • Mark

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

    Thanks W@nderlust

  • Ryan

    Thanks W@nderlust!!

  • Rajani Karthik

    Hey…….I got it. thanks everyone

  • Cheng Zhang

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

  • Raj

    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

  • santosh

    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.

  • santosh

    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?

  • http://www.bompee.com Ian

    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 );

    }

  • Ian

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

    http://support.microsoft.com/default.aspx?scid=kb;en-us;555134

  • Sam

    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 !!!

  • jagadish d

    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.

    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)
    {

    }

  • Anju

    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

  • sowmya

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

  • larry miller

    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#)

  • Imran

    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.

  • Rak

    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
    }

  • ananda

    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

  • Vinayak.N

    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.

  • Rob

    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!

  • http://aa Shashanka

    Hi ALL,

    Thanks
    It is solved
    Click here for the exe/bat file called A.

    Regards
    Shashanka

  • http://dd Shashanka

    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 :

  • MarkyTheMark

    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

  • snickss

    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.

  • CryyL

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

  • W@nderlust

    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.

  • Yinon

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

  • Ray

    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

  • redsv

    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

  • John

    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= “\\

    objProc.StartInfo.FileName ="\\\\c$\Test.bat”

  • Zen

    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

  • http://don'tforget,DRIVELETTERvs.UNCPATH(2000vs2003) Jeff

    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

  • Topcat

    Good job! this is exactly what I needed.

  • Dinesh

    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 =
    ‘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

  • Code Smith

    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

  • Naags

    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

  • DINESH

    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 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 !!!

  • Lynda

    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!

  • Mick T

    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

  • Maurilio Martini

    Great Stuff!! [}}:-))

  • Gennady

    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 (

    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

  • http://geekswithblogs.net/mahesh Mahesh
  • Gear

    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

  • Samir

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

  • Dino

    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?

  • Dino

    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.

  • http://www.mobilnova.com Dennis

    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

  • Tonny

    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.

  • Tonny

    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.

  • Sara

    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

  • JOse

    dsa

  • Sashanan

    This code solved my problem, at least. Thanks for sharing.

  • http://www.morganpersson.net Morgan

    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.

  • Ipun

    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……………

  • P. Ravichandran

    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);

  • Kumar

    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

  • http://blog.joycode.com/percyboy/ percyboy

    The codes really work!
    but it doesn’t support the “goto label” grammer.

  • http://tinuverma@gmail.com Deepak

    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?

  • vikas kumar

    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

  • James

    Wow, just hit this after some searching and hair removing(insert frustration image here). This was by far the most helpful.

    Thanks!

  • Anupam Srivastava

    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

  • Tracy Spratt

    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

  • Tracy Spratt

    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

  • darktown

    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()

  • http://sudeep_aitian@yahoo.com Sudeep Ghosh

    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

  • http://guestbooks.pathfinder.gr/read/online-7-card-stud online 7 card stud
  • http://guestbooks.pathfinder.gr/read/play-seven-card-stud play seven card stud

    Eventually play seven card stud fold http://guestbooks.pathfinder.gr/read/play-seven-card-stud scalper four represent percentage!

  • http://guestbooks.pathfinder.gr/read/7-card-stud 7 card stud
  • http://guestbooks.pathfinder.gr/read/online-seven-card-stud online seven card stud
  • Abhi

    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 :

    It should work now…

    regards
    abhi

  • Tim Riester

    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

  • Ivan Belov

    Thanks for snippet, Brendan! Helped me to solve related problem. Great job! :))

  • Marck NOOB

    Is that possible to someone please write a full aspx page, calling a bat file ??

    Please help me, I am very boob! :D

  • Utkal Sharma

    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);

  • Alex

    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.

  • Jason

    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

  • lastdragon

    none of the above suggestions seem to work

  • MadRiverLizard

    How would I modify this so that the process uses command line arguments (c:\bat.bat 2004 1)?

  • Jan Landen

    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

  • Kien

    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.

  • Dariwe

    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?

  • HELP

    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

  • Ramesh

    Thanx I will try and then send another reply

  • Somayeh

    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.

  • viki

    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

  • Sunil

    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();

  • Michael

    Brendan,

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

    – Michael

  • Serge

    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

  • Yaheya Quazi

    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!

  • Oliver

    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.

  • Mike

    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

  • Brendan Tompkins

    Nice! Thanks!

  • TrungGap

    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

    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\\“;

  • Dan Marth

    Sorry about the mis-spelling of your name.

  • Dan

    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

  • Brendan Tompkins

    Dan – Good. BTW, anyone know of any tools to port from C# to VB?

  • Dan Marth

    Brenden,

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

    Thanks,

    Dan

  • Dan Marth

    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

    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

    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.

  • Brendan Tompkins

    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

    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

  • Dan Marth

    Brendan,

    FYI, I am running this on windows 2000 but I will take a look at TokenMon.

    Thanks,

    Dan

  • Brendan Tompkins

    Dan,

    Thanks! Try TokenMon from Sysinternals. Under 2003, these batch files run as NETWORK SERVICE, AFAIK….

  • Dan

    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

    Hi Dan.. See the above comments I left for Matt.

  • Dan

    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

    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..

  • Matt

    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

  • Eric Engler

    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

  • Brendan Tompkins

    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.

  • Chris Kinsman

    Did you try cmd /c

  • Brendan Tompkins

    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.

  • Lorenzo Barbieri

    Perhaps it was a security setting enabled by the IISLockdown Tool?