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.
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>
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
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.
- Powershell script to copy files to current user profile
- Powershell script to add users from a text file to an Active Directory group using alternate credentials
- Powershell command to open the current directory in Windows Explorer when in Powershell
- How to run Powershell as an administrator
- How to browse UNC paths in Powershell using PSDrives
- How to check if Powershell is running as an administrator