Powershell 1.0 - 当脚本位于不同目录中时重命名文件失败
我正在尝试批量重命名旧日志文件,但该脚本仅在脚本存储在与日志文件相同的文件夹中时才适用于我。这是代码:
cls
$file = gci E:\logs |? {$_.extension -eq ".log" |% {rename-item $_ ($_.Name + ".old")}
当我从 E:\logs
运行此脚本时,它工作得很好。但是,当我从 C:\Scripts 运行此脚本时,它给了我这个错误:
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
我还尝试使用带有 -literalpath
开关的 Move-Item
命令,但有相同的结果
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Name 属性只提供文件名,不提供路径。您可能想改用 FullName 属性。您还可以简化此操作,因为 Rename-Item 接受源文件名的管道输入:
另请注意,gci (get-childitem) 允许您使用
-Filter
参数过滤其输出的项目。此参数是位置参数 (2),因此您甚至不必指定参数名称。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:
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.听起来好像没有找到它,因为它不在 dos 路径中。
毒蛇
It sounds like that it's not finding it because it is not in the dos path.
viperjay