Problem
I am working with Jenkins to deploy PowerShell scripts remotely. As such, I am trying to figure out if there will be problems utilizing $PSScriptRoot
over $MyInvocation.MyCommand.Path
for getting the current scripts root directory.
Details
A colleague in passing told me that utilizing $PSScriptRoot
would be a bad idea for remote functionality as I might occasionally find that it does not return the expected value at runtime for one reason or another, even if it worked previously. However, could not explain why that would be.
In my research, I have not found anything on this that could explain this further or what the best practice way for avoiding such a problem would be. I primarily found that these two are basically interchangeable; however, $PSScriptRoot
can only be used in PowerShell v3 or later. And through the help of several of you already, I have also come to learn that $MyInvocation
has situational differences that allows it to change based on scope and module. But I still haven't found out if or why this would be a problem with PowerShell Remoting.
Example 001
So I have a PowerShell script in Jenkins, that uses $PSScriptRoot
to act as the means of finding a script I wish to call via a relative path. Would I be able to rely on this to always provide the same/expected path to said script?
Example 002
Using a PowerShell script that was called by a PowerShell script that Jenkins initiated, would I be able to expect $PSScriptRoot
to be able to provide me with the path of where that script actually sits, or would it give me a path based on Jenkins?
Personally, I am expecting both to be that $PSScriptRoot
will provide me with the actual physical location of the script that is running rather than a relative path that changes based on the initial script that called it.
Since having this understanding would help save me a lot of time and headache, I am hoping that fellow programmers such as yourself could help enlighten me to IF this is true, and why such a problem would happen.
The Question
I am trying to find out if using $PSScriptRoot
would cause me problems in PowerShell Remoting that would make using $MyInvocation
a more viable option?
$MyInvocation.MyCommand.Path
and$PSScriptRoot
are that a) one includes the filename and the other does not, and b) one works on all PowerShell versions and the other only on PowerShell v3 and above. Period. – Griffycurrent script
is in that context? – Emmy