0

I need to open file B when file A is changed and then let file B open file A without triggering the watcher again. My thoughts are that I can do this with an if statement in '$changeAction' that checks to see if File B is open first.

I imagine this would be something like:

if(file B is open, then do nothing, else open file B)

How do I write this in Powershell?

 Function Register-Watcher {
        param ($folder)
        $filter = "*.xlsx"
        $folder = "\\powershell\watcher\test\folder"

        $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
            IncludeSubdirectories = $false
            EnableRaisingEvents = $true


        }

        $changeAction = [scriptblock]::Create('

            $path = $Event.SourceEventArgs.FullPath
            $name = $Event.SourceEventArgs.Name
            $changeType = $Event.SourceEventArgs.ChangeType
            $timeStamp = $Event.TimeGenerated

            Write-Host "The file $name was $changeType at $timeStamp"

            $Excel = New-Object -ComObject Excel.Application
            $Excel.Workbooks.Open("\\powershell\watcher\test\folder\fileB.xlsm") #this should be the 'else' in the 'if File B is open#

        ')

        Register-ObjectEvent $Watcher "Changed" -Action $changeAction
    }

     Register-Watcher "\\powershell\watcher\test\folder\fileA.xlsx"
     $Change
Jeff T.
  • 11
  • 6

1 Answers1

0

To do this, you could check if there any Excel process running which has opened a particular file.

Get-CimInstance Win32_Process -Filter "CommandLine like '%filepath.xlsx%'"

Based on the output of the above expression, you can decide wether to open the file or not.

Prasoon Karunan V
  • 2,916
  • 2
  • 12
  • 26