Search code examples
powershellrecursiondirectory-structure

How to use Powershell to recursively overwrite every file in a directory and its subdirectories with 0 bytes/nothing?


I have a directory with many subdirectories and all sorts of files (with and without extensions). I want to be able to keep the folder structure as well as the names of all of the files but remove the actual data, keeping the size of the directory down. Maybe it could even only overwrite files over a certain size, but that's not necessary. I thought it might be doable with Powershell, but I'm open to alternatives. Thanks so much for any and all help!


Solution

  • Use Get-ChildItem to retrieve the list of files. Use Out-File to write over each.

    Get-ChildItem C:\example\Path -Recurse -File | 
        ForEach-Object {
            "" | Out-File -Path $_.FullName -NoNewLine -Force
        }
    

    Note that -NoNewLine is only available in newer versions of PowerShell.