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

时间:2018-07-09 16:46:53

标签: regex powershell powershell-v4.0

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

#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

3 个答案:

答案 0 :(得分:2)

使用-include更改-filter参数

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

包括基于cmdlet

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

过滤器是基于提供程序的

for more info

答案 1 :(得分:1)

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

来源:

答案 2 :(得分:0)

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

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