Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell get current script directory name only

Tags:

powershell

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?

like image 509
steve15 Avatar asked Dec 28 '25 16:12

steve15


1 Answers

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
like image 144
RoadRunner Avatar answered Dec 30 '25 17:12

RoadRunner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!