Home > Software design >  Load script into a PowerShell console via an alias
Load script into a PowerShell console via an alias

Time:05-12

To load a script file into an open PS console (e.g. to import functions) dot-sourcing or the Import-module applet is needed.

Using this inside a function (to create an alias) doesn't work, e.g.:

Function psinit1 { . C:\Scripts\scriptFunktions.ps1 }
Function psinit2 { Import-module C:\Scripts\scriptFunktions.ps1 -force}

when I call psinit1 or psinit2 I don't get an error, but my functions are not available. Why doesn't this work, am I right in assuming that the function opens a new scope which loads the script (and gets closed once the function is done)?

How can I get it to work?

CodePudding user response:

Unless you invoke a function via . the dot-sourcing operator, its body executes in a child scope, so that any operations you perform inside of it - unless you explicitly target a different scope - are limited to that child scope and its descendant scopes.

Therefore, to make your functions works as intended, i.e. to make definitions visible to the caller's scope, dot-source their invocations too:

. psinit1

Generally, note that while Import-Module also accepts .ps1 scripts, its primary purpose is to act on modules. With scripts, it effectively behaves like dot-sourcing, except that repeating an Import-Module call with a .ps1 script in a child scope fails, unless -Force is also specified - in short: do not use Import-Module with .ps1 scripts.

  • Related