Copy-Item

If you are copying a folder, the Copy-Item cmdlet always assumes you want to create the folder in the destination.  Let’s say you wanted to copy the “trek” folder from a server, to your local device.  You might run a command like this:

				
					copy-item -Path \\myserver\star\trek -Destination C:\temp\star\trek -force -recurse
				
			

If there is no folder C:\temp\star\trek, it will create the folder for you, and the directory structure will be fine.  However, if there is already a folder C:\temp\star\trek, you will end up with a folder c:\temp\star\trek\trek.  This is the script I use to make sure I get consistent results.

				
					$Dest = "C:\temp\star\trek"
$Parent = "C:\temp\star"
$Source = "\\myserver\star\trek"

IF (!(Test-Path $Dest)) {
   New-Item -Path $Dest -ItemType Directory
   Copy-Item -Recurse -Force -Path $Source -Destination $Parent
   } Else {
   Copy-Item -Recurse -Force -Path $Source -Destination $Parent
   }
				
			

Perhaps you have something better?  Let me know below!

Leave a Reply

Your email address will not be published. Required fields are marked *