mercredi 30 janvier 2019

How do I keep powershell from opening an excel file if its already open?

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

Aucun commentaire:

Enregistrer un commentaire