Run a batch file as a specific User (or Administrator) from ASP.NET...

by Rahul 7/13/2008 3:32:21 PM

...well first of all, I am NOT recommending it, but sometimes it could be necessary! Now, let's proceed to the code...

1. Create a page called RunBatchFile.vb and paste the following...

Imports System.Diagnostics
Imports System.IO
Partial Class RunBatchFile
    Inherits System.Web.UI.Page
    Dim _password As New System.Security.SecureString
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim password As String
'Read from any Registry or Encrypted config file if you like for added security.
password = "YOUR___PASSWORD" For Each c As Char In password _password.AppendChar(c) Next Dim strFilePath As String = "c:\\temp\\test.bat" Dim psiMyProcess As ProcessStartInfo = New ProcessStartInfo("cmd.exe") psiMyProcess.LoadUserProfile = True psiMyProcess.UserName = "Administrator" psiMyProcess.Password = _password psiMyProcess.UseShellExecute = False psiMyProcess.CreateNoWindow = True psiMyProcess.RedirectStandardOutput = True psiMyProcess.RedirectStandardInput = True psiMyProcess.RedirectStandardError = True psiMyProcess.WorkingDirectory = "c:\\temp\\" Dim prcProcess As Process = Process.Start(psiMyProcess) Dim strm As StreamReader = File.OpenText(strFilePath) Dim strOut As StreamReader = prcProcess.StandardOutput Dim strIn As StreamWriter = prcProcess.StandardInput Do While strm.Peek() <> -1 strIn.WriteLine(strm.ReadLine()) Loop strm.Close() strIn.WriteLine(String.Format("# {0} ran successfully. Exiting now!", strFilePath)) strIn.WriteLine("Exit") prcProcess.Close() Dim strOutput As String = strOut.ReadToEnd().Trim() strIn.Close() strOut.Close() Response.Write(String.Format("<font face=courier size=0>{0}</font>", _ strOutput.Replace(System.Environment.NewLine, "<br>"))) End Sub End Class

2. The batch file that I have is a one liner (and a no-brainer)... [Here, one and two are folders containing a few files]

xcopy one\*.* two /y

3. If everything is in place, you should get something like this as output...

 image

Hope this helps, Smile
Rahul


Quote of the day:
The human race has one really effective weapon, and that is laughter. - Mark Twain

Tags: , ,

ASP.NET | Tips and Tricks | Troubleshooting

blog comments powered by Disqus

Comments


Disclaimer

The opinions expressed herein are our own personal opinions and do not represent our employer's view in any way.
© Copyright 2014, Rahul Soni