Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading a modified class in Powershell

I've a script file containing a class definition. Using the new V5 Powershell syntax. I've another script file that dot source the class and uses it. I'm testing that file in the console.

On clean startup of the console it will load the class correctly. I then make some changes to the class and saved them back to file. Re-running the script does not appear to pick the changes up. It is as though once loaded into the console, the class is immutable and will not be parsed and reloaded.

This really hurt when developing, since I have to spin up a new console after any change to a class.

Is there a way to force Powershell to reload classes each time it sees them?

This occur in code debugged both in Powershell ISE and in the Powershell console (using vscode).

like image 454
Dov Reshef Avatar asked Nov 30 '16 06:11

Dov Reshef


People also ask

How do I import a class in PowerShell?

But, to import the classes defined in a module into your session, you can't use Import-Module or even #Requires -Module. Instead, use the Using statement, introduced in PowerShell 5.0, which imports the module, including its classes, into the caller's session.

How do I reload a PowerShell module?

Tip: You can reload a module by using the –Force parameter. It can be useful during development when you updated your module and you want to see your latest changes.

Are there classes in PowerShell?

PowerShell 5.0 adds a formal syntax to define classes and other user-defined types. The addition of classes enables developers and IT professionals to embrace PowerShell for a wider range of use cases.

Does PowerShell support OOP?

PowerShell is an object-oriented scripting language; however, moderately complex scripts are often written using a procedural/functional approach.


1 Answers

This is a known issue with classes in Powershell, and looks like the issue remains unresolved at this time of writing.

To workaround this today, you either need to start a new interactive session (which you don't want to do), or load your development class in a child instance of Powershell:

powershell.exe -Command { Your-Code }

# Alternatively, write a script to test your newly updated class
powershell.exe -File \path\to\Test-ClassScript.ps1
like image 92
Bender the Greatest Avatar answered Oct 18 '22 20:10

Bender the Greatest