by MichaelPS at 2013-04-19 03:09:17
Hi there,by happysysadm at 2013-04-19 03:35:21
I’ve got a script, “Set-PinnedApplication.ps1”. In this script I have a function called Set-PinnedApplication.
In another script, let’s call it “CostumStartMenu.ps1” I have to use the function Set-PinnedApplication. Therefore I want to load the “Set-PinnedApplication.ps1” at the beginning of the script. Actually this isn’t a big deal, I just have to enter “&”, the path and scriptname. But this is with fixed path.
I need it relative to the path, where my “CostumStartMenu.ps1” is stored. Then I just have to copy the “Set-PinnedApplication.ps1” in the same directory as the “CustomStartMenu.ps1” and it works - no matter where that directory ist. I already tried zu type “& .\Set-PinnedApplication.ps1”, but it seems, that this is only realtive to the current path. If i run the script, for example, by typing C:> D:\Scripts\CostumStartMenu.ps1 this doesn’t work, propably becaus .\Set-PinnedApplication.ps1 means in this case C:\Set-PinnedApplication.ps1. But it is in D:\Scripts\Set-PinnedApplication.ps1.
Can you help me, finding out the best way to achieve that goal? I’m really stuck with this.
I had some trouble understanding your problem. The proper syntax to dot source a script in the same path as the caller is to add the following line:by MichaelPS at 2013-04-19 03:47:20
Can you try?
Hi,by happysysadm at 2013-04-19 05:16:52
thanks, but I just tried it and it didn’t work. The file could not be found.
Both those scripts are in the same folder, right?by MichaelPS at 2013-04-19 06:06:21
Yes, right! I’m in C:\ in Powershell and run the script by typing & ‘D:\Scripts\CustomStartMenu.ps1’. Both files are in D:\Scripts. Since this is going to be a logon script, the pathes can change and have to be relative.by MichaelPS at 2013-04-19 06:19:22
I just found a solution. I had to do this:by MasterOfTheHat at 2013-04-19 06:58:00
[code2=powershell]$scriptpath = $MyInvocation.MyCommand.Path | Split-Path -Parent
$scriptname = “Script.ps1”
. (Join-Path $scriptpath $scriptname)[/code2]
This works for me. Thank you a lot anyways!
Yeah, dot sourcing is relative to the current scope. That means that, since you’re running the script from C:, the dot source is going to look relative to C:. If you actually ran it from D:\Scripts, it would work.
What you found will work a little better if you are going to be invoking the script from somewhere other than the script’s location. That actually pulls the path of the script file and uses it to build the imported scripts absolute path.