powershell获取项目|复制项目不只保留一个文件夹的文件夹结构

时间:2018-11-30 17:08:40

标签: powershell

我正在尝试使用Powershell脚本将所有文件夹/子文件夹/子文件从服务器上的一个文件夹移动到另一个文件夹,同时始终保持相同的文件结构。为此,我正在使用Get-childItem |复制项目。除目录中的第一个文件夹外,所有文件夹,子文件夹和子文件都可以正常移动。而是将所有这些子文件/子文件夹从此文件夹输出到目标位置。但是,它不会保留其结构,只是不包括其父目录。我的代码如下:

Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*file path*" -f $destinationServer, $destinationClient) -Recurse -Force 
  • filepath 的措辞旨在提高可读性
  • $ sourceFilePath是我要复制的源文件夹
  • $ destination服务器/ $ destinationClient是在释义的“文件路径”中使用的变量

我无法弄清楚为什么此代码除了适用于该单个文件夹及其项目以外,还适用于所有其他文件夹,子文件夹和文件。任何帮助将不胜感激,如果还有其他信息可以帮助您,请告诉我。


感谢@ChristianMüller:

New-Item $destinationFilePath -name "MissingFolder" -type directory -Force | Out-Null

Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*filepath*" -f $destinationServer, $destinationClient) -Recurse -Force

1 个答案:

答案 0 :(得分:0)

这是一个非常奇怪的错误,也令我惊讶! :)

似乎目标基本目录不存在,而是仅创建目录而不包含内容。

因此,通过这种构造,您甚至可以在ISE中调试此行为:

$sourceFilePath = "c:\temp\Test1"
$destPath = "c:\temp\Test2"
$a=Get-ChildItem $sourceFilePath -Force

rm -Force $destPath
foreach($x in $a) {
    $x | Copy-Item -Destination "$destPath" -Recurse -Force 
}

dir $destPath

首先使用新项目创建目标目录,以解决问题:

$sourceFilePath = "c:\temp\Test1"
$destPath = "c:\temp\Test2"
$a=Get-ChildItem $sourceFilePath -Force

rm -Force $destPath

New-Item -ItemType Directory -Force -Path $destPath
foreach($x in $a) {
    $x | Copy-Item -Destination "$destPath" -Recurse -Force 
}

dir $destPath

但在我的示例中,除了

外,完全不使用“ Get-ChildItem”是可行的
Copy-Item c:\temp\test1 -Destination c:\temp\test2 -Recurse -Force

这对您也有用吗?

Copy-Item $sourceFilePath -Destination ("*file path*" -f $destinationServer, $destinationClient) -Recurse -Force 
相关问题