I am crafting a Powershell script that aims to turn off a Windows machine (laptop/PC) once a download of one or more files is completed (for the sake of the example, let's assume one large file is the case here).
In few words, we're reading the size of the entire downloads folder each x seconds and we compare the before and after delay sizes. If there is no change in the recent time, that means the download is either completed or stuck, both cases lead to shutdown.
Given the following script (the size getter can be a standalone function at some point, yes):
#Powershell5
#Major Minor Build Revision
# ----- ----- ----- --------
# 5 1 19041 1320
$downloadDir = "C:\Users\edi\Downloads"
while (1)
{
$s1 = Get-ChildItem -Path $downloadDir | Measure-Object -Property Length -Sum | Select-Object Sum
write-host "S1:" $s1.sum
# this 3 seconds time is just for testing purposes; in real case scenario this will most
# likely be set to 60 or 120 seconds.
Start-Sleep -s 3
$s2 = Get-ChildItem -Path $downloadDir | Measure-Object -Property Length -Sum | Select-Object Sum
write-host "S2:" $s2.sum
if ($s1.sum -eq $s2.sum)
{
write-host "Download complete, shutting down.."
# loop exit is this, actual shutdown; commented out for testing purposes.
#shutdown /s
}
}
The problem I am facing is that the file sizes reading is not done "in real time". In other words, the file size is not changing as you would normally see in Explorer view. I need to be able to read these numbers (changing file size) in real time.
Interesting fact: while the download is in progress and the script running, if manually going to the downloads folder and hit F5 / Refresh... the numbers change (the size reading is accurate).
Side note: My research got me to this article that might present the root cause, but I am not 100% sure of it: https://devblogs.microsoft.com/oldnewthing/20111226-00/?p=8813
Appreciate any idea on this. Thanks in advance!