Mike Todd
Mike Todd

Reputation: 101

Run a PowerShell Script that Monitors a file that's lock but once unlocked runs a command

I have a text file that is written to by a CNC Controller, the file is locked until a certain command in executed on the CNC Controller, I want to have a PowerShell Script running that keeps checking this file and once it is no longer locked, PowerSheel opens up a certain Webpage on our Intranet that processes the file and stores that data in an SQL database.

I've seen some scripts to check if a file is locked and seen some that constantly monitors a file for if its Changed, i need a mix of both

P.S. i'm a complete novice on PowerShell!!!

This is the Script I want to use but want it not to look for CHANGED events but once the file $OUT$.DAT is no longer locked by nother process

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "c:\ftpserver"
$watcher.Filter = "*.dat"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
            $changeType = $Event.SourceEventArgs.ChangeType
            $logline = "$(Get-Date), $changeType, $path"
            Add-content "c:\ftpserver\log.txt" -value $logline
          }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
Register-ObjectEvent $watcher "Changed" -Action $action
while ($true) {sleep 5}

Upvotes: 1

Views: 5192

Answers (1)

Owain Esau
Owain Esau

Reputation: 1922

You can modify that code and add it to a function i.e. :

function checkLock {
    Param(
        [parameter(Mandatory=$true)]
        $filename
    )
    $file = gi (Resolve-Path $filename) -Force
    if ($file -is [IO.FileInfo]) {
        trap {
            return $true
            continue
        }
        $stream = New-Object system.IO.StreamReader $file
        if ($stream) {$stream.Close()}
    }
    return $false
}

You can then just chuck the function call into an if statement or a loop like so:

if ((checkLock $filename) -eq $true) {
    Write-Host "file locked"
    continue
}
else {
    Write-Host "file not locked"
    << code you want to run on unlocked file >>
}

Timed loop:

While ($True) {
    if ((checkLock $filename) -eq $true) {
        Write-Host "file locked"
        continue
    }
    else {
        Write-Host "file not locked"
        << code you want to run on unlocked file >>
    }

    start-sleep -seconds 10

}

This will run continually until canceled. If you want it to run for a set amount of time use:

$timeout = new-timespan -Minutes 1
$sw = [diagnostics.stopwatch]::StartNew()
While ($sw.elapsed -lt $timeout) {
    if ((checkLock $filename) -eq $true) {
        Write-Host "file locked"
        continue
    }
    else {
        Write-Host "file not locked"
        << code you want to run on unlocked file >>
    }

    start-sleep -seconds 10

}

Upvotes: 1

Related Questions