PowerShell is a cross-platform language build on top of .Net framework which accepts and returns objects. PowerShell can access the libraries written in C#, VB, jScript.
Scripts are usually build using PowerShell cmdlets but we can use the libraries coded in C#.
Embed C# (CSharp) code directly in PowerShell
Below example shows how to use C# (CSharp) code directly in PowerShell
#Defining Class in C# with functionality methods
$Source = @"
using System;
namespace CustomNamespace
{
public class CustomClass
{
//Function to Split the string
public string[] Split(string value, char delimiter)
{
string[] strArray = value.Split(delimiter);
return strArray;
}
//Function to sort
public string[] Sorts(string[] strArray)
{
Array.Sort(strArray);
return strArray;
}
}
}
"@
#Adding the C# source code to powershell
Add-Type -TypeDefinition $Source -Language CSharp
#Creating the object of the class defined in C#
$objCustomClass = New-Object CustomNamespace.CustomClass
#Sorting array of string
"Sorting array of string`n" | Out-Host
$arrays = "b","a","c"
"Original array" | Out-Host
$arrays
#Sorting using C# custom method
"Sorted array using C#" | Out-Host
$objCustomClass.Sorts($arrays)
#Sorting using PowerShell by using dotnet class
"Sorted array using PowerShell" | Out-Host
[Array]::Sort($arrays)
$arrays
#Split string
"`n`nSplit function`n" | Out-Host
$str = "one,two,three"
$delimiter = ","
"Source string is : " + $str + " `nand delimiter is : " + $delimiter + "`n"| Out-Host
#Split using C# custom method
"Split string using C#" | Out-Host
$objCustomClass.Split($str, $delimiter)
#Split using powershell
"Split string using PowerShell" | Out-Host
$str.Split($delimiter)
Result
Benefits of using C# (CSharp) in PowerShell
- .Net codes are faster than PowerShell scripts
- Can use the existing libraries coded in C# or vb
Hope this is helpful and thank you for reading.
Recent Comments