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 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>
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 recursively copy the contents of a folder to another location using the following command:
Copy-Item -Path "C:\temp\ccmsetup.log" -Destination (New-item -Name "ccmsetup" -Type Folder -Path "c:\temp") -Force -Verbose
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.