1

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?

SQL_Guy
  • 333
  • 4
  • 15

1 Answers1

1
  • 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
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thank you very much! This is complex (for me). One small correction - the code above is missing a second closing curly brace, other then that, it works perfectly. It should be: Get-ChildItem -path "c:\temp" -Recurse | Select-Object @{ n='BaseName'; e={ $_.BaseName.Replace("_Error_","") }}, Extension | Export-csv -NoTypeInformation -Path c:\temp\filelist.csv – SQL_Guy Aug 09 '22 at 00:13
  • Glad to hear it helped, @SQL_Guy. Thanks for telling me about the missing `}` - answer updated. – mklement0 Aug 09 '22 at 01:28