我正在尝试将工作站上文件夹的选定内容复制到网络共享。
Workstation的文件夹:
\ProjectX
DocumentA.sql
DocumentA.ad
\Build
DocumentA.csv
我想将ProjectX
的内容复制到\\server\shared\projects\ProjectX
(已创建ProjectX
文件夹)。
期望的结果:
\ProjectX
DocumentA.sql
\Build
DocumentA.csv
我试过了:
$destination = '\\server\shared\projects\ProjectX'
Get-ChildItem '.\*' -Include '*.csv', '*.sql' -Recurse | Foreach {
Copy-Item -Path $_ -Destination $destination -Recurse
}
不幸的是,这导致:
\ProjectX
DocumentA.sql
DocumentA.csv
我错过了什么?
我对涉及robocopy
的答案不感兴趣。
答案 0 :(得分:2)
这是一种痛苦,因为Copy-Item
太愚蠢了,无法正确地完成工作。这意味着你必须自己编写逻辑。
通常我最终会得到这样的结果:
$Source = (Get-Location).Path;
$Destination = '\\server\shared\projects\ProjectX';
Get-ChildItem -Path $Source -Include '*.csv','*.sql' -Recurse | ForEach-Object {
# Get the destination file's full name
$FileDestination = $_.FullName.Replace($Source,$Destination);
# Get the destination file's parent folder
$FileDestinationFolder = Split-Path $FileDestination -Parent;
#Create the destination file's parent folder if it doesn't exist
if (!(Test-Path -Path $FileDestinationFolder)) {
New-Item -ItemType Directory -Path $FileDestinationFolder | Out-Null;
}
# Copy the file
Copy-Item -Path $_.FullName -Destination $FileDestination;
}
编辑:我认为当父直接不存在时尝试创建子目录时会失败。我将把它作为读者的练习。
答案 1 :(得分:0)
尝试使用 -Container 切换Copy-Item
cmdlet。
$destination = '\\server\shared\projects\ProjectX'
Get-ChildItem '.\*' -Include '*.csv', '*.sql' -Recurse | Foreach {
Copy-Item -Path $_ -Destination $destination -Recurse -container
}