当前位置: 动力学知识库 > 问答 > 编程问答 >

powershell - Trying to write a function to copy subfolders and files of a directory and only the difference

问题描述:

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

}

}

I want to copy it to LocalAppData in users profile.

网友答案:

try just this

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

This will copy the difference of objects in two folders so that all files not in the first get copied to the second, and vice verse. You could change the destination to a user's Local\AppData folder. Hope this gives you a good starting point.

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: