在Powershell中使用get-childitem时排除文件夹和文件

时间:2019-09-18 07:15:18

标签: powershell

我不确定应该如何排除以下内容:  .env, web.config, node_modules

$sourceRoot = "C:\Users\Wade Aston\Desktop\STEMuli\server"
$destinationRoot = "C:\Users\Wade Aston\Desktop\STEMuli/server-sandbox"
$dir = get-childitem $sourceRoot -Exclude .env, web.config, node_modules <-- How do I exclude these       
$i=1
$dir| %{
    [int]$percent = $i / $dir.count * 100
    Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
    $_ | copy -Destination $destinationRoot  -Recurse -Force
    $i++
}

谢谢=]

2 个答案:

答案 0 :(得分:1)

一些注意事项: *尝试使用通配符来应用排除,例如:* .env * Copy-Item参数Source,允许使用String类型的集合。与使用foreach顺序处理相比,使用collection应该更快。 *如果仅需要文件,则可以考虑使用Get-ChildItem -File

您可以尝试以下方法:

$Source = Get-ChildItem -Path C:\TEMP -Exclude dism.log, *.csv 
$dest = 'C:\temp2'

Copy-Item -Path $Source -Destination $dest -Force

希望有帮助!

答案 1 :(得分:1)

要排除“ * .env”和“ web.config”之类的某些文件并排除具有特定名称的文件夹,您可以执行以下操作:

$sourceRoot      = "C:\Users\Wade Aston\Desktop\STEMuli\server"
$destinationRoot = "C:\Users\Wade Aston\Desktop\STEMuli\server-sandbox"

$dir = Get-ChildItem -Path $sourceRoot -Recurse -File -Exclude '*.env', 'web.config' | 
       Where-Object{ $_.DirectoryName -notmatch 'node_modules' }

$i = 1
$dir | ForEach-Object {
    [int]$percent = $i / $dir.count * 100
    Write-Progress -Activity "Copying ... ($percent %)" -Status $_  -PercentComplete $percent -Verbose

    $target = Join-Path -Path $destinationRoot -ChildPath $_.DirectoryName.Substring($sourceRoot.Length)
    # create the target destination folder if it does not already exist
    if (!(Test-Path -Path $target -PathType Container)) {
        New-Item -Path $target -ItemType Directory | Out-Null
    }
    $_ | Copy-Item -Destination $target -Force
    $i++
}
相关问题