Introduction

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

How do I copy a file or folder to a new destination if the folder does not exist?

If you want to use Powershell to copy a file or folder to a directory that does not exist, you are required to create the destination directory before executing the copy.

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

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 file to a new directory 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 file or folder to a non-existing location

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

You can accomplish this using the below one-liner.

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.

Related posts

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here