Execute .sh from c# or .cmd prompt - c#

I wanted to execute the following shell script commands '.sh' from either c# or through command prompt (which I can further execute it via c#)
I usually use the following commands to execute my .sh file .
The commands I do it manually are
a) Open cygwin (which inturn calls C:\cygwin\bin\mintty.exe -i /Cygwin-Terminal.ico -). This will open cygwin console
b) Go to the working directory where I need to execute the .sh file using
cd <dir in unix format>
c) execute the .sh script file
sh <path to my .sh file in unix format>
But, I would like to automate these steps using command line/ c#
(i.e to execute without opening console/apps like mintty.exe or bash.exe)
Note : The examples provided in How do i start Mintty and run a script file? didnt help me since they just close after opening without executing my commands.

If you want also the mintty window (useful when using vt100 escape sequences), you could use a batch wrapper file.
#echo off
setlocal EnableDelayedExpansion
set "script=%~1"
set "cygwin=C:\cygwin64\bin"
set "path=!cygwin!;!path!"
mode con lines=80 cols=120
REM C:\cygwin\bin\mintty
start "cygwin window" !cygwin!\mintty.exe -i /cygdrive/c/Windows/System32/compstui.dll,53 --exec "!script!"
You should prefix (at least) the cygwin/bin directory to the path variable, else you get strange results
The -i ...compstui.dll,53 is only for changing the icon in the taskbar/window

You can run a script directly with bash, using C:\cygwin\bash.
example: c:\cygwin\bin\bash --login "C:\foo.bsh"

Related

C# run a .bat file where some of the commands are to be run in an attached linux shell

I am able to execute a .bat file with these commands contained:
ssh -i BatchStagingVM_key.pem azureuser#xx.xxx.xx.xx //works
timeout /T 5 /NOBREAK
echo blah
Essentially the first one runs, connecting to the VM, but the last two does not even register or get to the shell in the logged into linux vm command line. there is a few questions relating to executing .bat files, but none where some of the commands are to be executed on a vm on that same command line instance. Running these one at a time, works fine, but I want to automate this. Any advice/ideas/packages to check out?
The linux VM command line, that isn't receiving commands from the .bat file execution

How to run PowerShell script using System.Diagnostics.Process.Start in c#?

I'm writing this:
using System.Diagnostics;
Process.Start("C:\\CodeProjects\\C#\\WindowsPowerShell\\v1.0\\powershell_ise.exe", "-File .\\mp4_to_flac.ps1");
All this does is open up the script in Windows PowerShell ISE. But I also want it to RUN! So what other arguments do I have to pass in so that it executes?
Process.Start method Reference
You don't want to run powershell_ise.exe but powershell.exe. From a dos command prompt you can just prefix your command or script with #powershell, but for a process you're going to want to use something like
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
(that's mine on Win 8.1), yours should be somewhere near there if you're on a different version.
The chocolatey guys throw in these switches
-NoProfile -ExecutionPolicy unrestricted
when executing powershell from the command prompt, you might have to do that also depending on how your execution policy is set.
You could call it like so:
Process.Start(".\\mp4_to_flac.ps1");
and make sure all your windows settings are correct, so a double click on the file will execute it.

Create Batch file for iexpress

I am trying to use iexpress to run my batch file which will execute the 2 exe & 1 msi files for me. when i try to do it manually, it works.
following is the code in my batch file.
Start /wait %CD%\1.exe /q
Start /wait %CD%\2.exe /q
msiexec.exe /i "%CD%\3.msi"
but this doesn't seem to be working when i create an exe file from iexpress.
Reference
Above mentioned article has some code(to copy files to temp folder) & but i am not able to understand the syntax.
MKDIR %Tmp%\<UNIQUE PRODUCT NAME>
XCOPY . %Tmp%\<UNIQUE PRODUCT NAME> /S /E /Y
%Tmp%\<UNIQUE PRODUCT NAME>\setup.exe
The problem is that, as you can see from your screenshot, the batch file is being executed by command.com, not cmd.exe. (If you don't specify an interpreter, IExpress uses command.com. Ouch.) So there are no variables like %cd% or %~dp0.
You likely don't need them anyhow. But you do need to execute your batch file explicitly in IExpress like:
cmd.exe /c file.bat
so that it uses a modern command interpreter.
The second bit of code in your question makes the files persistent (ie they won't be deleted after the IExpress archive terminates) by xcopying them to a different directory.
Here is what it means:
1) Creates a directory(MKDIR) with name of "UNIQUE PRODUCT NAME" in the path stored in %TMP% Environment Variable, which normally points to: C:\DOCUME~1\yourusername\LOCALS~1\Temp
MKDIR %Tmp%\<UNIQUE PRODUCT NAME>
2) Then copy recursively all installation files from current folder into the new folder created before.
XCOPY arguments:
/S Copies directories and subdirectories except empty ones.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
XCOPY . %Tmp%\<UNIQUE PRODUCT NAME> /S /E /Y
3) Finally execute the application from the new location
%Tmp%\\setup.exe
Hope this helps
Try replacing %CD% with %~dp0
Assuming that 1.exe is in the same folder as your batch script.
Your %CD% is not working. Please be sure that CMD extensions are enabled (type CMD /x to enable and CMD /y to disable) then expand the %CD% with this code
SET CURDIR=%CD%
Start /wait "%CURDIR%\1.exe" /q
Start /wait "%CURDIR%\2.exe" /q
msiexec.exe /i "%CURDIR%\3.msi"
And I'm not sure that you can start an exe from that location (APPDATA) for security reasons.
Thanks a lot for this forum discussion.Finally i could able to compile all msi files and executables in an one .exe file.
Complete procedure as follows create a batch file
echo on
SET CURDIR=%CD%
msiexec.exe /i "%CURDIR%\1.msi"
"%CURDIR%\3.EXE"
"%CURDIR%\setup.exe"
echo off
You can arrange any number of exe files or msi files as you wish and save the batch file as yourfile.bat.
Now the tricky part is before you proceed to Iexpress, convert the batch file to exe with the software provided by http://www.f2ko.de/programs.php?pid=b2e
Now when you run the program keep the 'Invisible Application' checked to hide the command prompt.You can also encrypt your exe with the password.'Delete at Exit' is optional as the temporary folder will be automatically deleted when the execution of files completed.
Once you successfully compile the batch file,execute the .exe file created.
Bingo!! you'll not see the command prompt window and your applications start executing sequentially.
Begin your Iexpress tool and Add all your files present in the batch file(except batch file).On the ‘Install Program to Launch’ screen, leave the Post Install Command blank and find the following in the Install Program dropdown:'demo.exe'and proceed further to create your complete bunch of single package. Cheers!!

