Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)}
share|improve this question
up vote 4 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}
share|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
Note that where clause where {$directory -notcontains $_.DirectoryName} is subtle ... it is matching the given entry's directoryname property against the list in $directory - meaning that exact entries only will work this way. If I want to exclude a path component (like bin) there is no method for that unless I list each and every complete path that I want to exclude (i.e. c:\temp\bin, c:\bin, C:\bin\temp) – user174518 Nov 19 '12 at 18:54

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
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .