powershellfilerename-item-cmdlet

How to change the file extension of files that contain a certain string with PowerShell


I'm trying to automatically rename all *.txt files to *.log files, but only if they contain the upper case string ERROR.

However, the following code doesn't work:

Get-ChildItem *.txt -file | Select-String "ERROR" | Rename-Item -NewName { $_.Name -replace '.txt','.log' }

I'm getting the following error message:

Rename-Item : Cannot bind argument to parameter 'NewName' because it is an empty string.

I found out that I can get the actual path with:

Get-ChildItem *.txt -file | Select-String "ERROR" | ForEach-Object { Write-Host $_.Path }

but I can't figure out how to use it with Rename-Item.

I also tried:

Get-ChildItem *.txt -file | Select-String "ERROR" | [io.path]::ChangeExtension($_.name, "log")

but I got the following error message:

Expressions are only allowed as the first element of a pipeline.

Solution

  • Select-String -Path *.txt -List -CaseSensitive 'ERROR' |
      Rename-Item -NewName { $_.FileName -replace '\.txt$', '.log' } -WhatIf
    

    Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want.