Home > front end >  Output list of files to CSV and change file names
Output list of files to CSV and change file names

Time:08-09

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

  • ... ontainer} | select-object BaseName.Replace("_",""), Extension | expor ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidArgument: (:) [Select-Object], ParameterBindingException
    • FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand

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

CodePudding user response:

  • 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
  • Related