user2457075
user2457075

Reputation: 159

How can I substring a path in powershell

I have a path that I want to clip off a leading section and use the remaining portion. Example path:

C:\temp\rootfolder\subfolder1\subfolder2

I want to be able to get just the subfolder1\subfolder2 portion and I have the root folder as a variable. Is there a command that I can take a path and apply a root path and get the remaining portion?

Actual Path: C:\temp\rootfolder\subfolder1\subfolder2

Root Path: C:\temp\rootfolder

Desired Path: subfolder1\subfolder2

Upvotes: 2

Views: 2512

Answers (3)

ATP
ATP

Reputation: 561

You can try

Set-Location $rootPath
$remainingPath = Get-Item $GivenFullPath | Resolve-Path -Relative

Upvotes: -1

Gordon
Gordon

Reputation: 6863

Does this get you close?

"C:\temp\rootfolder\subfolder1\subfolder2" -replace [regex]::escape("C:\temp\rootfolder\"), ""

Upvotes: 0

Tony Hinkle
Tony Hinkle

Reputation: 4742

Use the Replace method on the string that contains the full path, passing in the variable that contains the root path ($root in my example), and empty quotes to replace it with nothing:

$root = "C:\temp\rootfolder\"
$path = "C:\temp\rootfolder\subfolder1\subfolder2"
$path = $path.Replace($root, "")

In this example $path will contain "subfolder1\subfolder2" at the end.

Upvotes: 3

Related Questions