1

我有这个功能来读取 SQL Server 错误日志,但问题是我无法读取服务器当时正在使用的错误日志。我一直在谷歌搜索,似乎 Fileshare 标志不适用于 powershell。当我尝试打开文件时,有什么方法可以设置 Fileshare 标志吗?

    功能检查日志{
        参数($日志)
        $pos
        foreach($log in $logpos){
            如果($log.host -eq $logs.host){
                $当前日志 = $日志
                休息
            }
        }
        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}
        否则{$pos = 0}
        if($logs.enc -eq $null){$br = New-Object System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open)) }
        别的{
            $encoding = $logs.enc.toUpper().Replace('-','')
            if($encoding -eq 'UTF16'){$encoding = 'Unicode'}
            $br = 新对象 System.IO.BinaryReader([System.IO.File]::Open($path, [System.IO.FileMode]::Open), [System.Text.Encoding]::$encoding)
        }
        $required = $br.BaseStream.Length - $pos
        如果($需要-lt 0){
            $pos = 0
            $required = $br.BaseStream.Length
        }
        if($required -eq 0){$br.close(); 返回 $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("错误:"))
            {
                $errorLine = [正则表达式]::Split($s, "\s\s+")
                $err = [正则表达式]::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."

吉斯利

4

1 回答 1

1

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

The binary reader constructor takes as input a stream. I didn't define the stream seperately and that's why I didn't notice that you set the FileShare flag in the stream's constructor.

What I had to do was to change this:

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

To this:

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

And then it worked like a charm.

Gísli

于 2012-01-03T13:50:26.423 回答