C# and DLL call in Powershell Updated 160205
I recently needed to combine C# and powershell. I found varios way to combine this.
One obviuos way is to compile C#-code as a dll and call the included functions from powershell.
Another way is to actually include the source code from C# directly in a powershell script and run it.
One advantage of this is that the C# code can be run on any system that permits running powershell scripts, and
the source code can be changed very easy without a compiler.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLib
{
public class Class1
{
public static string retfromdll()
{
string retstr = "Return string from dll";
return retstr;
}
}
}
Listing 1 source code for the dll
#############################
# Csharp code in Powershell #
#############################
$Global:namestr="Testname in global var"
$Assem = ("D:\PowershellScripts\CsharpInPoweshellToPublish\ClassLib.dll")
$Source = @”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLib;
namespace ConsoleApp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello world");
}
public static string GetName()
{
string namestr;
Console.WriteLine("Enter your name: ");
namestr = Console.ReadLine();
return namestr;
}
public static void SetName(string namestr)
{
string outputstr="Name as input from Powershell: "+namestr;
Console.WriteLine(outputstr);
}
public static void SetNameByGlobalVar()
{
Console.WriteLine("Name from a global variabel from Powershell:
$Global:namestr");
}
public static void UseDllFromCS()
{
string namestr;
string outputstr;
namestr=Class1.retfromdll();
outputstr="Return from Dll called from CS: "+namestr;
Console.WriteLine(outputstr);
}
}
}
“@
#Import C# source code and load a dll
Add-Type -TypeDefinition $Source -Language CSharp -ReferencedAssemblies $Assem
[System.Reflection.Assembly]::LoadFrom("D:\PowershellScripts\CsharpInPoweshellToPublish\ClassLib.dll")
#CALL MAIN IN C#
[ConsoleApp.Program]::Main("test")
#Call a C# function without param and return a string
$NameFromCS=[ConsoleApp.Program]::GetName()
Write-Host "Name returned from CS: $NameFromCS"
Write-host "Type another name: "
#Call a C# function with a param
$NameFromPS=Read-Host
[ConsoleApp.Program]::SetName($NameFromPS)
#Call a C# function without param, but use a global declared variabel
[ConsoleApp.Program]::SetNameByGlobalVar()
#Call a C# function in a dll
$StringFromDll=[ClassLib.Class1]::retfromdll()
Write-Host "Name returned from dll: $StringFromDll"
#Call a C# function that call a function in a dll
[ConsoleApp.Program]::UseDllFromCS()
Listing 2 Powerhell code
The source code for the dll can be downloaded here. (as visual studio ce 2015 project)
The source code for the powershell script can be downloaded here.
.