Reputation: 185
So let's say I have a script at C:\scripts\MyScript.ps1 which is simply:
Get-Content ".\text.txt"
In C:\scripts I also have a file, text.txt, which contains arbitrary text which gets printed when the script is called. This script works fine if I use it when PowerShell's current directory is C:\scripts. However, if PowerShell is currently in a different directory, e.g. C:\otherFolder, then calling the script thusly from the PoSh command window fails:
PS C:\otherFolder> ..\scripts\MyScript.ps1
which I would expect since the reference to text.txt within the script is relative and the file not present in C:\otherFolder. My question is, is there any way to write a script which has relative references to other files, which will still work as intended even if called from within a different folder?
I realize there wouldn't be a problem if the script referred to "C:\scripts\text.txt", but I want to be able to move the script (and it's dependent files) around without having to update the references in the script each time.
Thanks.
Upvotes: 2
Views: 128
Reputation: 3363
I think this related StackOverflow question provides an answer: How to get the current directory of the cmdlet being executed
You'll probably want to use $MyInvocation.MyCommand.Path
within your script
Upvotes: 2
Reputation: 60928
try this in your script:
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$path = join-path $dir "text.txt"
get-content $path
Upvotes: 3