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:
$source = "L:\" $destination = "C:\docs\" $since = (Get-date).AddDays(-365) $includes ="*.doc*","*.pdf","*.xls*","*.ppt*"
$items = get-childitem $source -recurse -include $includes | where-object {$\_.LastAccessTime –gt $since}
foreach ($item in $items)
{
$dir = $item.DirectoryName.Replace($source,$destination)
$target = $item.FullName.Replace($source,$destination)
if (!(test-path($dir))) { mkdir $dir }
if (!(test-path($target)))
{
copy-item -path $item.FullName -destination $target -recurse -force
}
}