简体   繁体   中英

Powershell get current script directory name only

I'm trying to get in a variable in my script the current folder name, ONLY the folder name.

Everything that i can find on internet is like this:

PS C:\temp> get-location

Path
----
C:\temp

i get the C:\Temp location. I want only the Temp name in my variable.

How is it possible?

Thanks.

You can use Split-Path to get the folder name from Get-Location with -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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM