Powershell Cannot create a file when that file already exists when using Move-Item

Viewed 1156

I'm trying to move png images in subfolders to a subfolder in the folder they are in.

Main folder is called "stuff", images are in variously named subfolders in the "stuff" main folder, and each of these subfolders have a folder name "Oneshot" in them, I'm trying to move these images that are in M:/Stuff/FolderExample/ to M:/Stuff/FolderExample/Oneshot/. Current code I am using

Get-ChildItem -Path C:\Users\a\Desktop\stuff\*.png -Recurse | Move-Item -Destination "$($_.FullName)\Oneshot\"

How can I make this work? I'm just trying to learn powershell so I can automate this process as I otherwise would need to repeat the process manually for thousands of times

2 Answers

Use a scriptblock ({...}) as the argument to -Destination - this will allow you to access the current pipeline item as $_ during parameter binding:

Get-ChildItem -Path C:\Users\a\Desktop\stuff\*.png -Recurse |Where-Object Directory -notlike *\OneShot | Move-Item -Destination {"$($_.Directory.FullName)\Oneshot\"}

The Where-Object command in the middle of the pipeline will ensure we don't attempt to move pictures already in one of the OneShot folders.

Powershell is not the best idea to move files. The main reason is that you run into problems in case the path becomes too long >256 characters. I would use robocopy for such tasks. It is part of every current windows version.

robocopy  M:/Stuff/FolderExample/  M:/Stuff/FolderExample/Oneshot/ /MIR

Please keep in mind that this code will also delete everything that is in M:/Stuff/FolderExample/Oneshot/ and not in M:/Stuff/FolderExample/. So use /MIR with caution.

You could still invoke robocopy in an ps1 file and wrap other powershell code around it e.g. for variables.

Related