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.
Note: The
-WhatIfcommon parameter in the command above previews the operation. Remove-WhatIfand re-execute once you're sure the operation will do what you want.Use
-CaseSensitiveto ensure case-sensitive matching.Use
-Listto stop searching after the first match in a given file has been found, as an optimization.Take advantage of
Select-String's-Pathparameter that directly accepts a wildcard pattern of files to look for - no need for a separateGet-ChildItemcall in this case.Since it is the
Microsoft.PowerShell.Commands.MatchInfoinstances emitted bySelect-Stringthat provide the input toRename-Item- via their.Pathproperty - you must use their.FileNameproperty to refer to the file name in the calculated property passed to-NewName.