无法使用二进制阅读器读取打开的文件

时间:2012-01-03 11:26:44

标签: powershell file-io binaryreader

我有这个函数来读取SQL Server错误日志,但问题是我无法读取服务器当时使用的错误日志。我一直在google-ing,似乎Fileshare标志不适用于PowerShell。当我尝试打开文件时,有没有办法设置Fileshare标志?

    function check_logs{
        param($logs)
        $pos
        foreach($log in $logpos){
            if($log.host -eq $logs.host){
                $currentLog = $log
                break
            }
        }
        if($currentLog -eq $null){
            $currentLog = @{}
            $logpos.Add($currentLog)
            $currentLog.host = $logs.host
            $currentLog.event = $logs.type
            $currentLog.lastpos = 0
        }
        $path = $logs.file
        if($currentLog.lastpos -ne $null){$pos = $currentLog.lastpos}
        else{$pos = 0}
        if($logs.enc -eq $null){$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open))}
        else{
            $encoding = $logs.enc.toUpper().Replace('-','')
            if($encoding -eq 'UTF16'){$encoding = 'Unicode'}
            $br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open), [System.Text.Encoding]::$encoding)
        }
        $required = $br.BaseStream.Length - $pos
        if($required -lt 0){
            $pos = 0
            $required = $br.BaseStream.Length
        }
        if($required -eq 0){$br.close(); return $null}
        $br.BaseStream.Seek($pos, [System.IO.SeekOrigin]::Begin)|Out-Null
        $bytes = $br.ReadBytes($required)
        $result = [System.Text.Encoding]::Unicode.GetString($bytes)
        $split = $result.Split("`n")
        foreach($s in $split)
         {
            if($s.contains("  Error:"))
            {
                $errorLine = [regex]::Split($s, "\s\s+")
                $err = [regex]::Split($errorLine[1], "\s+")
                if(log_filter $currentLog.event $err[1..$err.length]){$Script:events = $events+ [string]$s + "`n" }         
            }
        }
        $currentLog.lastpos = $br.BaseStream.Position 
        $br.close()
     }

要清楚,当我尝试打开文件时会出现错误。错误消息是:

 Exception calling "Open" with "2" argument(s): "The process cannot access the file
 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' 
  because it is being used by another process."

吉斯利

1 个答案:

答案 0 :(得分:0)

所以我找到了答案,这很简单。

二进制读取器构造函数将流作为输入。我没有单独定义流,这就是为什么我没注意到你在流的构造函数中设置了FileShare标志。

我必须做的是改变这一点:

{$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open))}

对此:

{$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite))}

然后它就像一个魅力。

吉斯利