2016-11-14 20 views
1
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

您正在尋找['robocopy'(https://technet.microsoft.com/en-us/library/cc733145.aspx)。 –

+0

'robocopy || headaches' – sodawillow

回答

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 
1

嘗試只是這

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