PowerShell is a powerful scripting language that allows you to automate various tasks on Windows operating systems. While PowerShell provides a rich set of cmdlets and functions, you may sometimes need to extend its functionality by using .NET libraries. In these cases, you can use C# code within PowerShell scripts to call .NET assemblies.

Here’s an example of calling a C# method from a PowerShell script:

“`powershell
Add-Type -TypeDefinition @”
using System;

public class MyUtils
{
public void MyMethod()
{
Console.WriteLine(“Hello from C#!”);
}
}
“@

$utils = New-Object MyUtils
$utils.MyMethod()
“`

In this script, we define a C# class `MyUtils` with a `MyMethod` method that writes a message to the console. We then use the `Add-Type` cmdlet to compile the C# code and make it available within the PowerShell script.

Next, we create an instance of the `MyUtils` class using the `New-Object` cmdlet and call the `MyMethod` method on the instance. This will execute the C# code and print “Hello from C#!” to the console.

You can also pass parameters from PowerShell to a C# method and receive return values:

“`powershell
Add-Type -TypeDefinition @”
using System;

public class MyUtils
{
public int AddNumbers(int a, int b)
{
return a + b;
}
}
“@

$utils = New-Object MyUtils
$result = $utils.AddNumbers(2, 3)
Write-Output $result
“`

In this script, we define a C# class `MyUtils` with an `AddNumbers` method that takes two integers as input and returns their sum. We create an instance of the `MyUtils` class, call the `AddNumbers` method with the parameters 2 and 3, and store the result in the `$result` variable. Finally, we use the `Write-Output` cmdlet to print the result to the console.

By combining PowerShell and C#, you can leverage the rich set of .NET libraries available to build advanced automation scripts and solutions on Windows.