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.
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.
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)
public class BasicTest { public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); } }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With