Introduction

One of the most basic tasks in Powershell is copying files or folders. Copying file contents of a folder and folders using Powershell works fine if both the source and destination paths are available, but not if the destination path is missing.

In this blog post, I explain how to use the Copy-Item cmdlet in Powershell to create a folder before copying a file or folder to the directory.

If you want to learn Powershell, I highly recommend the Pluralsight courses.

Copy a file to a directory that does not exist

The challenge with copying a file or folder to a non-existing folder

If you want to copy a single file from one location to another location using Powershell, you can’t just run the regular Copy-Item command:

Copy-Item -Path "C:\temp\ccmsetup.log" -Destination "C:\temp\ccmsetup\ccmsetup.log" -Force -Verbose

If you try to copy a file or folder to a directory that does not exist, you receive the following error:

Could not find a part of the path <path>

powershell copy file

How to correctly copy a folder of file to a non-existing location

Instead, you need to create the folder before copying the file.

You can copy files and directories in a folder from one location to another using the following command. Make sure that the destination parameter is configured -Force parameter is set. This preserves the directory structure.

Copy-Item -Path "C:\temp\ccmsetup.log" -Destination (New-item -Name "ccmsetup" -Type Folder -Path "c:\temp") -Force -Verbose


Conclusion

Like many other things in life, and especially with Powershell, things are not as straight-forward as they may first seem.

How long time did it take for you to work this out? Please leave a comment below.

If you want to learn Powershell, I highly recommend the Pluralsight courses.

Related posts

4 COMMENTS

  1. Thanks for sharing this.
    However, i really do not understand why there is no parameter to include to just create the folder via the copy-item cmdlet.
    It looks quite cumbersome to me to include another command to first create the folder.

LEAVE A REPLY

Please enter your comment!
Please enter your name here