March 23, 2015 at 10:31 am #23604
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.
March 23, 2015 at 10:33 am #23605
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
March 23, 2015 at 10:41 am #23607
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....
March 23, 2015 at 10:42 am #23608
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?
March 23, 2015 at 10:47 am #23610
PS D:\scripts> write-host -ForegroundColor Cyan "This is script path: $PSScriptRoot"
This is script path:
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.
March 23, 2015 at 10:50 am #23612
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
March 23, 2015 at 10:57 am #23613
Ahhhhh....got it. That worked!
You must be logged in to reply to this topic.