PowerShell kullanarak ULS ve IIS Günlük Dosyalarını SharePoint'te arşivleyin


Gereksinim: IIS ve ULS Günlüğünün Günlük dosyalarını arşivleyin.

SharePoint'teki günlük dosyaları (hem IIS Günlüğü hem de ULS Günlüğü), yapılandırmalarınıza ve kullanımınıza bağlı olarak büyüyebilir ve disk alanını doldurabilir. Çeşitli bloglarda ve panolarda pek çok komut dosyası mevcuttur ve İşte SharePoint sunucularındaki günlük dosyalarını arşivlemek için kullandığım komut dosyası.

Günlük Dosyalarını SharePoint'te Arşivlemek için PowerShell:

Yapılandırma parametreleri bölümünde günlük dosyası yolunu ve arşiv konumunu ayarlayın ve betiği çalıştırın. Bu komut dosyası şunları yapar:

  • Son olarak 7 Gün veya bugünden önce değiştirilen tüm günlük dosyalarını bir klasöre kopyalar.
  • Arşivlenecek günlük dosyalarını içeren klasörden bir Zip dosyası oluşturun.
  • Eski günlük dosyalarını siler.

Add-Type -Assembly System.IO.Compression.FileSystem

#Configuration Parameters
$LogFilesPath="C:\inetpub\logs\LogFiles\W3SVC3"
$ArchivePath="C:\LogArchive"

#Get All Log Files Modified before Last Week
$LogFilesToArchive = Get-ChildItem -Path $LogFilesPath -recurse | where-object {$_.LastWriteTime -le (Get-Date).addDays(-7) }
Write-host "Total Log Files to Archive:"$LogFilesToArchive.count -f Yellow
if($LogFilesToArchive.count -eq 0) { Break }

#Create a Temp Folder
$LogFileDate = Get-Date -Format "yyyyMMdd"
$TempFolder = Join-path -path $ArchivePath $LogFileDate
If (!(Test-Path $TempFolder)) 
{  
    New-Item $TempFolder -type Directory | Out-Null
}

#Copy Log Files to Temp Folder and Remove them
Foreach ($Logfile in $LogFilesToArchive)
{
    #Copy Log file to the Temp Directory
    Copy-Item -Path $Logfile.FullName -Destination $TempFolder
    
    #Delete the copied Log file from the source
    Remove-Item $Logfile.FullName -Confirm:$False
}

#Archive the Temp Folder
$ZipFileName= "$($ArchivePath)\$($LogFileDate).zip"
If (Test-Path $ZipFileName){ Remove-Item $ZipFileName }

$CompressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($TempFolder, $ZipFileName, $CompressionLevel, $False)

#Remove the Temp Folder
Remove-Item $TempFolder -Recurse -Force -Confirm:$False

Write-host "$($LogFilesToArchive.count) Log Files Archived to '$($ZipFileName)'" -f Green

Komut dosyasını otomatikleştirmek için Windows Görev zamanlayıcısında zamanlayın. Günlük dosyalarını birden çok konumdan arşivlemek için komut dosyasını yeniden kullanılabilir bir işlevin içine de sarabilirsiniz. Bu komut dosyası 30 günden eski tüm günlük dosyalarını kaldırır. İhtiyaçlarınıza uyacak şekilde sabit kodlanmış değeri değiştirebilirsiniz.


Add-Type -Assembly System.IO.Compression.FileSystem

Function Archive-Logs($LogFilesPath, $ArchivePath)
{
    #Get All Log Files Modified older than a Last Week
    $LogFilesToArchive = Get-ChildItem -Path $LogFilesPath -recurse | where-object {$_.LastWriteTime -le (Get-Date).addDays(-30) }
    Write-host "Total Log Files to Archive:"$LogFilesToArchive.count -f Yellow
    if($LogFilesToArchive.count -eq 0) { Return }

    #Create a Temp Folder
    $LogFileDate = Get-Date -Format "yyyyMMdd-HHMMss"
    $TempFolder = Join-path -path $ArchivePath $LogFileDate
    If (!(Test-Path $TempFolder)) 
    {  
        New-Item $TempFolder -type Directory | Out-Null
    }

    #Copy Log Files to Temp Folder and Remove them
    Foreach ($Logfile in $LogFilesToArchive)
    {
        #Copy Log file to the Temp Directory
        Copy-Item -Path $Logfile.FullName -Destination $TempFolder
    
        #Delete the copied Log file from the source
        Remove-Item $Logfile.FullName -Confirm:$False
    }

    #Archive the Temp Folder
    $ZipFileName= "$($ArchivePath)\$($LogFileDate).zip"
    If (Test-Path $ZipFileName){ Remove-Item $ZipFileName }

    $CompressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    [System.IO.Compression.ZipFile]::CreateFromDirectory($TempFolder, $ZipFileName, $CompressionLevel, $False)

    #Remove the Temp Folder
    Remove-Item $TempFolder -Recurse -Force -Confirm:$False

    Write-host "$($LogFilesToArchive.count) Log Files Archived to '$($ZipFileName)'" -f Green
}

