3

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 + "',"
  }
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • What is `nnn + long file path` meant to be? The `FullName` will contain the full path, which looks like the thing you're trying to remove. Can you update the question with a real example of what you see and what you want to see? – arco444 Jun 25 '15 at 12:51
  • I made an edit with my real world example. Thanks for your time. – GibboK Jun 25 '15 at 13:09
  • possible duplicate of [How to convert absolute path to relative path in powershell?](http://stackoverflow.com/questions/12396025/how-to-convert-absolute-path-to-relative-path-in-powershell) – n0rd Jun 25 '15 at 19:23

2 Answers2

6

$_ 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 }
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 1
    I think `$pattern = "^"+[regex]::escape("$basedir\")` is necessary. Otherwise you escape the `^` character, which will not work as intended. – Christopher K. Apr 15 '20 at 09:07
0

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

Stephen Dunne
  • 419
  • 1
  • 5
  • 13
  • 1
    Not true. Since `Get-ChildItem -Recurse` recurses into subfolders, just echoing `$_.Name` would not output the path relative to the base directory `C:\ppp\nnn\trunk\www\client` for grandchildren and below. – Ansgar Wiechers Jun 25 '15 at 19:08
  • Yes, apologies, you are correct! I thought only the file name was required. – Stephen Dunne Jun 26 '15 at 09:22