Search code examples
powershellpowershell-3.0rename-item-cmdlet

One Line PowerShell Batch Rename based on File Contents


I have a list of EDI text files with specific text in them. Currently in order for our custom scripting to convert them into an SQL table, we need to be able to see the X12 file type in the filename. Because we are using SQL script to get the files into tables this solution needs to be a one line solution. We have a definition table of client files which specify which field terminator and file types to look for so we will be later substitute those values into the one line solution to be executed individually. I am currently looking at Powershell (v.3) to do this for maximum present and future compatibility. Also, I am totally new to Powershell, and have based my script generation on posts in this forum.

Files example

  • t.text.oxf.20170815123456.out
  • t.text.oxf.20170815234567.out
  • t.text.oxf.20170815345678.out
  • t.text.oxf.20170815456789.out

Search strings to find within files: (To find EDI X12 file type uniquely, which may be duplicated within the same file n times)

  • ST*867
  • ST*846
  • ST~867
  • ST~846
  • ST|867
  • ST|846

Here is what I have so far which does not show itself doing anything with the whatif parameter:

(Get-ChildItem .\ -recurse | Select-String -pattern 'ST~867' -SimpleMatch).Path | Foreach -Begin {$i=1} -Process {Rename-Item -LiteralPath $_ -NewName ($_ -replace 'out$','867.out' -f $i++) -whatif}

The fist part:

(Get-ChildItem .\ -recurse | Select-String -pattern 'ST~867' -SimpleMatch).Path

Simply gets a list of paths that we need to input to be renamed

The second part after the | pipe:

Foreach -Begin {$i=1} -Process {Rename-Item -LiteralPath $_ -NewName ($_ -replace '\.out','.867.out' -f $i++) -whatif}

will supposedly loop through that list and rename the files adding the EDI type to the end of the file. I have tried 'out$','867.out' with no change.

Current Errors:

  • The first part shows duplicated path elements probably because there are multiple Transaction Set Headers in the files, is there any way to force it to be unique?
  • The command does not show any Errors (red text) but with the whatif parameter shows that it does not rename any files (tried running it without as well).

Solution

  • 1) remove duplicates using -List switch in Select-String 2) you need to really pipe the objects into the for loop

    Try this?

    Select-String -Path .\*.out -pattern 'ST~867' -SimpleMatch -List | Select-Object Path | ForEach-Object { Rename-Item $_.path ($_.path -replace 'out$','867.out') }