GibboK
GibboK

Reputation: 73988

Remove parent path

The following script lists all file in a directory and return their name and path in console.

The result is like:

C:\Projects\company\trunk\www\client\project\customer\start.js

I need instead removing the initial part and having the result like

project\customer\start.js

I am not able to set the right regular expression in Replace. Could you please point me out in the right direction?

Get-ChildItem -Path C:\Projects\company\trunk\www\client\project -Filter *.js -Recurse -File |
  Sort-Object Length -Descending |
  ForEach-Object {
    $_ = $_ -replace '\\C:\Projects\company\trunk\www\client\project', ''
    "'" + $_.FullName + "',"
  }

Upvotes: 3

Views: 2560

Answers (2)

Stephen Dunne
Stephen Dunne

Reputation: 459

Since you have a FileInfo object on the pipeline you could just use $_.Name - there is no need for the regular expression

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200473

$_ is a FileInfo object, not a string, the path doesn't start with a backslash, and backslashes in the search string must be escaped if you want to use the -replace operator.

Try this:

$basedir = 'C:\ppp\nnn\trunk\www\client'
$pattern = [regex]::Escape("^$basedir\")

Get-ChildItem -Path "$basedir\nnn" -Filter *.js -Recurse -File |
  Sort-Object Length -Descending |
  ForEach-Object { $_.FullName -replace $pattern }

Upvotes: 6

Related Questions