I am trying to figure out how to use relative paths for Powershell scripts. I have dot sourced with absolute paths, but the scripts that I am writing may end up in a different base directory so I need to make sure the path is relative so it can be picked up. How can I do that?
So far I have tried:
. .\scripts\variables.ps1
That always throws this exception:
The term '.\scripts\variables.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program...
That lets me know it can't find my script? So, what am I doing wrong?
If the file will always be in a location relative to the script (i.e. in the same folder), we want to use the relative path. Fortunately, we can do so using $PSScriptRoot.
The dot sourcing feature lets you run a script in the current scope instead of in the script scope. When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt.
You could manually import the file with the Import-Module cmdlet. The module autoloading feature was introduced in PowerShell version 3. To take advantage of module autoloading, a script module needs to be saved in a folder with the same base name as the . PSM1 file and in a location specified in $env:PSModulePath .
A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.
You can use : . $PSScriptRoot\scripts\variables.ps1
Here $PSScriptRoot
is the path of directory of the running script.
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