16

I'm trying to store the current folder name into a variable (just the folder name, not the full path).

Everything that I could find on the internet is somehting like this:

PS C:\temp> get-location

Path
----
C:\temp

But what I want is just "temp" stored in a variable. How could I do this?

1 Answer 1

35

You can use Split-Path to get the folder name from Get-Locationwith -Leaf:

PS C:\temp> Get-Location

Path
----
C:\temp

PS C:\temp> Split-Path -Path (Get-Location) -Leaf
temp

We can also use the automatic variable $PWD to get the current directory:

PS C:\temp> Split-Path -Path $pwd -Leaf
temp

Or using the automatic variable $PSScriptRoot, which uses the current directory the script is being run in:

Split-Path -Path $PSScriptRoot -Leaf

From the documentation for -Leaf:

Indicates that this cmdlet returns only the last item or container in the path. For example, in the path C:\Test\Logs\Pass1.log, it returns only Pass1.log.

Additionally, as @Scepticalist mentioned in the comments, we can use Get-Item and select the BaseName with Select-Object from a specific folder(instead of just the current working directory):

PS C:\> Get-Item -Path c:\temp | Select-Object -Property BaseName

BaseName
--------
temp

Or just select the BaseName property directly with Member Enumeration(PowerShell v3+):

PS C:\> (Get-Item -Path C:\temp).BaseName
temp
Sign up to request clarification or add additional context in comments.

5 Comments

Also be sure you need Get-Location. You can also use Get-Item -Path c:\temp | Select BaseName if you need the specific folder name instead of the current working directory name
@Scepticalist Good point. To just get the basename we can use (Get-Item -Path C:\temp).BaseName
And to get the folder name of the current script directory as the title asks for, you can use Split-Path $PSScriptRoot -Leaf
(pwd).Path also works.
fyi: $PSScriptRoot does not change when you change the directory. So when using the $PSScriptRoot in the customizable prompt, it does not get updated when changing the directory

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.