Can we implement .NET interfaces in PowerShell scripts?

Suppose we have several interfaces defined in the .NET class library written in C #. Is there a way to implement these interfaces in a PowerShell script?

Call it a business need. As a supplier, we provide several interfaces that our customers use to use our product. One of our customers wants to do this from a PowerShell script.

+6
source share
3 answers

Although you cannot directly implement the interface from powershell, you can pass powershell delegates to .NET code . You can provide an empty implementation of an interface that accepts delegates in the constructor and build this object from powershell:

public interface IFoo { void Bar(); } public class FooImpl : IFoo { Action bar_; public FooImpl(Action bar) { bar_ = bar; } public void Bar() { bar_(); } } 

And in powershell:

 $bar = { Write-Host "Hello world!" } $foo = New-Object FooImpl -ArgumentList $bar # pass foo to other .NET code 
+4
source

Here is a simple PowerShell 5.0 example that implements the .Net IEqualityComparer interface:

 Class A:System.Collections.IEqualityComparer { [bool]Equals($x,$y) { return $x -eq $y } [int]GetHashCode($x) { return $x.GetHashCode() } } [A]$a=[A]::new() $a.Equals(1,1) -- returns True $a.Equals(1,2) -- returns False $a.GetHashCode("OK") -- returns 2041362128 

You may even have a class (called A) that inherits from another class (called B) and implements IEqualityComparer:

 Class A:B,System.Collections.IEqualityComparer { 
+9
source

You can use Add-Type to define a class in C #, JScript or VBScript. When there is a vendor assembly, it should only be loaded before the Add-Type call with another Add-Type call:

 $sourceCode = @" public class CustomerClass : Vendor.Interface { public bool BooleanProperty { get; set; } public string StringProperty { get; set; } } "@ # this here-string terminator needs to be at column zero $assemblyPath = 'C:\Path\To\Vendor.dll' Add-Type -LiteralPath $assemblyPath Add-Type -TypeDefinition $sourceCode -Language CSharp -ReferencedAssemblies $assemblyPath $object = New-Object CustomerClass $object.StringProperty = "Use the class" 
+6
source

All Articles