6

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?

4
  • Just create a module and use the using directive: stackoverflow.com/questions/31051103/… Jan 1, 2018 at 16:57
  • Can you elaborate and possibly offer a simple example of what the content of both files would look like? I have read the reference you sent already.. read it many times and tested every example on that link... NONE of them work consistently. Jan 1, 2018 at 17:20
  • I guess I should elaborate. By not working consistently I mean I have to shut down the console window/Powershell editor in order for any file changes to actually take. It looks like MS caches these modules someplace, so when you re-run them, your delta gets ignored/overlooked. The using statement does help, but it's not enough. Jan 1, 2018 at 22:17
  • The fact that "using module" does not reload is a known shortcoming. I recommend you upvote this issue on Github for getting it fixed in PSCore: github.com/PowerShell/PowerShell/issues/7654
    – Dave_J
    Oct 24, 2018 at 8:26

3 Answers 3

4

In the file Hello.psm1:

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:

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:

Hello 
Hello Mickey
1

This may not apply to your case, but I have had nightmares with PowerShell caching information (in my case it was just for modules). Things I'd changed in the module weren't being properly loaded - even after a reboot.

I found deleting the cache stored in a subdirectory of C:\Users\<YourUsername>\AppData\Local\Microsoft\Windows\PowerShell solved my issue.

0

The simplest solution is to use the using keyword, at the very beginning of your script :

using module .\path\to\your\Module.psm1

Path can be relative from your current file.

To prevent caching problem, use powershell.exe .\script.ps1 to execute it, even in the PoweShell ISE console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.