Brian R
Brian R

Reputation: 785

Is there a difference between using a period to indicate relative path vs $PSScriptRoot?

I've been referencing files in my scripts with a period to indicate the current execution directory of the script, such as ".\images\test.png" but I've discovered that I could also point to the same file with $PSScriptRoot\images\test.png.

Is there an argument to be made for one over the other? When using the PS ISE, the former requires that I CD into my script directory before running code, but the scripts will normally be run automatically so the PWD should always be localized in scope. Is there another case I'm not considering?

ED: I suppose I should have specified that I am asking in the case of an independent script that is executed in isolation (it's invoked directly and does not invoke other scripts), which probably leads to the edge case of the current location and location of the current script are one in the same. In less specific conditions that I failed to consider, I can see more divergence.

Upvotes: 0

Views: 101

Answers (1)

Bill_Stewart
Bill_Stewart

Reputation: 24585

The direct answer to your question as to "is there a difference" is yes, there is a substantial difference.

The difference is that . is a reference to the current location. If the current location is a different location than where the script is, then it will not be the same as $PSScriptRoot. For example:

PS C:\> C:\Scripts\Test-Script.ps1

Inside Test-Script.ps1, . will refer to C:\ but $PSScriptRoot will refer to C:\Scripts.

Upvotes: 1

Related Questions