#Call The function
Archive-Logs -LogFilesPath "C:\inetpub\logs\LogFiles\W3SVC3232" -ArchivePath "C:\LogArchive"
Archive-Logs -LogFilesPath "C:\inetpub\logs\LogFiles\W3SVC6245" -ArchivePath "C:\LogArchive"
Archive-Logs -LogFilesPath "D:\SPLogs\ULS" -ArchivePath "C:\LogArchive"

Eski Dosyaları Arşivlemek için PowerShell

Aynı klasör alt klasör yapısına sahip tüm eski dosyaları başka bir durumda başka bir klasöre taşıdık.


Function Archive-OldFiles
{
 param
    (
        [Parameter(Mandatory=$true)] [string] $SourcePath,
        [Parameter(Mandatory=$true)] [string] $ArchivePath,
        [Parameter(Mandatory=$true)] [string] $LogFile,
        [Parameter(Mandatory=$false)] [Int] $Days = -30 #Number of Days to check beyyond - based on last modified by date
    )

    Try {
        Add-content $Logfile -value "`n------------------- Archive Files Script Started: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')----------------" 

        #Get All Files from the Source - matching given condition
        $SourceFiles = Get-ChildItem -Path $SourcePath -Recurse -File | Where {$_.LastWriteTime -lt (Get-Date).AddDays($Days)}
        Write-host "Total Number of Files matching in the Source: $($SourceFiles.Count)"
        Add-content $Logfile -value "Total Number of Files matching in the Source: $($SourceFiles.Count)" 
        
        $Counter = 1     
        #Move Files to Archive Folder
        $SourceFiles | ForEach-Object {
            #Get the File name and Folder of the File
            $FileName = $_.FullName
            $FolderPath = $_.Directory.FullName
            $TargetFolder = $FolderPath.Replace($SourcePath, $ArchivePath)

            #Display Progress bar
            $Status  = "Archiving '" + $FileName + "' to " + $TargetFolder +" ($($Counter) of $($SourceFiles.Count))"
            Write-Progress -Activity "Archiving Files..." -Status $Status -PercentComplete (($Counter / $SourceFiles.Count) * 100)

            Try {
                #Create Folder in the destination, if it doesn't exist
                If(!(Test-Path $TargetFolder))
                {
                    New-Item -ItemType Directory -Force -Path $TargetFolder | Out-Null -ErrorAction stop
                }

                #Move Files to Archive
                Move-Item $_.FullName -Destination $TargetFolder -Force -ErrorAction Stop
                Write-Host "Successfully moved $FileName to $TargetFolder\$($_.Name)" -f Green
                Add-Content $LogFile -Value "Successfully moved $FileName to $TargetFolder\$($_.Name)" 
            }
            Catch {  
                Write-host -f Red "Error Moving $FileName to $TargetFolder, $($_.Exception.Message)"  
                Add-Content $LogFile -Value "Error moving $FileName $($_.Exception.Message)"
            }
            $Counter++       
        }
    }
    catch {
        Write-host -f Red "Error Moving $FileName to $TargetFolder, $($_.Exception.Message)"  
        Add-Content $LogFile -Value "Error moving $FileName $($_.Exception.Message)"
    }
    Finally {
        Add-content $Logfile -value "---------------------- Archive Files Script Completed: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')-----------------"
    }    
}
#Parameters
$SourcePath = "E:\Reports"
$ArchivePath = "E:\Reports-Archive"
$Days = "-365"
$LogFile = "E:\Reports\Log.txt"
Archive-OldFiles -SourcePath $SourcePath -ArchivePath $ArchivePath -Days $Days -LogFile $LogFile

IIS günlüklerini PowerShell kullanarak arşivlemek, sunucunuzdaki depolama alanını boşaltmanın ve IIS günlüklerinizin düzenli ve kolay erişilebilir olmasını sağlamanın basit ve etkili bir yoludur. Bu adımları izleyerek IIS günlüklerini PowerShell kullanarak kolayca arşivleyebilir, zamandan ve emekten tasarruf edebilirsiniz.

İlgili makaleler