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

Use PowerShell to copy files from workstation to server, preserving the directory structure

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

工作站的文件夹:

\ProjectX
  DocumentA.sql
  DocumentA.ad
  \Build
    DocumentA.csv

我想将ProjectX的内容复制到\server\shared\projects\ProjectXProjectX文件夹已经创建)。

想要的结果:

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

尝试使用 -Container 开关 Copy-Item cmdlet。

$destination = '\server\shared\projects\ProjectX'

 Get-ChildItem '.\*' -Include '*.csv', '*.sql' -Recurse | Foreach { 
    Copy-Item -Path $_ -Destination $destination -Recurse -container
 }

这很痛苦,因为 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;
}

编辑:我认为当您在父目录不存在的情况下尝试创建子目录时,这会失败。我将把它留作 reader.

的练习