Table of Contents
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>

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
- How to browse UNC paths in Powershell using PSDrives
- How to check if Powershell is running as an administrator
There is a missing quote after the “file.txt, but it works perfectly otherwise, so thank you.
Nice! Even works when the destination is buried deep within several levels of subfolders and none of those subfolders exists. It will create all of them. Thank you!
Long path tools help yo copy files and folder, try using it.
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.