我有一个名为 Write-Logs 的函数,在许多其他脚本/每个循环中被调用。我意识到当涉及到循环时需要花费很多时间。我认为这是由于 I/O 开销造成的。 由于某些原因,我不能/不允许更新任何主要脚本。是否可以在功能级别上做一些事情来提高性能?我愿意接受任何建议。
Function Write-Logs {
Param(
[parameter(Mandatory=$true)][string]$logContent,
[parameter(Mandatory=$true)][string]$logPath
)
$currentTime = Get-Date
If(!(Test-Path $logPath)){
New-Item -Path $logPath -ItemType 'file' -Force
}
Write-Output "$($currentTime): $($logContent)" | Out-File $logPath -Append
}
例如我的
main.ps1
# This test folder could contain more than 1000 items
$mySrc = 'D:\test'
$myLogPath = 'D:\Logs\mylog.txt'
Get-ChildItem -Path $mySrc -Recurse | ForEach-Object {
Write-Logs -logContent $_.FullName -logPath $myLogPath
}
您可能会考虑使用可步进管道
创建一个带有处理块的
advanced function
:
Write-Log
(使用单数名词)
Function Write-Log {
Param(
[parameter(ValueFromPipeLine=$True)][string]$logContent,
[parameter(Mandatory=$true)][string]$logPath
)
begin {
$Pipeline = { Out-File -FilePath $logPath -Append }.GetSteppablePipeline()
$Pipeline.Begin($True)
}
process {
$currentTime = Get-Date
$Pipeline.Process("$($currentTime): $_")
}
end {
$Pipeline.End()
}
}
用途:
Get-ChildItem -Path $mySrc -Recurse | Write-Log -LogPath $myLogPath
性能优势在于,您不必连续(重新)打开和关闭每个 Get-ChildItem
FileSystemInfo
条目的日志文件,而是保持打开状态直到管道结束。