Powershell 重命名文件不起作用 - 没有错误

Powershell renaming files not working - no error

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

#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

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

#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 '-', ' ')

您正试图在适当的上下文之外使用 $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 正则表达式匹配的更多信息,请参阅以下来源。

来源:

-include 参数更改为 -filter

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

include 是基于 cmdlet

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

过滤器基于提供者

for more info