ScriptMonkey
ScriptMonkey

Reputation: 311

Remove the root of a file path

I'm attempting to 'trim' the first part of a file path, so I'm left with only some of the trailing parts, after a wildcard character. I can do the following, which I know is not ideal, and due to the nature of the paths, could return the wrong part of the path. Where you see the '9' it can be any number:

$Path = Get-Item '\\servername\share1\share2\share3\idontwantthis9\whatiwant\alsowhatiwant'

$PathRoot = ($Path.FullName).Replace($Path.Root.FullName,'') #Not neccessary, but gets me closer.
$PathRoot.Split("\")[1..100] -join('\') #Any better way of saying 1..<everything after> suggestions?

This returns:

idontwantthis9\whatiwant\alsowhatiwant

Which is great, but I'm expecting a command similar to 'split-path' to get rid of the 'idontwantthisX' part with a wildcard for the number.

I realise I could just use:

$Path.Split('\')[7..8] -join('\')

However, the path can be of a variable length, the only constant is that somewhere in the path, it will read 'idontwantthisX' with a random traling number.

Upvotes: 1

Views: 1272

Answers (2)

Lee_Dailey
Lee_Dailey

Reputation: 7489

here's a slight variant on the one by mklement0. i didn't notice his until mine was done. [blush] i went with a regex based -split instead of -replace.

$Path = '\\servername\share1\share2\share3\idontwantthis9\whatiwant\alsowhatiwant'
$RemoveUpToThisRegex = 'idontwantthis\d{1,}\\'

$KeepThisPathPart = ($Path -split $RemoveUpToThisRegex)[1]

$KeepThisPathPart

output ...

whatiwant\alsowhatiwant

Upvotes: 1

mklement0
mklement0

Reputation: 439417

Use the -replace operator with a regex (regular expression) that strips the prefix:

$path = '\\servername\share1\share2\share3\idontwantthis9\whatiwant\alsowhatiwant'

$path -replace '^.+\\idontwantthis\d+\\'

The above yields whatiwant\alsowhatiwant.

Upvotes: 1

Related Questions