0
votes

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

3 Answers

6
votes

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.

0
votes

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

0
votes

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.