Run batch script before Debugging

I want to run a batch script every time before starting program for debugging.
For the build events, such functionality is realized using pre-build event, post-build event.
For actual debugging, I could not find any pre-Debug, post-Debug events.
How to realize this scenario?
I am using VS2008, .net framework 3.5, c# application.
I am opposed to idea of creating some extra lines of code within the application that would fire-up external batch file.
I realise you wished to avoid additional code, but in your Main function you could use Debugger.IsAttached() to kick off your work for you.
For example:
if (Debugger.IsAttached)
{
System.Diagnostics.Process.Start(#"C:\myBatchFile.bat");
}
You can use a VS macro.
I had the same issue and this is the best I came with so far
Dim MustUpdateDB As Boolean
Private Sub DebuggerEvents_OnEnterRunMode(ByVal Reason As EnvDTE.dbgEventReason) Handles DebuggerEvents.OnEnterRunMode
If (MustUpdateDB) Then
MsgBox("Start debug operation", MsgBoxStyle.OkOnly, "TITLE")
REM DO WHATEVER COMMAND HERE
REM System.Diagnostics.Process.Start("C:\listfiles.bat")
MustUpdateDB = False
End If
End Sub
Private Sub BuildEvents_OnBuildDone(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildDone
MsgBox("Build Done", MsgBoxStyle.OkOnly, "Title")
MustUpdateDB = True
End Sub
There is a pretty good explanation on how to add event handlers to a macro
here
The only issue I have so far is to figure out how to get the currently debugged application active directory
A basic solution that worked for me (in VS 2017) was to create a batch file that does the command(s) that should run before debugging, and also include as the last line some parameters to be passed via command-line, such as this:
rem Place the command(s) you need here:
xcopy pristine.file changed.file
rem Now process passed commands - a few extra placeholders shouldn't hurt anything, to
rem allow for some extra command-line parameters
%1 %2 %3 %4 %5 %6 %7
Now in the debugging properties, set the 'Command' to your batch file, and for 'Command Arguments' include $(TargetPath) as the first argument, followed by any arguments your program uses or needs:
$(TargetPath) my command args
YMMV, but for my simple needs this seems to be working well.
if $(ConfigurationName) == Debug mkdir c:\mydir
You should check out... How to run Visual Studio post-build events for debug build only
So, you have a .bat file that you want to run via the pre-build event?
Try to specify full path to your batch file in the pre-build event command e.g.
cmd /c C:\Path\to\foo.bat
or
cmd C:\windows\system32\cmd.exe /c C:\Path\to\foo.bat

How to execute a batch file from C#?

(See end for solution)
I didn't think this was going to be hard. I have a commmand file, d:\a.cmd which contains:
copy /b d:\7zS.sfx + d:\config.txt + d:\files.7z d:\setup.exe
But these lines of C# won't execute it:
Process.Start("d:\\a.cmd");
Process.Start("cmd", "/c d:\\a.cmd");
Throws Win32Exception: "%1 is not a valid Win32 application."
Process.Start opens .pdf files...why not execute command files?
This works if I type it in a cmd window:
cmd /c d:\a.cmd
Windows XP, MS Visual Studio 2008.
Thanks in advance,
Jim
SOLUTION
I'm only SLIGHTLY embarrassed :( There was a file named cmd.exe, size zero in my app's dir. I have no idea how it got there but it is now toast and both of the above C# statements now work. I'm off to find a Harry Potter book so I can get some self-punishment ideas from Dobby...
I've got four things for you that you can try out:
(1) Try providing the full path for cmd.exe (e.g. on my machine: C:\WINDOWS\SYSTEM32\CMD.EXE).
(2) Try adding call to the command to be executed:
Process.Start(#"C:\WINDOWS\SYSTEM32\CMD.EXE", #"/c call D:\a.cmd");
(3) Besides that, I can only guess where the %1 in the Win32Exception is coming from. Maybe your file associations are set-up incorrectly.
If you type the following on the command-line:
> assoc .cmd
You will likely get a mention of cmdfile. If you then look up this token with:
> ftype cmdfile
You might get an answer along the lines of:
cmdfile="%1" %*
Those settings are stored in the registry, and this is how the command-line interpreter knows how to execute files with custom extensions. (You can find out how a PDF document is started by executing the above two statements for the .pdf extension.)
(4) If you start to suspect that your machine might be mis-configured, start regedit (the registry editor) and locate the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor.
On my Windows XP machine (and your Process.Start example works on my machine, with different filenames though), I've got the following values stored in there:
// Name Type Value
// -----------------------------------------------
// (standard) REG_SZ (not set)
// AutoRun REG_SZ
// CompletionChar REG_DWORD 0x00000040 (64)
// DefaultColor REG_DWORD 0x00000000 (0)
// EnableExtensions REG_DWORD 0x00000001 (1)
// PathCompletionChar REG_DWORD 0x00000040 (64)
Of those, the AutoRun value might be of some interest. I think it corresponds to the /d command-line switch of cmd.exe, which controls whether cmd.exe attempts to start files with custom extensions. Usually, this is enabled. Maybe, on your machine, it isn't?
Or you can do a .bat file, then call this file through System.Diagnostics.Process.Start(). It won't redirect output to Console Application, but it would certainly execute the commands inside.
You need to specify the process full name (cmd.exe).
You should try
Environment.GetFolderPath(Environment.SpecialFolder.System) + "cmd.exe"
So you can be sure to execute the right file even if a cmd.exe is in your applications directory.
It looks like something wrong with your computer. Try running this on another machine. This should work. Process.Start(string) uses ShellExecuteEx to launch the file, so it's pretty much the same thing as double-clicking the file in Explorer, as you supposed.
A simple test worked for me.
B:\foo.cmd:
#echo Hello from foo.cmd!
#pause
Program.cs:
class Program{
static void Main(){
System.Diagnostics.Process.Start("B:\\foo.cmd");
}
}
This works as expected.
Your error message is suspicious, "%1 is not a valid Win32 application." The value in my registry at HKCR\cmdfile\shell\open\command is
"%1" %*
The %1 gets replaced by the file name, and the %* can be ignored here (it indicates that any further command-line arguments should be passed along, but we're not concerned with that right now).
The fact that the file itself is launched to handle this type of file indicates that Windows itself knows how to launch this type of file. On a normal installation of Windows, the following extensions should be set up similarly:
.exe Windows and DOS executable files
.com DOS "command" files
.bat Windows and DOS batch files
.cmd Windows NT batch files
.pif Windows shortcuts to DOS executable files
If you go to HKCR\.xxx (where xxx is any of the above), the "(Default)" value should be xxxfile. If you then go to HKCR\xxxfile\shell\open\command, the "(Default)" value should be "%1" %*. Also the "(Default)" value of HKCR\xxxfile\shell should be either not set or open.
If you have anything else in any of these values, then some program has attempted to insert itself into the execution process. Viruses sometimes do this (Sircam, for example).
Have you tried executing cmd.exe, and passing the .cmd file to it as an argument?
hmm try:
System.Diagnostics.Process myproc = new System.Diagnostics.Process();
myproc.EnableRaisingEvents=false;
myproc.StartInfo.FileName="d:\\a.cmd";
myproc.Start();
MessageBox.Show("did the command");
Have you tested your batch file in the directory, context it's going to run? The error message with %1 looks like the problem may be in there?

Categories