In PowerShell, each script has its own scope. Anything defined in that script, for example variables and functions, exists only within that scope.
You can’t access those items from the scope where the script is run… only from within the script.
So a function inside the script can call another function inside the script, but you can’t call a function defined in the script from the scope where you run/call the script.
Let that one sink in a little 😉
So what if you want to make something available in your current scope, that is defined within a script.
Normally I would tell people to write a module, but in the case of a customer I was at last week they needed to manage servers where they were not allowed to place a module.
This is an ongoing discussion, but for now we needed to make things work.
I like re-usable code… I like it a lot.
So creating many scripts with the same functions, and just a little bit of code that differs, would have been madness… or at least, that’s my opinion.
This is where dot sourcing helps out 🙂
Let’s say that you have a script where you define a whole bunch of variables and/or functions that you want to make available in your current scope.
Call a script like so:
So, simply but a dot in front of the script 😉 You’ll notice that the things defined in that script, will now be available in your current scope.
Neat little trick, right?!
[…] you will need to dot source them first in order to use them. Dutch PowerShell MVP Jeff Wouters has a good article on this in case you want some more info on […]