PowerShell: how is the source of the function, for example, the source of the file?

In my main script, I will first call the init function to initiate many of the variables that I expected to be used in the script. One way is to use variables whose name is $script:var1 , which are a script-level variable. But so ugly, and I would like to use the standard variable name, so I need a mechanism for the source of the function, like the source of the file.

At the source of the file, all variables in this file are available in the calling script.

+6
powershell
source share
2 answers

Use the same syntax that dot-operator uses as for finding files:

 . My-Function 
+4
source share

You can also do this in scriptblock and dot-source, but the rules are slightly different. You must have a place after the period for the source point to perform the function, and you are not using a script block.

Both of them will produce 42

 $a=0 function init {$a=42} . init $a $a=0 $init={$a=42} .$init $a 
+1
source share

All Articles