Home > Software engineering >  Extract the last component from a path string in PowerShell
Extract the last component from a path string in PowerShell

Time:03-23

I have a Question about shortening a string in PowerShell. So for example we have this code here: $path = "C:\Pow\temp\temp2"

Now, I wanted to shorten this String, even if I do not know it, but what I know is that it is a Path. So from this Path I want to get only the name of the last folder so from 'temp2'. Does someone know with what PowerShell Code you can do that? I would be happy for an answer, thank you.

CodePudding user response:

In PowerShell 3.0 and newer, use Split-Path:

PS ~> $path = "C:\Pow\temp\temp2"
PS ~> Split-Path $path -Leaf
temp2

In PowerShell 2.0, use Path.GetFileName():

PS ~> [System.IO.Path]::GetFileName($path.TrimEnd('\'))
temp2
  • Related