Skip to main content Link Menu Expand (external link) Document Search Copy Copied

I was working with Powershell recently, writing a script to deploy some files, when I found myself fixing the same bit of code over and over. The first time I ran the script it seemed to work. Then I ran it again with a few tweaks and it failed. I fixed it so that it was working, deleted the outputs for a fresh test, tried again and it failed again. A couple of times round the loop I had to stop to try and figure out what was going on.

I narrowed it down to an inconsistency in the way that the Copy-Item Cmdlet works. The following snippet will result in different behaviour depending upon whether the destination folder exists or not.

Note that I’ve had to use forward slashes in the below examples because WordPress seems to be eating my back slashes (I’ve tried single, double and triple slashes and even the ASCII code).

[code lang=”text”] $d = 'D:/Temp/CopyItemTest/Destination' Copy-Item -Path:D:/Temp/CopyItemTest/Source -Destination:$d -Force –Recurse [/code]

If the destination folder does not exist then it is created and the contents of the source folder are copied into it.

E.g. result is

[code lang=”text”] D:/Temp/CopyItemTest/Destination/File1.txt [/code]

If the destination folder does exist (i.e. if you run the code above a second time without altering the copied files) then a source sub-folder is created in the destination folder and then the contents of the source folder are copied into it.

E.g.

[code lang=”text”] D:/Temp/CopyItemTest/Destination/Source/File1.txt [/code]

Using the following instead results in a consistent behaviour:

[code lang=”text”] $d = 'D:/Temp/CopyItemTest/Destination' if (!(Test-Path $d)) { New-Item -Path:$d -Type:Directory } Copy-Item -Path:D:/Temp/CopyItemTest/Source -Destination:$d -Force -Recurse [/code]

The result of this will always be:

[code lang=”text”] D:/Temp/CopyItemTest/Destination/Source/File1.txt [/code]