Exclude list in PowerShell Copy-Item does not appear to be working

前端 未结 10 927
旧时难觅i
旧时难觅i 2020-12-02 11:40

I have the following snippet of PowerShell script:

$source = \'d:\\t1\\*\'
$dest = \'d:\\t2\'
$exclude = @(\'*.pdb\',\'*.config\')
Copy-Item $source $dest -R         


        
10条回答
  •  情书的邮戳
    2020-12-02 12:31

    I had a similar problem extending this a bit. I want a solution working for sources like

    $source = "D:\scripts\*.sql"
    

    too. I found this solution:

    function Copy-ToCreateFolder
    {
        param(
            [string]$src,
            [string]$dest,
            $exclude,
            [switch]$Recurse
        )
    
        # The problem with Copy-Item -Rec -Exclude is that -exclude effects only top-level files
        # Copy-Item $src $dest    -Exclude $exclude       -EA silentlycontinue -Recurse:$recurse
        # http://stackoverflow.com/questions/731752/exclude-list-in-powershell-copy-item-does-not-appear-to-be-working
    
        if (Test-Path($src))
        {
            # Nonstandard: I create destination directories on the fly
            [void](New-Item $dest -itemtype directory -EA silentlycontinue )
            Get-ChildItem -Path $src -Force -exclude $exclude | % {
    
                if ($_.psIsContainer)
                {
                    if ($Recurse) # Non-standard: I don't want to copy empty directories
                    {
                        $sub = $_
                        $p = Split-path $sub
                        $currentfolder = Split-Path $sub -leaf
                        #Get-ChildItem $_ -rec -name  -exclude $exclude -Force | % {  "{0}    {1}" -f $p, "$currentfolder\$_" }
                        [void](New-item $dest\$currentfolder -type directory -ea silentlycontinue)
                        Get-ChildItem $_ -Recurse:$Recurse -name  -exclude $exclude -Force | % {  Copy-item $sub\$_ $dest\$currentfolder\$_ }
                    }
                }
                else
                {
    
                    #"{0}    {1}" -f (split-path $_.fullname), (split-path $_.fullname -leaf)
                    Copy-Item $_ $dest
                }
            }
        }
    }
    

提交回复
热议问题