Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Copy-Item create the destination directory structure?

Tags:

powershell

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' 
like image 495
Ev. Avatar asked Sep 23 '11 01:09

Ev.


People also ask

Can copy item Create folder if not exist?

Copy a file to a directory that does not exist Instead, you need to create the folder before copying the file.

How do you copy and entire directory structure?

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.

What is the command to copy directory structure?

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.


1 Answers

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 
like image 75
ajk Avatar answered Sep 22 '22 12:09

ajk