PowerShell: Copy-Item -recurse -force Does Not Create Directories when Using Get-ChildItem -include
I recently wrote a PowerShell script which copied documents from a filter to my local hard drive. I chose PowerShell for this task because it was one of the few programs actually allowed on my ultra locked-down workstation (and 'cuz I love it.)
Because I only wanted specific types of files, I gathered the list of documents using get-childitem -recurse -include and then copied the files using copy-item. What I didn't initially realize was that copy-item's -recurse and -force switches are ineffective in my script because 1.) I'm passing the copy-item command one item at a time and 2.) the get-childitem include switch is "best considered a file filter," according to Lee Holmes of Microsoft's PowerShell team.
I got around this by manually creating the directory structure as needed using if (!(test-path $dir)) { mkdir $dir }. The entire script can be found below:
1$source = 'L:\'
2$destination = 'C:\docs\'
3$since = (Get-Date).AddDays(-365)
4$includes = '*.doc*','*.pdf','*.xls*','*.ppt*'
5
6$items = Get-ChildItem $source -Recurse -Include $includes | Where-Object { $_.LastAccessTime -gt $since }
7
8foreach ($item in $items) {
9 $dir = $item.DirectoryName.Replace($source, $destination)
10 $target = $item.FullName.Replace($source, $destination)
11
12 if (!(Test-Path $dir)) { mkdir $dir }
13
14 if (!(Test-Path $target)) {
15 Copy-Item -Path $item.FullName -Destination $target -Recurse -Force
16 }
17}
Update 2025: -Include acts as a wildcard filter and only takes effect when the -Path contains a wildcard or when combined appropriately with -Filter. If you're running into odd results, consider using -Filter and -File with Get-ChildItem (for example: Get-ChildItem -Path 'L:\*' -Recurse -Filter '*.pdf' -File). The behavior described above about copying one file at a time still applies: Copy-Item -Recurse creates directories when copying directories, but not when you pass individual files—so creating the target directories first (as shown) remains a valid approach.