How to do it...

Here is an outline of the steps you would want to take:

  1. Get all the files at the path specified.
  2. Group the files by file type (extension).
  3. Filter out those groups that contain more than one item.
  4. Expand each group, sort the files by size (length).
  5. Pick the two largest files in each group.
  6. Delete the files.

While we are working on a sandbox directory, and that we are taking precautions not to delete anything important, it is still better to only prototype the action using ShouldPerform (the WhatIf parameter). This way, the files would not be actually deleted, but PowerShell would only tell you what it would do if the command is run.

Let us get cracking.

  1. List the contents of the current directory and group the output based on the extension.
PS> Get-ChildItem -Path . -File | Group-Object -Property Extension
  1. Filter to discard lone files of each extension.
PS> Get-ChildItem -Path . -File | Group-Object -Property Extension | Where-Object Count -GT 1
  1. Now comes a loop construct. We will look at how that works in a future chapter. For now, just know that it works. The goal here is to only leverage the pipeline.
PS> Get-ChildItem -Path . -File | Group-Object -Property Extension | Where-Object Count -GT 1 | ForEach-Object {$_.Group | Sort-Object Length -Bottom 2}
  1. Delete these files using the Remove-Item cmdlet. Use the WhatIf switch if you do not want the files actually deleted.
PS> Get-ChildItem -Path . -File | Group-Object -Property Extension | Where-Object Count -GT 1 | ForEach-Object {$_.Group | Sort-Object Length -Bottom 2} | Remove-Item -WhatIf
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.178