0

I am trying to write a powershell script to call a method that's located in my Visual Studio (2010) solution. What is the syntax for calling, for example, a method like

public void CreateData(string s, int i)

?

3 Answers 3

6

You can compile your class library project into a dll then load the dll using reflection in powershell. Here is an example:

c# code:

public class MyClass {
    public void CreateData(string s, int i) {
        // your logic here
    }
}

powershell code:

$lib = [Reflection.Assembly]::LoadFile("C:\path\to\MyClass.dll")
$obj = new-object MyClass
$result = $obj.CreateData("s_value",5)

This code assumes that your class is called "MyClass". You may have to run set-executionpolicy RemoteSigned in powershell first.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use LoadFrom instead if you want to specify a relative path to a DLL
0

You will need to build you C# class and use something like InvokeCSharp to call the CreateData method

Please see the link for a good example http://vincenth.net/blog/archive/2009/10/27/call-inline-c-from-powershell-with-invokecsharp.aspx

Comments

0

I would create a program like that:

class Program
{
    static void Main(string[] args)
    {
        if(args.Length > 1)
            CreateData(args[0], int.Parse(args[1]));
    }

    public static void CreateData(string s, int i)
    {
        File.WriteAllText(@"C:\data.txt", 
              string.Format("This is some data:  s = {0}  i = {1}", s, i)); 
    }
}

And then after the program is compiled I have the executable "ConsoleApp.exe"

I launch the folowing powershell script:

& "Path_Of_The_Program\ConsoleApp.exe" "MyText" 100

It successfully writes the data inside my file.

2 Comments

Thanks for your response. I can get my class to open using the syntax you gave me, but I can't get the specific method called. I tried going like myclass.cs/CreateData, but this didn't work. Any ideas?
You need to compile your class first and then launch the command with the .exe file path. You can build your class using the csc command line utility ( msdn.microsoft.com/en-us/library/78f4aasd.aspx )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.