I'm trying to copy a file to a new location, maintaining directory structure.
$source = "c:\some\path\to\a\file.txt" destination = "c:\a\more\different\path\to\the\file.txt" Copy-Item $source $destination -Force -Recurse
But I get a DirectoryNotFoundException
:
Copy-Item : Could not find a part of the path 'c:\a\more\different\path\to\the\file.txt'
Copy a file to a directory that does not exist Instead, you need to create the folder before copying the file.
Type "xcopy", "source", "destination" /t /e in the Command Prompt window. Instead of “ source ,” type the path of the folder hierarchy you want to copy. Instead of “ destination ,” enter the path where you want to store the copied folder structure. Press “Enter” on your keyboard.
In order to copy the content of a directory recursively, you have to use the “cp” command with the “-R” option and specify the source directory followed by a wildcard character. Given our previous example, let's say that we want to copy the content of the “/etc” directory in the “/etc_backup” folder.
The -recurse
option only creates a destination folder structure if the source is a directory. When the source is a file, Copy-Item expects the destination to be a file or directory that already exists. Here are a couple ways you can work around that.
Option 1: Copy directories instead of files
$source = "c:\some\path\to\a\dir"; $destination = "c:\a\different\dir" # No -force is required here, -recurse alone will do Copy-Item $source $destination -Recurse
Option 2: 'Touch' the file first and then overwrite it
$source = "c:\some\path\to\a\file.txt"; $destination = "c:\a\different\file.txt" # Create the folder structure and empty destination file, similar to # the Unix 'touch' command New-Item -ItemType File -Path $destination -Force Copy-Item $source $destination -Force
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With