试图编写一个函数来复制目录的子文件夹和文件,只有差异

时间:2016-11-14 18:03:56

标签: powershell

function Copy-File {
  #.Synopsis
  # copies only the difference of files existing in between source and destination 
  param([object]$source,[object]$destination)
  # create destination if it's not there ...
  mkdir $destination -Force -ErrorAction SilentlyContinue
  $source1 = Get-ChildItem -Path $source
  $destination1 = Get-ChildItem -Path $destination
  $filediff = Compare-Object -ReferenceObject $source1 -DifferenceObject $destination1
  $filediff | foreach { 
    $CopyParams = @{ 'Path' = $_.InputObject.FullName }
    if ($_.SideIndicator -eq '<=') {
      $CopyParams.Destination = $destination1
    } else {
      $CopyParams.Destination = $source1
    }
    Copy-Item @CopyParams
  }
}

我想将其复制到用户个人资料中的LocalAppData。

2 个答案:

答案 0 :(得分:1)

试试这个

$destination="c:\tempcopy"
gci "c:\temp" | %{if (!(Test-Path "$destination\$($_.Name)")) {copy-item $_.FullName -Destination "$destination\$($_.Name)" -Force}    }

答案 1 :(得分:0)

这将复制两个文件夹中对象的差异,以便不在第一个文件夹中的所有文件都复制到第二个文件夹,反之亦然。您可以将目标更改为用户的Local \ AppData文件夹。希望这能给你一个很好的起点。

Function Get-Folder($Message)
{

    Function Select-Folder($Title = $Message, $path = 0) {  
        $object = New-Object -comObject Shell.Application   

        $folder = $object.BrowseForFolder(0, $Title, 0, $path)  
        if ($folder -ne $null) {  
            $folder.self.Path  
            $Choice = $folder.Self.Path
        }  
    }  

    Select-Folder -Message $Message -path $env:USERPROFILE

    $selectedFolder = $this

}

Function Start-FolderSelection
{
    $script:firstFolder = Get-Folder -Message "Select the reference folder"
    $script:secondFolder = Get-Folder -Message "Select the folder to compare"
}

Function Compare-FolderContents
{
    $firstFolderChildren = Get-ChildItem $script:firstFolder
    $secondFolderChildren = Get-ChildItem $script:secondFolder

    $script:folderComparison = Compare-Object -ReferenceObject $firstFolderChildren -DifferenceObject $secondFolderChildren
}

Function Copy-FileDifferences
{
    $firstFolderDifference = $script:folderComparison | ? { $_.SideIndicator -eq "=>" }
    $secondFolderDifference = $script:folderComparison | ? { $_.SideIndicator -eq "<=" }

    foreach($difference in $firstFolderDifference)
    {
        $diffObj = $difference.InputObject
        Copy-Item $diffObj.FullName -Destination $script:firstFolder
    }
        foreach($difference in $secondFolderDifference)
    {
        $diffObj = $difference.InputObject
        Copy-Item $diffObj.FullName -Destination $script:secondFolder
    }
}

Function Run-Functions
{
    Start-FolderSelection
    Compare-FolderContents
    Copy-FileDifferences
}

Run-Functions