Im following this question but I can't seem to get this working.
(For the sake of testing) I have a powershell module with 2 scripts: variables.ps1 and function.ps1 and a manifest mymodule.psd1 (These files are all in the same directory)
This is the content of variables.ps1:
$a = 1;
$b = 2;
This is the content of function.ps1
. .\variables.ps1
function myfunction
{
write-host $a
write-host $b
}
When I import the module and call myfunction. This is the output:
C:\> Import-Module .\mymodule.psd1
C:\> myfunction
. : The term '.\variables.ps1' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\Jake\mymodule\function.ps.ps1:8 char:4
+ . .\variables.ps1
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\variables.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
Why doesn't this work?
When you use relative paths in scripts, they're relative to the callers $PWD
- the current directory you're in.
To make it relative to the directory where the current script is located on the file system, you can use the automatic variable $PSScriptRoot
. (Join-Path $PSScriptRoot variables.ps1)
The $PSScriptRoot
variable is introduced in PowerShell version 3.0, for PowerShell 2.0 you can emulate it with:
if(-not (Get-Variable -Name 'PSScriptRoot' -Scope 'Script')) {
$Script:PSScriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
}
. (Join-Path $PSScriptRoot variables.ps1)
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