Home > Blockchain >  Powershell: How to remove files that contain 2 or less lines
Powershell: How to remove files that contain 2 or less lines

Time:09-21

My question is as follows: I have a main directory that contains several sub-directories, each of the sub directories contain several files than contain 1 or more lines. I would like to remove all files from these sub directories that contain 1 or 2 lines and leave all files that contain more than 2 lines.

What I have found/come up with until now:

$ActionTargetFolder = "\\networkfolder\"
$GetAllActionTargetSubFolders = Get-ChildItem $ActionTargetFolder -Recurse -Directory

Get-ChildItem $GetAllActionTargetSubFolders -Recurse -File  | Where-object  { 
    ((Get-Content $_| Measure-Object -line).lines) -le 2 } | Remove-Item -Force 

No files are removed, no errors come up: what do I need to change?

I hope someone could help

Example file content:

Filename 1: CustomernameA_20220820

Content file 1 (must not be removed, since it contains 4 lines):

|Changed database context to 'ABCLog'.
|Identifier |2022-08-11 |Time |Actions |191 |ActionCompleted
|Identifier |2022-08-12 |Time |Actions |269 |ActionCompleted
|Identifier |2022-08-13 |Time |Actions |104 |ActionCompleted

Filename 2:CustomernameA_20220827

Content file 2 (must not be removed, since it contains 3 lines):

|Changed database context to 'ABCLog'.
|Identifier |2022-08-12 |Time |Actions |26 |ActionCompleted
|Identifier |2022-08-13 |Time |Actions |104 |ActionCompleted

So the general idea is to combine these files into one file, since they have duplicate data. Furthermore, as you can see for date 2022-08-12, the value is different: the value in the second line is always wrong and should therefore be removed. The first line contains the line 'Changed database context to 'ABCLog'.' and can also be removed. I can combine the files by skipping the first to lines and put the rest in one file, however, sometime the file does not contain a line with values: if I then skip 2 lines, my script keeps on processing (cannot cope with an empty file??). Therefore, I want to remove all files that only have 1 or 2 lines in them: they will be made empty and are of no use to me.

Typical file that I want to be removed:

Filename 3:CustomernameA_20220827

Content file 3 (must be removed, contains 2 lines):

|Changed database context to 'ABCLog'.|
|Identifier |2022-08-12 |Time |Actions |26 |ActionCompleted

I hope I clarified it some more.

CodePudding user response:

my approach would be like this

Get-ChildItem -Path "C:\stackoverflow\" -Filter "*.txt" -Recurse -File | ForEach-Object {
$StreamReader = [System.IO.StreamReader]::new($_.fullname)
#Read FirstLine - do nothing
$StreamReader.ReadLine() 
#Read SecondLine - do nothing
$StreamReader.ReadLine() 
#Read ThirdLine - Remove File if Null
if ($StreamReader.ReadLine() -eq $null){
$StreamReader.Close()
Remove-Item -Path $_.FullName
}
}
  • Related