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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - Should Copy-Item create the destination directory structure?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...