Run ps1 for command line, vs the "run script" button in ISE

Hello all, I’m new to this forum so if I do something wrong please let me know.

I’m new to powershell but not new to object oriented programming (not a pro). What I noticed that there is a difference in the way scripts can be loaded, or run. Take this sample script for example:

class do{
[string]$var="one";
[void] test(){
Write-Host ('test stuff');
}
}
$do=[do]::new();
Write-Host ('loaded');

It contains a constructor that creates an object $do.

In powershell ISE:

-If I run this sctipt from the command line ./test.ps1. It gives back “loaded”. But the object $do does not exists. And I can not make a new object $do form the command line. The “do” class does not exists at all.

-If I click on the run icon, or press f5, you can see that the commandline is filled with the path of het scipts location, and it also gives back “loaded”. But now the object $do does exist, and $do.var gives back “one”.

So what is the difference??

The goal is to load a bunch of classes.ps1 files to get access to the objects. But when I try to do that the objects are not available. Does anyone know how to load a class like this form the commandline or from another script? All help is very appreciated !!

Hi, welcome to the forum :wave:

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working).

As to your question, this is to do with scopes. When you run the script, the $do variable - the instance of the do class - is being created in the script scope and it’s only accessible to that scope. When the script finishes running, it no longer exists.

If you want to bring it into the local scope, you need to dot source the script:

PS E:\Temp> . .\do.ps1
PS E:\Temp> $do.test()
test stuff
PS E:\Temp> $do2 = [do]:new()
PS E:\Temp> $do2.test()
test stuff
1 Like

Thank you very much!!! It works!!! :grinning: So that is the difference between the f5 and commandline. I changed the script between the preformatted text. I will check the documentation you added. Thank again, you helped me a lot! :sunglasses:

Glad it helped.

When you run a script in the console, a container is created to run the script. Dot-sourcing runs the script without creating the container so scoped elements such as variables and functions persist in the global scope when the script finishes running.

When you run your scripts in the ISE a container is not created and all scoped elements persist in the global scope. This can lead to some unexpected results if you don’t initialise your variables or clean up after yourself.