turbo88
turbo88

Reputation: 453

How to create empty files in all empty folders using PowerShell?

I want to create empty text files in all the subfolders which are empty. The following piece of script will list all the empty subfolders.

$a = Get-ChildItem D:\test -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName

How can I iterate through the output of the above command and create empty text files in them?

Upvotes: 1

Views: 2237

Answers (4)

Raja Nagendra Kumar
Raja Nagendra Kumar

Reputation: 426

this worked for me .. it creates file only if the directory neither has sub-directories or files

$a = Get-ChildItem C:\tejasoft -recurse | Where-Object {$_.PSIsContainer -eq $True -and ($_.GetDirectories().Count -eq 0)}
$path = $a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}
$a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}|ForEach-Object -Process {New-Item -Path $path -Name ".keep" -Value "Test Value" -ItemType File }

Upvotes: 0

Raja Nagendra Kumar
Raja Nagendra Kumar

Reputation: 426

How make sure.. this does not create the file in a directory, which has sub directory in it.

i.e. file should be created in a directory where there are no files and sub-directories

Upvotes: 0

Matt
Matt

Reputation: 46730

There were a few too many loops in the answer you made for yourself. I offer this solution which will make an empty file in all directories that do not have files ( From your solution it is OK if they have folders so I'm keeping with that logic.)

Get-ChildItem -Recurse C:\temp | 
        Where-Object {$_.PSIsContainer -and ($_.GetFiles().Count -eq 0)} | 
        ForEach-Object{[void](New-Item -Path $_.FullName -Name "Touch.txt" -ItemType File)}

If $_.PSIsContainer is false then it won't bother with the other condition of checking for files. Also cast the output of New-Item to void to stop the output of successfully created all those new files.

Upvotes: 2

turbo88
turbo88

Reputation: 453

The following piece of code worked for me.

$a = Get-ChildItem D:\test -recurse | Where-Object {$_.PSIsContainer -eq $True}
$path = $a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}
$a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}|ForEach-Object -Process {New-Item -Path $path -Name "testfile.txt" -Value "Test Value" -ItemType File }

Upvotes: 0

Related Questions