运行PowerShell脚本,监视锁定的文件但解锁后运行命令

时间:2018-03-05 21:58:14

标签: powershell

我有一个由CNC控制器写入的文本文件,文件被锁定,直到在CNC控制器上执行某个命令,我想运行一个PowerShell脚本来继续检查这个文件,一旦它不是更长时间的锁定,PowerSheel在我们的Intranet上打开一个特定的网页,处理该文件并将该数据存储在SQL数据库中。

我看过一些脚本来检查一个文件是否被锁定,并且看到一些文件不断监视文件,如果它已经更改,我需要两者混合

P.S。我是PowerShell的新手!!!

这是我想要使用的脚本,但希望它不要查找CHANGED事件,但是一旦文件$ OUT $ .DAT不再被其他进程锁定

### 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}

1 个答案:

答案 0 :(得分:0)

您可以修改该代码并将其添加到函数中,即:

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
}

然后你可以将函数调用放入if语句或循环中,如下所示:

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

定时循环:

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

}

这将持续运行直至取消。如果您希望它运行一段时间,请使用:

$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

}