【问题标题】:Powershell renaming files not working - no errorPowershell重命名文件不起作用 - 没有错误
【发布时间】:2018-12-17 10:11:29
【问题描述】:

我正在尝试将文件从一个目录复制到另一个目录并重命名它们。目标文件夹的文件被删除并且文件被复制,但不幸的是我的脚本的重命名部分没有做任何事情。没有显示错误。

#Set variables
[string]$source = "C:\temp\Photos\Original\*"
[string]$destination = "C:\temp\Photos\Moved\"
#Delete original files to avoid conflicts
Get-ChildItem -Path $destination -Include *.* -Recurse | foreach { $_.Delete()}
#Copy from source to destination
Copy-item -Force -Recurse -Verbose $source -Destination $destination

Get-ChildItem -Path $destination -Include *.jpg | rename-item -NewName { $_.Name -replace '-', ' ' }

目前我只是想用空格替换连字符,但我还需要从文件名的末尾删除W,当我可以让它工作时。

示例原始文件名:First-Last-W.jpg

所需文件名示例:First Last.jpg

【问题讨论】:

    标签: regex powershell powershell-4.0


    【解决方案1】:

    -include 参数更改为-filter

    Get-ChildItem -Path $destination -Include *.jpg
    

    include 是基于 cmdlet 的

    Get-ChildItem -Path $destination -filter *.jpg
    

    过滤器是基于提供者的

    for more info

    【讨论】:

      【解决方案2】:

      您正在尝试在正确的上下文之外使用$PSItem(也称为$_)。您应该在管道中添加Foreach-Object

      # This can be a one-liner, but made it multiline for clarity
      Get-ChildItem -Path $destination -Filter *.jpg | Foreach-Object {
        $_ | Rename-Item -NewName ( ( $_.Name -Replace '-w\.jpg$', '.jpg' ) -Replace '-', ' ' )
      }
      

      我在上面的代码块中添加了两件事:

      1. 您在应该使用括号的地方使用了大括号,正如@Jacob 的回答所证明的那样。我也在这里解决了这个问题。

      2. 我添加了第二个-Replace,它将从新名称的末尾删除-W(同时保留.jpg 扩展名)。有关 Powershell 正则表达式匹配的更多信息,请参阅以下来源。

      来源:

      【讨论】:

      • 那不行,在将- 替换为与替换顺序相反的空格后,将没有-WRename-Item 确实接受管道输入并使用脚本块是正确的方法。在脚本块中,您必须使用$_.Property 来引用当前处理的管道对象属性。您的脚本将失败,因为您既没有通过管道将 $_ 传递给 Rename-Item,也没有指定 -Path。如果不能 100% 确定它们是否符合您的预期,您应该测试您的脚本。
      • 我确实测试了它,但不小心颠倒了上面的正则表达式。感谢您发现
      • Rename-Item 仍然没有要重命名的对象。 $_ | Rename-Item ...Rename-Item -Path $_ ...
      • 我发誓我有$PSItem,一定是误删了。再次感谢
      • 谢谢 - 这行得通,但我不得不使用 -filter 而不是 -include 作为其他答案之一
      【解决方案3】:

      我没有对此进行测试,但看起来那些花括号看起来不对,如果您尝试以下操作会发生什么:

      #Set variables
      [string]$source = "C:\temp\Photos\Original\*"
      [string]$destination = "C:\temp\Photos\Moved\"
      #Delete original files to avoid conflicts
      Get-ChildItem -Path $destination -Include *.* -Recurse | foreach { $_.Delete()}
      #Copy from source to destination
      Copy-item -Force -Recurse -Verbose $source -Destination $destination
      
      Get-ChildItem -Path $destination -Include *.jpg | rename-item -NewName ($_.Name -replace '-', ' ')
      

      【讨论】:

      • 错误:Rename-Item : Cannot bind argument to parameter 'NewName' because it is an empty string. At line:9 char:72
      猜你喜欢
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 2022-01-24
      • 1970-01-01
      • 2021-04-10
      • 2015-11-26
      • 1970-01-01
      相关资源
      最近更新 更多