In my main script, I will first call an init function to initiate many variables which I expected to be used in the script. One way is to use variables whose name are like $script:var1
which are script level variable. But that's kind of ugly and I'd like to use normal variable name, so I need a mechanism to source a function just like source a file.
When source a file, all the variables in that file are available in the calling script.
Use the same syntax that uses dot-operator, just like for sourcing files:
. My-Function
You can also do it in a scriptblock and dot-source that, but the rules are slightly different. You must have a space after the period to dot-source a function, and you don't with a scriptblock.
Both of these will produce 42
$a=0
function init {$a=42}
. init
$a
$a=0
$init={$a=42}
.$init
$a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With