views:

36

answers:

3

I have a powershell script located at d:\temp

When I run this script, I want the current location of the file to be listed. How do I do this ?

For example this code would accomplish it in a dos batch file; I am trying to convert this to a powershell script..

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"
A: 

Get-Location?

Jay
+3  A: 

The path of a running scripts is:

$MyInvocation.MyCommand.Path

Its directory is:

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
Roman Kuzmin
perfect. thanks!
Santhosh
Be careful using `$PSSriptRoot`. It that is a predefined variable within a module.
Keith Hill
@Keith, basically I agree that it’s not a good idea to recommend $PSScriptRoot for everyone. At least it should not be used in production scripts. I have just copy/pasted this from my “personal” script. I use exactly this name because it is convenient: my code uses $PSScriptRoot everywhere: in modules (built-in) and in scripts (fake).
Roman Kuzmin
What is a potential danger of using this name in scripts? Perhaps the PowerShell team will finally introduce $PSScriptRoot in ordinary scripts, too, and the variable will be, say, read only. Then yes, there will be a problem in my scripts. I will have to remove my assignment of $PSScriptRoot from my code (disadvantage). But the rest of the code should not be updated and it will use this new feature automatically (advantage).
Roman Kuzmin
`PowerShell team will finally introduce $PSScriptRoot in ordinary scripts` - that is what I'm hoping for. When I discovered this variable I was really excited - thinking I could replace the $MyInvocation / Split-Path dance but nooo. :-) Folks who would also like to see this should vote: https://connect.microsoft.com/PowerShell/feedback/details/522951/psscriptroot-only-works-with-modules
Keith Hill
+1  A: 

Roman Kuzmin answered the question imho. I'll just add that if you import a module (via Import-Module), you can access $PsScriptRoot automatic variable inside the module -- that will tell you where the module is located.

stej