Search code examples
powershellfilesizefilesystemwatcher

How can I get a file size when it triggers a FileSystemWatcher?


I need to get the size of a file when it is created in a specified folder for statistics purpose. I've tried different solutions, the best one I found is this one but it always returns 0 instead of the file size.

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\GUFE\Desktop"
$watcher.Filter = "*.pdf*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true  


$action = { $path = $Event.SourceEventArgs.FullPath
            $changeType = $Event.SourceEventArgs.ChangeType
            $size = (Get-Item '$path').length
            $logline = "$(Get-Date), $changeType, $path, $size"
            Add-content "C:\Users\GUFE\Desktop\log2.txt" -value $logline
          }    

Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}

For now I just put informations in a log file to see if I get the right ones.

Thank you in advance for your answers.


Solution

  • The problem is in this line:

    $size = (Get-Item '$path').length

    Because $path is inside single quotes, string interpolation is not enabled, so Get-Item is literally looking for a file called '$path', which, obviously, doesn't exist. Use no quotes or double-quotes instead:

    $size = (Get-Item $path).length