SQL_Guy
SQL_Guy

Reputation: 353

Output list of files to CSV and change file names

I know how to generate a list of files in a directory, for example:

get-childitem -path "c:\temp" -Recurse | select-object BaseName, Extension | export-csv -notypeinformation -path "c:\temp\filelist.csv"

Now I would like to also manipulate some filenames to clean them up, for example I am trying to do this, but it fails

get-childitem -path "c:\temp" -Recurse | select-object BaseName.Replace("_Error_",""), Extension | export-csv -notypeinformation -path "c:\temp\filelist.csv"

I get the error similar to this: Select-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'. At line:1 char:207

Can you tell me what I am doing wrong? Isn't "BaseName" a string?

Upvotes: 1

Views: 5346

Answers (1)

mklement0
mklement0

Reputation: 437177

  • As a direct argument, BaseName.Replace("_Error_","") cannot work if you want to provide an expression that operates on each input object.

    • Loosely speaking, such an argument is interpreted as an expandable string literal, with ( starting a new argument; see this answer for how unquoted tokens are parsed as command arguments.
  • Instead, you need a calculated property.

Get-ChildItem -path "c:\temp" -Recurse | 
  Select-Object @{ n='BaseName'; e={ $_.BaseName.Replace("_Error_","") } }, 
                Extension |
  Export-csv -NoTypeInformation -Path c:\temp\filelist.csv

Upvotes: 1

Related Questions