how to export a class in powershell v5 module

后端 未结 10 690
不思量自难忘°
不思量自难忘° 2020-12-08 14:53

I\'ve got a module setup to be like a library for a few other scripts. I can\'t figure out how to get a class declaration into the script scope calling Import-Module

10条回答
  •  轮回少年
    2020-12-08 15:11

    the using statement is the way to go if it works for you. otherwise this seems to work as well.

    testclass.psm1

    Use a function to deliver the class

    class abc{
        $testprop = 'It Worked!'
        [int]testMethod($num){return  $num * 5}
    }
    
    function new-abc(){
        return [abc]::new()
    }
    
    Export-ModuleMember -Function new-abc
    

    someScript.ps1

    Import-Module path\to\testclass.psm1
    $testclass = new-abc
    $testclass.testProp        # returns 'It Worked!'
    $testclass.testMethod(500) # returns 2500
    
    
    $testclass | gm
    
    Name        MemberType Definition
    ----        ---------- ----------
    Equals      Method     bool Equals(System.Object obj)
    GetHashCode Method     int GetHashCode()
    GetType     Method     type GetType()
    testMethod  Method     int testMethod(System.Object num)
    ToString    Method     string ToString()
    testprop    Property   System.Object testprop {get;set;}
    

提交回复
热议问题