Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a C# .cs file from a PowerShell Script

Tags:

c#

powershell

I have a PowerShell V2 script that moves some files around and installs some services. However I would like to call and run a .cs file about halfway through the PowerShell Script. I have found plenty of articles on calling PowerShell from C# but none the opposite way around. I would just like the C# file to run once then continue running the PowerShell script.

If anyone could point me in the direction of an article explaining how to accomplish this or if you know yourself and could help it would be greatly appreciated.

like image 746
Foster Avatar asked Jul 21 '14 14:07

Foster


People also ask

Where do I run my AC code?

Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click on New. Step 2: Write the C program code. Step 3: Click on Compile or press Alt + F9 to compile the code. Step 4: Click on Run or press Ctrl + F9 to run the code.


2 Answers

I saw no reason why we couldn't run a .cs file directly from PowerShell, so I took Keith's snip and added the missing Get-Content parts to do literally what the OP asks for. No need to compile your code, just edit the -Path argument to point to your .cs file.

$source = Get-Content -Path "A:\basic.cs" Add-Type -TypeDefinition "$source"  # Call a static method [BasicTest]::Add(4, 3)  # Create an instance and call an instance method $basicTestObject = New-Object BasicTest $basicTestObject.Multiply(5, 2) 

Basic.cs

public class BasicTest {     public static int Add(int a, int b)     {         return (a + b);     }      public int Multiply(int a, int b)     {         return (a * b);     } } 
like image 69
Knuckle-Dragger Avatar answered Oct 11 '22 02:10

Knuckle-Dragger


You can use Add-Type to compile C# code and add it to the current PowerShell session. Then you call the C# code like you would any other .NET framework code. This is an example from the man page on Add-Type:

PS C:\>$source = @" public class BasicTest {   public static int Add(int a, int b)     {         return (a + b);     }   public int Multiply(int a, int b)     {     return (a * b);     } } "@  PS C:\>Add-Type -TypeDefinition $source PS C:\>[BasicTest]::Add(4, 3) PS C:\>$basicTestObject = New-Object BasicTest PS C:\>$basicTestObject.Multiply(5, 2) 
like image 31
Keith Hill Avatar answered Oct 11 '22 03:10

Keith Hill