Matt Deemer
Matt Deemer

Reputation: 133

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

Upvotes: 0

Views: 334

Answers (2)

Theo
Theo

Reputation: 61243

Not a one-liner, but here you go:

$rootFolder = 'PATH OF FOLDER CONTAINING ALL THE SUBFOLDERS'
$fileToCopy = 'c:\test.txt'
$fileName   = [System.IO.Path]::GetFileName($fileToCopy)
Get-ChildItem -Path $rootFolder -Recurse -Directory | ForEach-Object {
    if (!(Test-Path -Path (Join-Path -Path $_.FullName -ChildPath $fileName) -PathType Leaf)) {
        Copy-Item -Path $fileToCopy -Destination $_.FullName
    }
}

Upvotes: 1

dno
dno

Reputation: 189

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
    }  
}

Upvotes: 1

Related Questions