How do I passt following parameters to my batch file?
custom.bat mode="test" logs="true"
I tried to double the " but nothing helped.
custom.bat "mode="test"" "logs="true""
And, in custom.bat you remove the unneeded quotes
#echo off
set "arg1=%~1"
set "arg2=%~2"
echo [%arg1%] [%arg2%]
You may use CALL command to launch a new batch-file. After executing the last line of the "called file", the control will return back to the "calling file".
You may set the parameters to the "called .bat fie" by using either a simple string or a variable.
eg.
CALL MyScript.bat "1234"
or
SET _MyVar="1234"
CALL MyScript.bat %_MyVar%
As a precaution, you may use SETLOCAL & ENDLOCAL to keep separation between variables of same-name among different files.
Related
I created an c# wpf application that accepts command line parameters. If I open cmd and call the application with multiple parameters, the parameters are passed in correctly.
But if I do that same thing but from a batch file it passes the parameters as one parameter combined together rather then multiple parameters. I had the application output the parameters and it looks like all the spaces (which is what separates each command line parameter) were changed to a weird á character.
is there something special I need to do to get the parameters passed correctly?
I have tried resaving the file with ASCII encoding but that didn't change anything.
I also tried adding this line to the batch file
chcp 1253>NUL
that changed it so the á wasn't there but it still had it was one parameter.
seems like the spaces are just not getting passed as a space.
here is what my batch file line looks like, each parameter is separated by a space.
start /wait C:\MyTestApp.exe /SILENT /BOOLAGREEMENT=TRUE /BOOLGAOPTIN=TRUE
--UPDATE--Adding steps to reproduce...
this is just generic code similar to what I did just condensed
create c# wpf app.
in App.xaml.cs override OnStartup
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
this.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
bool shutdownapp = false;
MessageBox.Show(string.Join(",", e.Args));
}
build exe.
now launch cmd and cd to the location of the exe.
MyTestApp.exe /param1=test1 /param2=test2
you should get a message box that says
/param1=test1,param2=test2
now create a batch file that has something like this...then run it
test.bat
#echo off
start /wait c:\MyTestApp.exe /param1=test1 /param2=test2
this time the message box should have this...
/param1=test1/param2=test2
Start sees all of that as a CMD to Start.
Is there a reason you actually need to use start? generally, there isn't and you can just call the executable directly.
eg TestMyApp.cmd
#(
SETLOCAL
ECHO OFF
)
REM Call your Command here with all arguments:
"C:\MyTestApp.exe" /SILENT /BOOLAGREEMENT=TRUE /BOOLGAOPTIN=TRUE
If you sincerely require Start.
Then you should be aware that it treats all of that command as a single string, by nature, which is what you're running into, so you should be calling a new CMD instance explicitly instead in that case:
START "" /WAIT CMD /C ""C:\MyTestApp.exe" /SILENT /BOOLAGREEMENT=TRUE /BOOLGAOPTIN=TRUE"
But that is a lot of extra work to go through if not needed.
Alternatively, you can also just run a CMD instance directly:
CMD /C ""C:\MyTestApp.exe" /SILENT /BOOLAGREEMENT=TRUE /BOOLGAOPTIN=TRUE"
Or Use CALL:
CALL "C:\MyTestApp.exe" /SILENT /BOOLAGREEMENT=TRUE /BOOLGAOPTIN=TRUE
I've managed to create my own file extension following this tutorial: http://www.codeproject.com/Articles/17023/System-File-Association
So far, it works perfectly. I've got only one thing that I can't solve.
When I double-click on a file with that extension, my program opens up. Now, I'd want to perform an action in my program. I made my way through some threads here and read that the file path is automatically passed to the startup arguments.
The problem is that no single argument is passed, also Process.GetCurrentProcess().StartInfo.FileName returned an empty string. I think this is consecutively because I don't pass any arguments when double-clicking my file.
This is my code:
var fai = new FileAssociationInfo(".extension");
if (!fai.Exists)
{
try
{
fai.Create("My Extension Program");
var pai = new ProgramAssociationInfo(fai.ProgId);
if (!pai.Exists)
{
pai.Create("My Program File",
new ProgramVerb("Open", Application.ExecutablePath);
pai.DefaultIcon = new ProgramIcon(Application.ExecutablePath);
}
}
}
As you can see I only pass the application's path to open it up. But how can I pass the file path as argument now? I've seen that e.g. the author of the article passes "%1" as argument, I tried that, too, but nothing changed.
Thanks in advance.
ProcessStartInfo.FileName usually gives you the path to your program executable itself, not the file which was clicked in Windows Explorer, so this seems the wrong thing to check in your case.
If you want to get the arguments using the current Process, then Process.GetCurrentProcess().StartInfo.Arguments should give you a string containing all the arguments passed to the program. If there are multiple arguments, you would need to parse these into separate values yourself.
But the standard, simpler way to get the arguments is to make sure the Main() method of your program has signature static void Main(string[] args){}. args is already processed into separate values for you, so it is easier to handle it here, even if you only pass it off to another class or store them in a static variable.
The %1 should ensure the clicked file is passed as the first argument (args[0]) to your program.
Well, I got it. What I had to do was creating a subkey in ClassesRoot: "ProgramName\shell\open\command". Then set a value containing the application's path and attach "%1" to it and you're done.
I am using the following command to set a value to the environmental variable in a c# Console application.
System.Environment.SetEnvironmentVariable(envvar, result,EnvironmentVariableTarget.Process);
After running the application in the command window, when I try to echo that variable ,I cannot see the value.
I have to use this application in a batch file.
I want the functionality like SET command. Please help..
Edit:
I tried using System.Environment.SetEnvironmentVariable(envvar,result,EnvironmentVariableTarget.user) and to propagate the change I tried this Propagating Change in Env VAr. But I cant echo the variable in same command window.
Let me rephrase the question:
I want to set a value to a Env Var in c#. I must be able to use that variable in same command window (ie i should not open a new cmd window to see the change). We use SET command and we can use that variable immediately .. rt ? I want such functionality. Plzz help
When you use EnvironmentVariableTarget.Process the variable set will only visible in the current process as you can see in this sample:
System.Environment.SetEnvironmentVariable("myVar", "myValue", EnvironmentVariableTarget.Process);
string s = System.Environment.GetEnvironmentVariable("myVar",EnvironmentVariableTarget.Process);
Above myVar will show s = "myValue" but not visible in command window.
If you want to set the value visible at command windows then you need to use EnvironmentVariableTarget.User:
System.Environment.SetEnvironmentVariable("myVar", "myValue", EnvironmentVariableTarget.User);
This way the setting myVar=myValue will be stored and then you can see on command windows.
A detailed sample is located here
In order to see the env in the current batch process. You have to output it in you program as string and parse it and call set in the batch file.
Or you can try EnvironmentVariableTarget.User. The env will be visible in all new processes when setted with this option.
I'm trying to copy a file over to a networked folder on a mapped drive. I tested out COPY in my command line which worked, so I thought I'd try automating the process within C#.
ProcessStartInfo PInfo;
Process P;
PInfo = new ProcessStartInfo("COPY \"" + "c:\\test\\test.txt" + "\" \"" + "w:\\test\\what.txt" + "\"", #"/Z");
PInfo.CreateNoWindow = false; //nowindow
PInfo.UseShellExecute = true; //use shell
P = Process.Start(PInfo);
P.WaitForExit(5000); //give it some time to finish
P.Close();
Raises an exception : System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
What am I missing? Would I have to add anything else to the command parameters?
I've tried File.Copy but it doesn't appear to work (File.Exists("<mappeddriveletter>:\\folder\\file.txt");) brings up false.
This SO post contains an example
Run Command Prompt Commands
how to do it right. You need to call cmd.exe with /c copy as a parameter.
Well, for the technical bit: copy in itself is not an executable, but merely a command interpreted by cmd. So basically, you'd have to start cmd.exe as a process, and pass it a flag that makes it run the copy command (which you'll also have to supply as a parameter).
Anyways, I'd side with Promit and recommend looking into File.Copy or something similar.
e: Ah, missed your comment on Promit's answer when I posted this.
Wouldn't it be a lot easier to use File.Copy ?
how to translate system("") to C# without calling cmd.exe?
edit: i need to throw something like "dir"
If I correctly understood your question, you're looking for Process.Start.
See this example (from the docs):
// Opens urls and .html documents using Internet Explorer.
void OpenWithArguments()
{
// url's are not considered documents. They can only be opened
// by passing them as arguments.
Process.Start("IExplore.exe", "www.northwindtraders.com");
// Start a Web page using a browser associated with .html and .asp files.
Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
}
Edit
As you said you needed something like the "dir" command, I would suggest you to take a look at DirectoryInfo. You can use it to create your own directory listing. For example (also from the docs):
// Create a DirectoryInfo of the directory of the files to enumerate.
DirectoryInfo DirInfo = new DirectoryInfo(#"\\archives1\library");
DateTime StartOf2009 = new DateTime(2009, 01, 01);
// LINQ query for all files created before 2009.
var files = from f in DirInfo.EnumerateFiles()
where DirInfo.CreationTimeUtc < StartOf2009
select f;
// Show results.
foreach (var f in files)
{
Console.WriteLine("{0}", f.Name);
}
As other folks noted, it's Process.Start. Example:
using System.Diagnostics;
// ...
Process.Start(#"C:\myapp\foo.exe");
I need to throw something like "dir"
If you need to run DIR, then you need to call cmd.exe as dir is internal to cmd.exe
Not sure if I understand your question. Are you looking for Process.Start?
Do you actually want the equivalent? You may not depending on what exactly you're trying to do.
For example calling copy from the command line has a C# equivalent itself, File.Copy, for dir there's a whole Directory class for getting info (these are a quick 2 out of thousands of examples). Depending on what you're after, C# most likely has a library/function for the specific command you're trying to run, usually a more robust method as well, instead of a global handler.
If the global "invoke this" is what you're after, then as the other answers suggest, using the System.Diagnostics.Process class is your best bet.
If you want to execute a command-line (cmd.exe) command, such as "dir" or "time" or "mkdir", pass the command as an argument to cmd.exe with the flag /C.
For example,
cmd.exe /C dir
or
cmd.exe /C mkdir "New Dir"