47

My PowerShell script file is located in C:/this-folder/that-folder/another-folder/powershell-file.ps1.

How do I get a variable that returns C:/this-folder/that-folder/another-folder/?

1
  • This seems to be asking how powershell-file.ps1 can get the parent directory path of itself, but it would be good to make that explicit. Commented Aug 6, 2022 at 0:17

4 Answers 4

59

Try this command in your script:

Split-Path -parent $MyInvocation.MyCommand.Definition
Sign up to request clarification or add additional context in comments.

Comments

18

In PowerShell 3.0 you can get it with the new $PSScriptRoot variable, and with $PSCommandPath you can get the full script path.

There's also a great post by MVP Keith hill you may want to check: Determining $ScriptDir Safely

Comments

14

You can use a standard .NET method:

$dirName = [System.IO.Path]::GetDirectoryName("c:\temp\abc\myproj1\newdata.txt")

From PowerShell: Get parent directory name from file or directory path.

1 Comment

The question isn't explicit but seems to be asking how to get the directory path of the executing script. If you're going to hard-code paths you might as well just do $dirName = "c:\temp\abc\myproj1".
2

I'm assuming you want to know what folder your script is running in when it's being run.

This should do it:

Split-Path $MyInvocation.MyCommand.Path

1 Comment

This includes the script name, which is what he already knows, so the other answers are more correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.