Reputation: 1640
I am trying to copy files from one directory to another and rename them. The destination folder's files are deleted and the files copy but unfortunately the rename part of my script isn't doing anything. There are no errors being displayed.
#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 '-', ' ' }
At the moment I am simply trying to replace hyphens with spaces but I will also need to remove a W
from the end of the filename, when I can get it to work.
Example original filename: First-Last-W.jpg
Example desired filename: First Last.jpg
Upvotes: 1
Views: 1645
Reputation: 21408
You are trying to use a $PSItem
(also referenced as $_
) outside of the proper context. You should add a Foreach-Object
to your pipeline:
# 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 '-', ' ' )
}
Two additional things I added to your code block above:
You used curly-braces where you should have used parentheses as evidenced in @Jacob's answer. I fixed this here as well.
I added a second -Replace
that will remove a -W
from the end of the new name (while keeping the .jpg
extension). For more information about Powershell regular expression matching, see the sources below.
Sources:
Upvotes: 1
Reputation: 31
change -include
param with -filter
Get-ChildItem -Path $destination -Include *.jpg
include is based cmdlet
Get-ChildItem -Path $destination -filter *.jpg
filter is based-provider
Upvotes: 3
Reputation: 1192
I've not tested this, but it looks those curly braces look wrong, what happens if you try the following:
#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 '-', ' ')
Upvotes: 0