Show directory path of script?

Welcome Forums General PowerShell Q&A Show directory path of script?

This topic contains 6 replies, has 2 voices, and was last updated by

 
Participant
3 years, 9 months ago.

  • Author
    Posts
  • #23604

    Participant
    Points: 0
    Rank: Member

    I'm converting a dos batch script for a critical process that runs periodically. There's a "source path" variable with "%~dp0" which I understand means the root of script directory. Powershell has an equivalent variable – $PSScriptRoot.
    So, how do you "echo" what the $PSScriptRoot path is? In the dos batch script, there are pauses to validate the path before proceeding to the next set of commands.

    Doing a write-host "This is the current script path: $PSScriptRoot" does not work.

  • #23605

    Member
    Points: 0
    Rank: Member

    That should work (though it wouldn't pause the script; it would just output the path to the screen.)

    If that's not working, then you're either not running a saved script file, or you're running PowerShell 2.0. ($PSScriptRoot was added in PowerShell 3.0). If you need a PowerShell 2.0 compatible version, do this: $scriptRoot = Split-Path $MyInvocation.MyCommand.Path

  • #23607

    Participant
    Points: 0
    Rank: Member

    I'm testing this on my Windows 8.1 box. I'm running PS version 5.0. The boxes I'll be executing this script will be on Windows 2012 R2 boxes – innate PS version 4.
    I'm not wanting to pause anything. Just display script path followed by a "pause" or "start-sleep". Whoever is running the script needs to see the script path before continuing the script.

    Still not working....

  • #23608

    Member
    Points: 0
    Rank: Member

    Dunno what to tell you. "Not working" doesn't tell me much. What do you see on the screen when that Write-Host command executes?

  • #23610

    Participant
    Points: 0
    Rank: Member

    PS D:\scripts> write-host -ForegroundColor Cyan "This is script path: $PSScriptRoot"
    This is script path:

    PS D:\scripts>

    That's it. That's all I get. I also tried pasting this in PS script and same thing. It doesn't return script path.

  • #23612

    Member
    Points: 0
    Rank: Member

    You typed that command at the console? Or did you put it into a script? $PSScriptRoot doesn't have a value when you're at the console, or when you're running a script in the ISE that you haven't saved yet. This, on the other hand, should work fine:

    Set-Content $env:temp\demo.ps1 'Write-Host -ForegroundColor Cyan "This is script path: $PSScriptRoot"'
    & $env:temp\demo.ps1
    
  • #23613

    Participant
    Points: 0
    Rank: Member

    Ahhhhh....got it. That worked!

The topic ‘Show directory path of script?’ is closed to new replies.