9

I have a script (script1.ps1) that lies in C:\FolderA

What powershell code can I insert in the script, that it will print what ever current location/path of the script. (The goal is to make this script portable)

ie:

-When in folderA, the code will print C:\FolderA (full-path)

-When Script1.ps1 is moved to C:\FolderB\FolderC and run, it prints the full path of C:\FolderB\FolderC

Any help would be much appreciated.

Thanks


Thanks to @Nkosi and @Kori Gill

The answer I was looking for was $PSScriptRoot

One thing to note, is that I noticed I had to define a variable first inside the script before running the script:

$Path = $PSScriptRoot

$Path

with this it worked otherwise it didnt

AdilZ
  • 1,107
  • 6
  • 27
  • 44
  • 2
    Possible duplicate of [What's the best way to determine the location of the current PowerShell script?](http://stackoverflow.com/questions/5466329/whats-the-best-way-to-determine-the-location-of-the-current-powershell-script) – Nkosi Nov 07 '16 at 22:53

1 Answers1

11

See "get-help about_Automatic_Variables".

Read sections on:

  • $MyInvocation
  • $PSScriptRoot
  • $PSCommandPath
Kory Gill
  • 6,993
  • 1
  • 25
  • 33
  • 2
    At least for me, I had to first run `Update-Help` as admin before this command would work. Otherwise, use the [online documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-5.1). – Nathan Jan 20 '21 at 16:51
  • I had to first run also this command from Admin PS Console: `Install-Script -Name Install-AboutHelp` from [this](https://stackoverflow.com/questions/40654102/get-help-about-automatic-variables-not-working) other question. – jeanie77 Sep 16 '21 at 08:19