Question:
I created a class in a ps1 file that works just fine IN the ps1 file itself. I can run various tests with the class and the tests in the same file.
My trouble is I don’t seem to be able to find a way to put my Class in one file and the Class Usage code in another.
With functions, you can just dot source them to bring any external ps1 files into your current script. It looks like Classes for Powershell do not work this way.
How can I organize code to keep classes in separate files from the executing script?
Do I have to use modules? How do I do that?
Answer:
In the file Hello.psm1
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Hello { # properties [string]$person # Default constructor Hello(){} # Constructor Hello( [string]$m ){ $this.person=$m } # method [string]Greetings(){ return "Hello {0}" -f $this.person } } |
In the file
main.ps1
:
1 2 3 4 5 6 7 8 |
using module .\Hello.psm1 $h = New-Object -TypeName Hello echo $h.Greetings() #$hh = [Hello]::new("John") $hh = New-Object -TypeName Hello -ArgumentList @("Mickey") echo $hh.Greetings() |
And running
.\main.ps1
:
1 2 3 |
Hello Hello Mickey |