2

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

4

2 回答 2

4

Name 属性只为您提供不带路径的文件名。您可能想改用 FullName 属性。您还可以简化此操作,因为 Rename-Item 接受源文件名的管道输入:

gci E:\logs *.log | rename-item -newname {$_.FullName + ".old"}

另请注意,gci (get-childitem) 允许您使用参数过滤它输出的项目-Filter。此参数是位置参数 (2),因此您甚至不必指定参数名称。

于 2010-06-18T19:51:03.910 回答
0

听起来它没有找到它,因为它不在dos路径中。

毒蛇

于 2010-06-18T19:37:29.080 回答