Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use New-Object of a class present in a C# DLL using PowerShell

Tags:

c#

powershell

I have a class in C# say for example

public class MyComputer : PSObject
{
    public string UserName
    {
        get { return userName; }
        set { userName = value; }
    }
    private string userName;

    public string DeviceName
    {
        get { return deviceName; }
        set { deviceName = value; }
    }
    public string deviceName;
}

which is derived from PSObject. I am loading the DLL having this code in powershell using import-module. Then I tried to create a new object of the MyComputer class in PowerShell.

PS C:> $MyCompObj = New-Object MyComputer

but it throws an error saying make sure assembly containing this type is loaded. Note: I am able to call Cmdlets successfully which is present in the DLL.

I am not sure is this the right way to go ahead on creating a new object. Please correct to me make this work.

like image 681
Shaj Avatar asked Sep 08 '10 09:09

Shaj


People also ask

How do you initialize a new object class?

Initializing an Object The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments: Point originOne = new Point(23, 94);

When a new object is created from a class it is called?

The variables p and q are assigned references to two new Point objects. A function like Turtle or Point that creates a new object instance is called a constructor, and every class automatically provides a constructor function which is named the same as the class.


2 Answers

First, make sure the assembly is loaded using

[System.Reflection.Assembly]::LoadFrom("C:\path-to\my\assembly.dll")

Next, use the fully qualified class name

$MyCompObj = New-Object My.Assembly.MyComputer
like image 74
devio Avatar answered Oct 21 '22 18:10

devio


You don't need to have PSObject as base. Simply declare class without base.

Add-Type -typedef @"
public class MyComputer
{
    public string UserName
    {
        get { return _userName; }
        set { _userName = value; }
    }
    string _userName;

    public string DeviceName
    {
        get { return _deviceName; }
        set { _deviceName = value; }
    }
    string _deviceName;
}
"@

New-Object MyComputer | fl *

Later when you will work with the object, PowerShell will automatically wrap it into PsObject instance.

[3]: $a = New-Object MyComputer
[4]: $a -is [psobject]
True
like image 27
stej Avatar answered Oct 21 '22 19:10

stej