I have a powershell script that copies files from $source to $dest and it excludes some files types. It excludes my csv files and web.config files fine, but it won't exclude the Log folder contents. This is my script, what is the correct syntax to exclude the files contents but not the Log folder itself?

$exclude = @('Thumbs.db','*-Log.csv','web.config','Logs/*')

Get-ChildItem $source -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($source.length)}
link|improve this question
feedback

2 Answers

up vote 1 down vote accepted

You'll need to setup a second Array with the paths you want to avoid and then add a filter in the pipe. Here's some sample code:

$exclude = @('Thumbs.db','*-Log.csv','web.config','Logs/*')
$directory = @("C:\logs")
Get-ChildItem $source -Recurse -Exclude $exclude | where {$directory -notcontains $_.DirectoryName}
link|improve this answer
Will that copy the directory but not the files or will it just ignore the entire folder? – guanome Nov 21 '11 at 17:31
That should copy the folder but not the contents. The where clause only affects files. If you want to limit folders, you have to use "$_.Name" or "$_.FullName" depending on the situation. – Doltknuckle Nov 21 '11 at 22:32
For me that where clause makes no sense, but it works! – guanome Nov 29 '11 at 13:43
feedback

You could make your own recursive copy function.

function Copy-WithFilter ($sourcePath, $destPath)
{
    $exclude = @('Thumbs.db', '*-Log.csv','web.config', 'Logs')

    # Call this function again, using the child folders of the current source folder.
    Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_.Length -eq $null } | % { Copy-WithFilter $_.FullName (Join-Path -Path $destPath -ChildPath $_.Name) } 

    # Create the destination directory, if it does not already exist.
    if (!(Test-Path $destPath)) { New-Item -Path $destPath -ItemType Directory | Out-Null }

    # Copy the child files from source to destination.
    Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_.Length -ne $null } | Copy-Item -Destination $destPath

}

# $source and $dest defined elsewhere.
Copy-WithFilter $source $dest
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.