LP13
LP13

Reputation: 34159

Powershell exclude issue with version 4

I want to copy a folder recursively and exclude some files while coping

On my local machine (with windows 10 OS) i have power-shell version

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      16299  251

The command below copies c:\source\publish folder to c:\dest and excludes the files as expected

$exclude = @('appsettings.staging.json','appsettings.production.json')

Copy-Item -Path "c:\source\publish" -Destination "c:\dest" -Exclude $exclude -recurse -Force -PassThru

On our build server i have the following powershell version

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

When i run the above command on the build server, it copies the folder to c:\dest as expected but DOES NOT exclude the files.

On the build server, to exclude the files i have to append \* to source path something like below

Copy-Item -Path "c:\source\publish\*" -Destination "c:\dest" -Exclude $exclude -recurse -Force -PassThru

The command above excludes the files, however it does not create publish folder under c:\dest instead it copies files directly to c:\dest

How do i copy the folder but also exclude the files with version 4.0.-1.-1

Upvotes: 1

Views: 98

Answers (3)

Esperento57
Esperento57

Reputation: 17492

Other method, more interressant because you can modify the where condition to be more specific :

$exclude = @('appsettings.staging.json','appsettings.production.json')
$Dest = New-Item -Path "c:\dest"-ItemType Directory -Force

Get-ChildItem "c:\source\publish" -file -Recurse | where name -notin $exclude | Copy-Item -Destination $Dest.FullName -Force

Upvotes: 0

G42
G42

Reputation: 10019

You could build logic based on the version of PowerShell being used.

$exclude = @('appsettings.staging.json','appsettings.production.json')
$source  = "c:\source\publish"
$dest    = "c:\dest"


if($PSVersionTable.PSVersion.Major -eq 4){
    $dest    = $dest + "\" + (Split-Path $source -leaf)
    $source  = $source + '\*'
    New-Item -Path $dest -ItemType Directory -Force
}

Copy-Item -Path $source -Destination $dest -Exclude $exclude -recurse -Force -PassThru

Upvotes: 1

TheMadTechnician
TheMadTechnician

Reputation: 36342

If you define different paths you are going to get different results. Specifying c:\source\publish says to get that folder c:\source\publish\* says to get everything within that folder, excluding the folder itself. So your destination path would need to account for that. You can simply create the path first, and then copy to it.

$exclude = @('appsettings.staging.json','appsettings.production.json')
$Dest = New-Item -Path "c:\dest\publish"-ItemType Directory -Force
Copy-Item -Path "c:\source\publish\*" -Destination $Dest.FullName -Exclude $exclude -recurse -Force -PassThru

Upvotes: 1

Related Questions