PowerShell中的Copy-Item排除列表似乎无法正常工作

80

我有以下 PowerShell 脚本段落:

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

以下代码能够将t1文件夹下的所有文件和文件夹复制到t2,但是它只会排除"root"/"first-level"文件夹中的排除列表,而不会排除子文件夹中的排除列表。

如何使其在所有文件夹中排除排除列表?

12个回答

0

我为日常使用编写了这个脚本,并将其打包到模块中,它可以维护所有目录结构并支持通配符:

function Copy-Folder {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [String]$FromPath,

        [Parameter(Mandatory)]
        [String]$ToPath,

        [string[]] $Exclude
    )

    if (Test-Path $FromPath -PathType Container) {
        New-Item $ToPath -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
        Get-ChildItem $FromPath -Force | ForEach-Object {
            # avoid the nested pipeline variable
            $item = $_
            $target_path = Join-Path $ToPath $item.Name
            if (($Exclude | ForEach-Object { $item.Name -like $_ }) -notcontains $true) {
                if (Test-Path $target_path) { Remove-Item $target_path -Recurse -Force }
                Copy-Item $item.FullName $target_path
                Copy-Folder -FromPath $item.FullName $target_path $Exclude
            }
        }
    }
}

只需调用 Copy-Folder -FromPath 'fromDir' -ToPath 'destDir' -Exclude *.pdb,*.config

-FromPath-ToPath 可以省略,

Copy-Folder -FromPath 'fromDir destDir -Exclude *.pdb,*.config


0
以下代码片段将从$source复制所有文件和文件夹到$dest,但不包括根文件夹和子文件夹中的.pdb.config文件:
Get-ChildItem -Path $source | Copy-Item -Destination $dest -Recurse -Container -Exclude @('*.pdb','*.config')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接