How to do it

We will simply build on the previous recipe to save ourselves some time and effort. The changes from the script in the previous recipe have been emboldened.

  1. Open your favourite code editor, enter the following in the file and save the file as a ps1 file.
$Today = Get-Date
$TotalFileSize = 0

$AllFiles = Get-ChildItem . -Recurse -File
$FilesToDelete = $AllFiles | Where-Object {[math]::Floor(($Today - $_.LastWriteTime).TotalDays) -eq 30}

foreach ($File in $FilesToDelete) {
    $TotalFileSize += $File.Length
    Remove-Item -Path $File -WhatIf
}

New-Object -TypeName psobject -Property @{
    TotalFiles = $AllFiles.Count
    FilesToDelete = $FilesToDelete.Count
    SpaceCleared = $TotalFileSize
}
  1. Call the PowerShell script.
& $HOME/Documents/code/github/powershell/ch09/02-Clear-LogFiles.ps1

Here is a glimpse of what that outputs.

  1. Now, pick just the SpaceCleared parameter.
(& $HOME/Documents/code/github/powershell/ch09/02-Clear-LogFiles.ps1).SpaceCleared

Notice the reference to the SpaceCleared property, and the output just before the prompt.

  1. Divide the output by 10242 to get the value in MB.
(& $HOME/Documents/code/github/powershell/ch09/02-Clear-LogFiles.ps1).SpaceCleared/[math]::Pow(1024, 2)

Similar to the one above; the total space cleared in MB.

..................Content has been hidden....................

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