Powershell:写入单个日志文件



我已经编写了一个小函数,它可以为安装该模块的每台服务器写入一个日志文件,但不知何故,写入该行的几个周期丢失了,有时我会得到已经在使用的错误文件。我在不同版本的Powershell、PS5.1、PS6、PS7.1 x86和x64上测试了这个功能,结果都是一样的。

if (!(Test-Path -ErrorAction Stop -Path (Join-path -Path $ScriptLogPath -ChildPath "$FQDN.log"))) {
New-Item -Path $ScriptLogPath -Name "$FQDN.log" -Force -ItemType File -ErrorAction Stop
}
$CreatedNew = $false
$Global:MTX = New-Object -TypeName System.Threading.Mutex($true, 'GlobalLogFileMutex', [ref]$CreatedNew)
try {   
if (-not $CreatedNew) {
$Global:MTX.WaitOne(10000) | Out-Null
}
}
catch [System.Threading.AbandonedMutexException] {
if (!(Test-Path -Path 'HKLM:SystemCurrentControlSetserviceseventlogApplicationLogWriter')) {
New-EventLog -LogName Application -Source LogWriter
}
Write-EventLog -LogName "Application" -Source "LogWriter" -EntryType Error -Message $_.Exception -EventId 1000
}           

($Date + $InstanceId + $Severity + $ScriptLineNumber + $ScriptName + $Message) | Out-File -Append -FilePath (Join-path -Path $ScriptLogPath -ChildPath "$FQDN.log")
}
catch {
if (!(Test-Path -Path 'HKLM:SystemCurrentControlSetserviceseventlogApplicationLogWriter')) {
New-EventLog -LogName Application -Source LogWriter
}
Write-EventLog -LogName "Application" -Source "LogWriter" -EntryType Error -Message $_.Exception -EventId 1000
}
finally {
if ($Null -ne $Global:MTX) {
[void]$Global:MTX.ReleaseMutex()
[void]$Global:MTX.Dispose()
}
}

这是将格式化字符串附加到文件中的代码块。

因此,我尝试了不同的方法来处理Mutex,并在全球范围内进行了处理。使用不同的方法将字符串附加到文件中,如添加内容。

为了尝试我使用这个小脚本的功能,它应该写150行,但最终只写了130行,没有一个错误。

for ($num1 = 1 ; $num1 -le 5 ; $num1++) {
Start-Job {
for ($num = 1 ; $num -le 10 ; $num++) {
Write-Log  -Severity 'INFO' -Message "Starting Job $num"
Start-Job -ScriptBlock {
try {
Start-Sleep -Milliseconds (Get-Random -Maximum 10)
Write-Log  -Severity 'INFO' -Message "Starting"
Start-Sleep -Milliseconds (Get-Random -Maximum 10)
Write-Log  -Severity 'INFO' -Message "DONE"
}
catch {
New-Item -Path "C:UsersUserDesktop" -Name (Get-Date -Format "dd/MM/yyyy HH:mm:ss") -ItemType File
}
}
}
}

由于每个服务器都在向同一日志文件写入,我认为您不能覆盖"错误文件已在使用中";

我在想,也许你应该仔细考虑这个概念,并从一个服务器上运行,在那里你通过调用命令进行监控?

最新更新