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.
- 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 }
- Call the PowerShell script.
& $HOME/Documents/code/github/powershell/ch09/02-Clear-LogFiles.ps1
Here is a glimpse of what that outputs.
- 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.
- 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.