I created a simple C# class to learn how to call C# class from powershell script. I compiled that project as "Class Library" and copied onto my C:\ drive.
Googled around and found that we need to register that .DLL with powershell using the following command.
PS C:\WINDOWS\system32> [Reflecion.Assembly]::LoadFile("C:\Calculator.dll")
PS C:\WINDOWS\system32> $ml = new-object Calculator()
At line:1 char:29
+ $ml = new-object Calculator()
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [],
ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression
I don't get any errors after that command. When I try to access the class like this, I get error. new to powershell. any suggestions please? Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator
{
public class Calculator
{
#region "Private Data Members"
private int _operandA;
private int _operandB;
#endregion "Private Data Members"
public int OperandA
{
get { return _operandA; }
set { _operandA = value; }
}
public int OperandB
{
get { return _operandB; }
set { _operandB = value; }
}
public void AddNumbers(int a, int b)
{
int c;
c = a + b;
MessageBox.Show("The addition of 2 operands is c");
}
}
}
You should add-type and then create the new object. based on your C# you namespace is Calculator and you will need to call the class from that namespace is make sure you add another calculator to your New-Object
Add-Type -Path 'C:\Calculator'
New-Object Calculator.Calculator
a working example is
Add-Type -Path 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Management.dll'
$Management = new-object System.Management.Instrumentation.Instrumentation
$Management
Output : System.Management.Instrumentation.Instrumentation
You don't need to instantiate with (), and you also need to qualify the namespace your class was defined in.
PS> [Reflection.Assembly]::LoadFile("C:\Calculator.dll")
PS> $ml = new-object Calculator.Calculator
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