Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to copy a file to a new location, maintaining directory structure.

$source = "c:somepathoafile.txt"
destination = "c:amoredifferentpathohefile.txt"

Copy-Item  $source $destination -Force -Recurse

But I get a DirectoryNotFoundException:

Copy-Item : Could not find a part of the path 'c:amoredifferentpathohefile.txt'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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:somepathoadir"; $destination = "c:adifferentdir"
# 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:somepathoafile.txt"; $destination = "c:adifferentfile.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...