How to make specific files to zero byte files

Viewed 248

I have a bunch of *.FLAC files in different subfolders, which I want to turn into zero byte files, for database use only. I have the following code, but it makes all files to zero bytes. I don‘t know, how to fit the code. Maybe you can help? Thanks!

$Path='G:\Music\' 
$Files=Get-ChildItem -Path $Path -File -Recurse | Where-Object  {($_.Length) -gt 0} 
    ForEach ($File in $Files) { New-Item$File.FullName -Force -Value '' }

1 Answers

This is how you can replace all your FLAC files for zero byte FLAC files recursively. You can use a normal foreach loop or pipe to foreach-object.

You don't really need to check if the FLAC file's length is greater than 0 but you can also add that condition.

$Path='G:\Music' # Define parent path
$Files=Get-ChildItem -Path $Path -File -Recurse -Filter *.FLAC # Get all FLAC files recursively

foreach($file in $files)
{
    $null > $file.FullName
}

# OR using foreach-object (same result)

Get-ChildItem -Path $Path -File -Recurse -Filter *.FLAC | ForEach-Object {$null > $_.FullName}

Edit:

Adding these 2 examples below for PS 5.1. As it seems, $null > file doesn't create an actual zero byte file on this PS version, see below comments from @mklement0 for more info.

# Example 1 (Not efficient)
Get-ChildItem -Path $Path -File -Recurse -Filter *.FLAC | ForEach-Object {
    New-Item -Path $_.FullName -Force
}

# Example 2
New-Item -Force (Get-ChildItem -Path $path -File -Recurse -Filter *.FLAC).FullName
Related