1

I have a script (.ps1) that is monitoring a directory, and when a file is created it should open that specific file (in this case a .pdf).

There are multiple files in the directory, but it should only open the one that gets detected as it gets created/moved to that directory when the script is running.

A new file will be continuously added so the name changes slightly every time. Example1.pdf, Example2.pdf and so on. This means that i need to open the most recent file, regardless of the name.

Right now it is only monitoring the directory, because i am not sure how to proceed with opening the file when it gets detected.

I would like to keep everything in this single script if possible.

(I am not that experienced with powershell. Howerver, I am experienced with cmd/batch. I am trying to convert to powershell)

Any good methods to make this work?

This is my script:

    $host.UI.RawUI.WindowTitle = "Watcher"
    $watcher = New-Object System.IO.FileSystemWatcher 
    $watcher.Path = "C:\top_secret_path\test"
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $false
    $watcher.EnableRaisingEvents = $false  

    $action = { 
        $path = $Event.SourceEventArgs.FullPath 
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\top_secret_path\log.txt" -value $logline 
              }

    Register-ObjectEvent $watcher "Created" -Action $action | Format-Table -AutoSize 
    while ($true) {sleep 5}
  • Just call the file and it should be opened with the default application for it. – Seth Oct 31 '18 at 10:12
  • If you sleep during an event you will lose events. – harrymc Oct 31 '18 at 10:16
  • I cannot call a specific file because the file name wont be the same every time. Example.pdf, Example1.pdf, Example2.pdf and so on. – Tom Oct 31 '18 at 10:49
0

Try doing a check or sort using the LastWriteTime to get the most current file to open.

Something like

$FilePath = 'D:\temp'
$LatestFileName = Get-ChildItem -Path $FilePath -File | 
Sort-Object LastWriteTime -Descending | Select-Object -First 1
Start-Process -FilePath $LatestFileName.FullName

Update for the OP...

My point of the snippet I posted here was not that it was separate from your code. You embody it in your watcher code, so it is only fired after the event triggers and the serialization occurs. This is something I've done for customers for several years, and it has worked as designed.

$host.UI.RawUI.WindowTitle = "Watcher"
$watcher = New-Object System.IO.FileSystemWatcher 
$watcher.Path = "D:\top_secret_path\test"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $false  

$action = { 
    $path = $Event.SourceEventArgs.FullPath 
            $changeType = $Event.SourceEventArgs.ChangeType
            $logline = "$(Get-Date), $changeType, $path"
            Add-content "D:\top_secret_path\log.txt" -value $logline 

            # File action
            $FilePath = $watcher.Path
            $LatestFileName = Get-ChildItem -Path $FilePath -File | 
            Sort-Object LastWriteTime -Descending | Select-Object -First 1
            Start-Process -FilePath $LatestFileName.FullName
          }

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

If you run this, it will only act on the event action. If you stop this and restart it, it will not act on any existing file in the folder until another event fires.

Yet, understand that your code is only looking for new files created. So, if you or a user copies an older dated file from one location to this folder, it will not open, only the latest newly created file will. A copy of course is not a create action. If that is the case, you have to change your event handled to trap for create or add, then change what I gave to match that.

  • Ok, that might work, but I need what you provided, to happen when the script finds out that a new file is added to the folder. I do not want it to open the most recent file when i start the script. I want it to open a file if it gets added after the script has started. – Tom Nov 5 '18 at 17:31
  • Ah ok, i see. I tried it and it says that State: Notstarted. What would cause this? – Tom Nov 7 '18 at 19:04

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.