使用PowerShell将文件从工作站复制到服务器,保留目录结构

时间:2016-05-06 13:54:02

标签: powershell powershell-v5.0

我正在尝试将工作站上文件夹的选定内容复制到网络共享。

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的答案不感兴趣。

2 个答案:

答案 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
 }