How to pass arguments in command line using dotnet? - c#

the command
dotnet myapp.dll -- [4, 3, 2] throws the exception System.FormatException: Input string was not in a correct format.
I do not know the syntax. How should I pass arguments correctly?
I use powershell.

using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Join('-', args));
}
}
}
Call it via Powershell 6:
dotnet .\ConsoleApp3.dll "[1,2,3]"
Output:
[1,2,3]
In the above call, your Main method will receive [1,2,3] as a single string and you have to parse/split it in your code.
If you want an array reflected in the string[] array of Main you can use a PowerShell array:
dotnet .\ConsoleApp3.dll #(1,2,3)
Output:
1-2-3
Here the PowerShell array #(1,2,3) is casted to a string[]-array. Therefore each item of the PowerShell array is injected to the string[] array.
Behavior is the same on PowerShell 5.1.

Related

Command Line Parser library giving 'System.Type' error in C#

I'm writing a Console App (.NET Framework) in C#. I want to use arguments from the command line, and I'm trying to use the Command Line Parser library to help me do this.
This is the package on Nuget - https://www.nuget.org/packages/CommandLineParser/
I found out about it from this StackOverflow question - Best way to parse command line arguments in C#?
MWE
using System;
using CommandLine;
namespace CLPtest
{
class Program
{
class SomeOptions
{
[Option('n', "name")]
public string Name { get; set; }
}
static void Main(string[] args)
{
var options = new SomeOptions();
CommandLine.Parser.Default.ParseArguments(args, options);
}
}
}
When I try create a minimal working example, I get an error for options on this line:
CommandLine.Parser.Default.ParseArguments(args, options);
The error is Argument 2: cannot convert from 'CLPtest.Program.SomeOptions' to 'System.Type'
I'm really confused as I have seen this same example code on at least 3 tutorials for how to use this library. (see for example - Parsing Command Line Arguments with Command Line Parser Library)
(This answer is being written at the time of v2.7 of this library)
From looking at their repository's README, it appears as if this is part of the API change that is mentioned earlier in the README. It looks as though the arguments are now handled differently since the example code you reference. So, now you should do something like this inside of Main:
...
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<SomeOptions>(args);
}
...
To actually do something with those options you can use WithParsed which takes in the options that are defined in your SomeOptions class.
...
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(option =>
{
// Do something with your parsed arguments in here...
Console.WriteLine(option.Name); // This is the property from your SomeOptions class.
});
}
...
The C# Example further down the README shows that you can pass in a method into WithParsed to handle your options instead of doing everything within Main.

How to set C# application to accept Command Line Parameters? [duplicate]

This question already has answers here:
Best way to parse command line arguments in C#? [closed]
(20 answers)
Closed 5 years ago.
I have created a C# command line application that creates a few reports automatically for my client. However, even though they use 95% of the same code I would like to split them in to different processes. I am using Windows task scheduler to run them. How do I set up the C# application to accept Command line parameters upon runtime?
I cannot find any explanation of this on the internet.
All command line parameters are passed to your application through string[] args parameter. The code below shows an example:
using System.Linq;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("/REPORT1"))
{
/* Do something */
}
else if (args.Contains("/REPORT2"))
{
/* Do something */
}
}
}
}
Then, in command prompt just use:
C:\MyApp\MyApp.exe /REPORT1
MSDN
The below snippet will print the number of parameters passed from the command line... string[] args contains the parameter values...
class TestClass
{
static void Main(string[] args)
{
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}

C#: matlab.Feval command does not work

I get this error message:
Error 1 No overload for method 'Feval' takes 2 arguments
My matlab function which i call in c# has only one input argument (txt-File)! If i use the command "Feval" it says i need 2 arguments... But which 2arguments? I have only one input parameter... Thank you
The problem:
//matlab.Feval("test_2",input,res); -> Trouble
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(#"cd C:\Users\z003dukj\Documents\MATLAB\test_2");
string[] input = System.IO.File.ReadAllLines(#"C:\Users\z003dukj\Documents\MATLAB\aaaa.txt");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("test_2",input);
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
}
}
The second input to Feval should be the expected number of output arguments of your custom function. In your case, that appears to be zero, so your call to Feval should be
matlab.Feval("test_2", 0, input);

Have PowerShell script use C# code, then pass arguments to Main method

I found a technet blog article the said it was possible to have PowerShell use C# code.
Article: Using CSharp (C#) code in Powershell scripts
I found the format I need to get the C# code to work in PowerShell, but if it don't pass the Main method an argument ([namespace.class]::Main(foo)) the script throws an error.
Is there a way I can pass a string of "on" or "off" to the main method, then depending on which string is passed run an if statement? If this is possible can you provide examples and/or links?
Below is the way I'm currently trying to structure my code.
$Assem = #( //assemblies go here)
$source = #"
using ...;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args )
{
if(args == on)
{//post foo }
if(arge == off)
{ //post bar }
}
"#
Add-Type -TypeDefinition $Source -ReferencedAssumblies $Assem
[AlertsOnOff.onOff]::Main(off)
#PowerShell script code goes here.
[AlertsOnOff.onOff]::Main(on)
Well to start, if you are going to compile and run C# code, you need to write valid C# code. On the PowerShell side, if you invoke Main from PowerShell, you need to pass it an argument. PowerShell will automatically put a single argument into an array for you, but it won't insert an argument if you don't have one. That said, its not clear why this is in a Main method. It's not an executable. It could very well just have two static methods, TurnOn and TurnOff. The code below compiles and runs, modify as you see fit:
$source = #"
using System;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args)
{
if(args[0] == `"on`")
{
Console.WriteLine(`"foo`");
}
if(args[0] == `"off`")
{
Console.WriteLine(`"bar`");
}
}
}
}
"#
Add-Type -TypeDefinition $Source
[AlertsOnOff.onOff]::Main("off")
# Other code here
[AlertsOnOff.onOff]::Main("on")

Run PSCmdLets in C# code (Citrix XenDesktop)

I'm new to PowerShell and running PowerShell cmd-lets in C#. Specifically, I'm trying to use Citrix's XenDesktop SDK to write a web app to manage our XenDesktop environment.
Just as a quick test, I made a reference to the Citrix BrokerSnapIn.dll, which looks like it gives me good C# classes. However, when I hit the .Invoke with this error message:
"Cmdlets derived from PSCmdlet cannot be invoked directly."
I've searched and tried a bunch of stuff, but don't know how to call PSCmdlets. I'm kinda left thinking that I have to use strings and a runspace/pipeline, etc, to do this.
Thanks In Advanced,
NB
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Citrix.Broker.Admin.SDK;
namespace CitrixPowerShellSpike
{
class Program
{
static void Main(string[] args)
{
var c = new GetBrokerCatalogCommand {AdminAddress = "xendesktop.domain.com"};
var results = c.Invoke();
Console.WriteLine("all done");
Console.ReadLine();
}
}
}
You need to host the PowerShell engine in order to execute a PSCmdlet e.g. (from the MSDN docs):
// Call the PowerShell.Create() method to create an
// empty pipeline.
PowerShell ps = PowerShell.Create();
// Call the PowerShell.AddCommand(string) method to add
// the Get-Process cmdlet to the pipeline. Do
// not include spaces before or after the cmdlet name
// because that will cause the command to fail.
ps.AddCommand("Get-Process");
Console.WriteLine("Process Id");
Console.WriteLine("----------------------------");
// Call the PowerShell.Invoke() method to run the
// commands of the pipeline.
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(
"{0,-24}{1}",
result.Members["ProcessName"].Value,
result.Members["Id"].Value);
}
}

Categories