Copy-Item 应该创建目标目录结构吗? [英] Should Copy-Item create the destination directory structure?
本文介绍了Copy-Item 应该创建目标目录结构吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将文件复制到新位置,以保持目录结构.
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
但是我得到一个DirectoryNotFoundException
:
Copy-Item : Could not find a part of the path 'c:\a\more\different\path\to\the\file.txt'
推荐答案
-recurse
选项仅在源是目录时创建目标文件夹结构.当源是一个文件时,Copy-Item 期望目标是一个已经存在的文件或目录.您可以通过以下几种方法解决此问题.
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.
选项 1:复制目录而不是文件
$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
选项 2:先触摸"文件然后覆盖它
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
这篇关于Copy-Item 应该创建目标目录结构吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文