Search code examples
powershellcopy-item

Need to copy single file to all subfolders recursively


Please can someone help me create a powershell or CMD script, as simple as possible (1 line?) that will do the following...

-Take file (c:\test.txt) -Copy to ALL subfolders within a given folder, including multiple levels deep eg, c:\test1\1\2\3\ and c:\test2\6\7\8\ -Without overwriting that file if it already exists -Not changing ANY existing files. Just adding the original txt file if it doesn't exist.

I've tried a bunch of scripts I found online, changing them, but have been unsuccessful. Either it overwrites existing files, or doesn't go multiple levels deep, or skips all the folders between top/bottom levels, or throws errors. I give up.

Thanks Matt


Solution

  • How about something like this...

    $folders = Get-ChildItem -Recurse -Path C:\temp\1 -Directory
    $file = "c:\temp\test.txt"
    
    foreach($folder in $folders){
        $checkFile = $folder.FullName + "\test.txt"
        $testForFile=Test-Path -Path $checkFile
        if(!$testForFile){
            Copy-Item $file -Destination $folder.FullName
        }  
    }