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

前端 未结 4 1866
Happy的楠姐
Happy的楠姐 2021-02-19 06:32

I have a class in C# say for example

public class MyComputer : PSObject
{
    public string UserName
    {
        get { return userName; }
        set { userN         


        
相关标签:
4条回答
  • 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
    
    0 讨论(0)
  • 2021-02-19 07:10

    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
    
    0 讨论(0)
  • 2021-02-19 07:12

    Here is how it got working.

    public class MyComputer
    {
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
        private string userName;
    
        public string DeviceName
        {
            get { return deviceName; }
            set { deviceName = value; }
        }
    
        public string deviceName;
    }
    
    //PS C:\> $object = New-Object Namespace.ClassName
    PS C:\> $object = New-Object Namespace.MyComputer
    PS C:\> $object.UserName = "Shaj"
    PS C:\> $object.DeviceName = "PowerShell"
    
    0 讨论(0)
  • 2021-02-19 07:13

    Is the MyComputer class in a namespace? If so, you probably need to use the namespace-qualifed name of the class in the New-Object command.

    Also, PowerShell does not like the public names DeviceName and deviceName which differ only in case. You probably meant to declare deviceName private. (But why not use auto-properties?)

    Finally, stej is correct. There is no need to derive the MyComputer class from PSObject.

    0 讨论(0)
提交回复
热议问题