elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [APORTE] [PowerShell] Truncate Log Files
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] [PowerShell] Truncate Log Files  (Leído 349 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.821



Ver Perfil
[APORTE] [PowerShell] Truncate Log Files
« en: 3 Marzo 2024, 22:14 pm »

El siguiente script desarrollado en PowerShell sirve para truncar el tamaño, a cero bytes, de los archivos log (*.log) dentro del directorio actual y subdirectorios. También se puede usar desde el directorio raiz "C:\", por ejemplo.

Es simplemente una herramienta de limpieza ocasional.

En herramientas de limpieza como CCleaner se puede especificar una regla para buscar y eliminar archivos log, sin embargo, si el archivo está en uso, este tipo de herramientas no lo podrá eliminar. En cambio, la metodología empleada en este script se beneficiará de cualquier archivo en uso que comparta permisos de escritura para poder borrar su contenido sin llegar a eliminar el archivo en simismo.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                    .NET Code                                            |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $netCode = @'
  10.    Option Strict On
  11.    Option Explicit On
  12.    Option Infer Off
  13.  
  14.    Imports System
  15.    Imports System.Runtime.InteropServices
  16.    Imports System.Text
  17.  
  18.    Public Class FileUtils
  19.  
  20.        Public Shared Function FormatFileSize(fileSize As Long) As String
  21.            Dim buffer As New StringBuilder(16)
  22.            NativeMethods.StrFormatByteSize(fileSize, buffer, buffer.MaxCapacity)
  23.            Return buffer.ToString()
  24.        End Function
  25.  
  26.    End Class
  27.  
  28.    Friend NotInheritable Class NativeMethods
  29.  
  30.        <DllImport("Shlwapi.dll", CharSet:=CharSet.Auto)>
  31.        Friend Shared Function StrFormatByteSize(fileSize As Long,
  32.               <MarshalAs(UnmanagedType.LPTStr)> buffer As StringBuilder,
  33.                                                 bufferSize As Integer) As Long
  34.        End Function
  35.  
  36.    End Class
  37. '@
  38.  
  39. $netType = Add-Type -TypeDefinition $netCode `
  40.                    -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
  41.                    -PassThru `
  42.                    -ReferencedAssemblies "System.dll" `
  43.                                          | where { $_.IsPublic }
  44.  
  45. <#
  46. ===========================================================================================
  47. |                                                                                         |
  48. |                                    Functions                                            |
  49. |                                                                                         |
  50. ===========================================================================================
  51. #>
  52.  
  53. function Show-WelcomeScreen {
  54.    Clear-Host
  55.    Write-Output ""
  56.    Write-Output " $($host.ui.RawUI.WindowTitle)"
  57.    Write-Output " +==========================================================+"
  58.    Write-Output " |                                                          |"
  59.    Write-Output " | This script will search for log files (*.log) inside the |"
  60.    Write-Output " | current working directory (including subdirectories) to  |"
  61.    Write-Output " | truncate them by setting their length to zero.           |"
  62.    Write-Output " |                                                          |"
  63.    Write-Output " | This may be useful to help reduce the size of a system   |"
  64.    Write-Output " | full of heavy sized log files.                           |"
  65.    Write-Output " |                                                          |"
  66.    Write-Output " +==========================================================+"
  67.    Write-Output ""
  68. }
  69.  
  70. function Confirm-Continue {
  71.    Write-Output " Press 'Y' key to continue or 'N' to exit."
  72.    Write-Output ""
  73.    Write-Output " -Continue? (Y/N)"
  74.    do {
  75.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  76.        $char = $key.Character.ToString().ToUpper()
  77.        if ($char -ne "Y" -and $char -ne "N") {
  78.            [console]::beep(1500, 500)
  79.        }
  80.    } while ($char -ne "Y" -and $char -ne "N")
  81.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  82. }
  83.  
  84. function Truncate-LogFiles {
  85.  
  86.    Write-Output "Fetching log files in ""$($PWD)"", please wait..."
  87.    Write-Output ""
  88.    $logFiles = Get-ChildItem -Path $PWD -File -Filter "*.log" -Recurse -Force -ErrorAction SilentlyContinue
  89.    if (-not $logFiles) {
  90.        Write-Warning "No log files found in directory: $($PWD)"
  91.        Return
  92.    }
  93.    Clear-Host
  94.  
  95.    foreach ($logFile in $logFiles) {
  96.  
  97.         if ($logFile.Length -eq 0) {
  98.            Continue
  99.        }
  100.  
  101.        $formattedFileSize = [FileUtils]::FormatFileSize($logFile.Length)
  102.        Write-Output "Truncating file: $($LogFile.FullName) ($($formattedFileSize)) ..."
  103.  
  104.        try {
  105.            # [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($logFile.FullName, [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs, [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)
  106.            $fs = [System.IO.File]::OpenWrite($logFile.FullName)
  107.            $fs.SetLength(0)
  108.            $fs.Close()
  109.        }
  110.        catch {
  111.            Write-Host "Access denied to file, it may be in use." -ForegroundColor Yellow
  112.        }
  113.        Start-Sleep -MilliSeconds 50
  114.    }
  115.  
  116. }
  117.  
  118. function Show-GoodbyeScreen {
  119.    Write-Output ""
  120.    Write-Host "Operation Completed." -BackgroundColor Black -ForegroundColor Green
  121.    Write-Output ""
  122.    Write-Output "Press any key to exit..."
  123.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  124.    Exit(0)
  125. }
  126.  
  127. <#
  128. ===========================================================================================
  129. |                                                                                         |
  130. |                                         Main                                            |
  131. |                                                                                         |
  132. ===========================================================================================
  133. #>
  134.  
  135. [System.Console]::Title = "Truncate Log Files - by Elektro"
  136. [CultureInfo]::CurrentUICulture = "en-US"
  137.  
  138. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  139.  
  140. Show-WelcomeScreen
  141. Confirm-Continue
  142. Truncate-LogFiles
  143. Show-GoodbyeScreen


« Última modificación: 3 Marzo 2024, 22:16 pm por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines