Powershell 1.0 - Renaming files fails when script is in a different directory
-
28-09-2019 - |
Question
I am trying to batch rename old log files, but the script only works for me when the script is stored in the same folder as the log files. Here is the code:
cls
$file = gci E:\logs |? {$_.extension -eq ".log" |% {rename-item $_ ($_.Name + ".old")}
When I run this script from E:\logs
, it works just fine. However, when I run this script from C:\Scripts, it gives me this error:
Rename-Item: Cannot rename because item at 'my.log.file.log' does not exist.
At C:\Scripts\rename-script.ps1:2 char:92
+ $file = gci E:\logs |? {$_.extension -eq ".log" |% {rename-item $_ ($_.Name + ".old")}
+ CategoryInfo : InvalidOperation (:) [Rename-Item], FSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
I also tried using the Move-Item
command with the -literalpath
switch but had the same result
Solution
The Name property gives you just the filename without the path. You probably want to use the FullName property instead. You can also simplify this since Rename-Item accepts pipeline input for the source filename:
gci E:\logs *.log | rename-item -newname {$_.FullName + ".old"}
Also note that gci (get-childitem) allows you to filter the items it outputs using the -Filter
parmater. This parameter is a positional parameter (2) so you don't even have to specify the parameter name.
OTHER TIPS
It sounds like that it's not finding it because it is not in the dos path.
viperjay