Log file rotation is essential in enterprise environments. Log files naturally grow and increase with time, while disk space remains limited. Without centralized oversight, you might accumulate too much and run out of room for your other files. Automating the process ensures that your log files will be archived or deleted at regular intervals or if your disk usage moves past a certain threshold.
Guide to automating disk space rotation and log file rotation
Log rotation can be automated using Windows PowerShell. You can also use PowerShell to collect disk usage reports. To schedule tasks, you can use Command Prompt to run a PowerShell script at set intervals. For more complex scenarios, such as setting disk usage thresholds, you can use an RMM tool.
📌 Prerequisites:
- PowerShell 5.1 or higher is required.
- You will need full administrator privileges.
- You will need Registry access to track policy and application settings.
- You will need to schedule tasks locally or have an RMM integration to execute these scripts at regular intervals.
- You will need Group Policy access to apply log retention policies when applicable.
📌 Recommended deployment strategies:
Step 1: Identify and catalog key log file locations
Administrators can use Windows PowerShell to list the contents of commonly monitored log directories, such as:
- C:\Windows\System32\LogFiles
- C:\ProgramData\AppName\Logs\
- C:\Logs\CustomScripts\
- C:\inetpub\logs\LogFiles (IIS)
- AV, backup, and monitoring tools (e.g., SentinelOne, Veeam, NinjaOne)
To do that, follow these steps:
- Open the Start Menu and search for Windows PowerShell.
- Right-click Windows PowerShell > Run as administrator.
- Deploy the script that will create the logs. Here’s a sample PowerShell script for this:
$paths = @(
"C:\Windows\System32\LogFiles",
"C:\ProgramData\AppName\Logs",
"C:\Logs",
"C:\inetpub\logs\LogFiles"
)
foreach ($path in $paths) {
Get-ChildItem -Path $path -Recurse -Include *.log |
Select-Object FullName, Length, LastWriteTime
}
Modify the script according to your needs.
- Export the files into a CSV file to give you a baseline comparison.
Step 2: Automate log rotation based on age or size
You can rotate logs after a certain number of days. To do that, follow these steps:
- Open the Start Menu and search for Windows PowerShell.
- Right-click Windows PowerShell > Run as administrator.
- Type this script and press Enter:
$logPath = "C:\ProgramData\AppName\Logs"
$days = 30
Get-ChildItem -Path $logPath -Recurse -Filter *.log |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } |
ForEach-Object {
$archive = "$($_.FullName).bak"
Rename-Item -Path $_.FullName -NewName $archive
}
You can also compress the logs into a .zip file before they’re archived or delete them after they pass over a certain threshold.
To compress the files, deploy this script:
Compress-Archive -Path $archive -DestinationPath "$archive.zip"
Remove-Item -Path $archive
To delete the log files once they’ve passed a certain threshold, deploy this script:
Get-ChildItem -Path $logPath -Recurse -Filter *.log |
Where-Object { $_.Length -gt 100MB } |
Remove-Item -Force
Modify the file size threshold according to your needs and organization requirements.
Step 3: Use CMD and scheduled tasks for basic log cleanup
You can use Command Prompt to schedule a task that will regularly clean up your log files after a set time period. Open Command Prompt with elevated permissions and deploy the command. Here’s a sample command you can use:
To delete the logs:
forfiles /p "C:\Logs" /s /m *.log /d -30 /c "cmd /c del @path"
To schedule a task:
schtasks /create /tn "RotateLogs" /tr "powershell.exe -File C:\Scripts\RotateLogs.ps1" /sc weekly /ru SYSTEM
The above script will run a PowerShell file like this one at set intervals:
Get-ChildItem -Path $logPath -Recurse -Filter *.log |
Where-Object { $_.Length -gt 100MB } |
Remove-Item -Force
Modify the Command Prompt and PowerShell scripts per endpoint according to organization requirements and client policies.
Step 4: Collect disk usage reports via PowerShell
Tracking disk usage can help you track how many logs you have generated and if you need to start deleting or archiving them. To do this, follow these steps:
- Open the Start Menu and search for Windows PowerShell.
- Right-click Windows PowerShell > Run as administrator.
- Type this script and press Enter:
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{Name="Free(GB)";Expression={[math]::round($_.Free/1GB,2)}}, @{Name="Used(GB)";Expression={[math]::round(($_.Used)/1GB,2)}}
Detailed per folder:
Get-ChildItem "C:\" -Directory |
ForEach-Object {
$_.FullName
(Get-ChildItem $_.FullName -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB
}
- Export the reports.
Step 5: Track rotation status and free Space in the Registry
You can log the results of log cleanups in the Windows Registry and track their status using an endpoint management tool.
- Open the Start Menu and search for Windows PowerShell.
- Right-click Windows PowerShell > Run as administrator.
- Type this script and press Enter:
New-Item -Path "HKLM:\SOFTWARE\Org\LogRotation" -Force
Set-ItemProperty -Path "HKLM:\SOFTWARE\Org\LogRotation" -Name "LastRotation" -Value (Get-Date).ToString("u")
Set-ItemProperty -Path "HKLM:\SOFTWARE\Org\LogRotation" -Name "FreeSpaceGB" -Value 120
- To verify the data inside the Registry keys, open Command Prompt as an administrator.
- Type this command and press Enter:
reg query HKLM\SOFTWARE\Org\LogRotation
Step 6: Enforce log policy with GPO (where applicable)
- Open the Start Menu and search for Edit Group Policy to open the program.
- Navigate to this address: Computer Configuration > Administrative Templates > Windows Components > Event Log Service.
- Go to Application, Security, and System to configure the following policies:
- Specify the maximum log file size (KB) – This is where you can specify the maximum log size.
- Configure log access – This will define the security log access permission.
- Back up log automatically when full – This will define the log retention method (overwrite or archive).
⚠️ Troubleshooting/Things to look out for
| Issue/Risk | Potential Consequences | Fix/Reversal |
| You are experiencing permission errors. | You will not be able to rotate or delete log files. | Make sure that you are using elevated permissions when running these scripts. |
| The log files are locked. | You will not be able to rotate or delete log files. | Check handle.exe or Restart Service before rotating or deleting. Some applications may prevent you from modifying their log files. |
| The Registry updates are missing. | You will not be able to record data in the Windows Registry. | Make sure that the scripts ran successfully and that the paths were correct. |
| The scheduled tasks are not triggering. | You will not be able to rotate or delete log files. | Validate the Task Scheduler history or run policy status in Command Prompt using gpresult /h result.html. |
Additional considerations when automating log file rotation and disk space reporting
- Some applications write rotating logs automatically, while others have to be configured. Take this into account when configuring these settings.
- HIPAA and SOC 2 clients may require longer archive retention. In that situation, it’s recommended to rotate log files instead of deleting them.
- Monitor your drives closely. Set log cleanup triggers when it reaches 80%-90% usage.
- Use tools like NXLog or PowerShell to extract relevant events before rotation.
NinjaOne services for log rotation and disk space reporting
NinjaOne can help organizations manage their log files and disk space by:
| Function | Benefit | How It Makes the Process Easier |
| Deploy and schedule PowerShell scripts for log rotation. | This ensures consistent log maintenance across all devices. | It will automate repetitive tasks, removing the need for manual cleanup. |
| Tag devices based on free disk space, log count, and growth trends. | This identifies devices at risk before issues occur. | It provides clear visibility to prioritize attention where needed. |
| Alert administrators when cleanup fails or space is low. | This prevents downtime and performance issues. | It delivers proactive notifications so admins can act quickly. |
| Generate disk usage and log presence reports across tenants | This supports audits and quarterly reviews with accurate data. | It saves time by producing ready-to-use compliance and business reports. |
| Trigger conditional actions (cleanup, notifications) based on thresholds. | This keeps systems optimized and compliant. | It automates responses to issues without requiring manual intervention. |
Manage disk space by automating log file rotation in all your managed devices
Automating log file rotation and disk space monitoring is essential for scalable IT operations. It’s essential to have centralized oversight and ensure that your log files do not exceed certain disk usage thresholds. This allows you to manage your resources more efficiently and ensures that your organization is allocating disk space to what’s truly important.
Related Articles:
- How to Use a PowerShell Script to Generate NinjaOne Support Log Files
- How to Monitor Log Files and Detect Specific Text on Linux Using a Bash Script
- How to Read Windows Event Logs: Shutdown and Restart
- How to Check & Monitor Disk Space Remotely with PowerShell Script
- How to Use Disk Cleanup in Windows to Optimize Your System
