Note: this article is published on 11/13/2024.
This series of articles are to discuss a task to remove IIS Log Files. We start from doing the task manually, then make automation, and the last deploy the automation to pipelines (different servers):
A - Introduction
In the previous articles, we have introduced the VB Script to remove the IIS Log Files, and to automate the script running through Windows Task Scheduler.
Now, we have a new requirement that using PowerShell Script to replace VBScript, while PowerShell Script is most popular script in automation field. This article will repeat the previous article with VBScript replaced by PowerShell Script. This article will have the same structure as previous one.
The content of this article will include
- A - Introduction
- B - Create the Script to Remove IIS Log Files
- C - Automate to trigger the Removing Script
- D - Automate the deployment of the Task
B - Create the Script to Remove IIS Log Files
The PowerShell script to remove IIS Log Files is
$logFolder = "D:\LOGS\IIS"
$iMaxAge = 14 #in days
$subFolders = Get-ChildItem -Path $logFolder -Recurse -Directory
foreach ($subFolder in $subFolders)
{
#Write-Host $subFolder
$targetDate = (Get-date).AddDays(-$iMaxAge)
#Write-Host $targetDate
#Remove Log Files outside of recent 14 days
Get-ChildItem -Path $subFolder -Recurse -File | Where-Object { $_.LastWriteTime -le $targetDate } | Remove-Item
}
Note:
- The PowerShell script is much more powerful than VBScript, Actually, it almost uses one line code to handle this task:
- Get-ChildItem -Path $subFolder -File
- Explanation: this code will get all files in one specific folder: $subFolder
- Get-ChildItem -Path $subFolder -File | Where-Object { $_.LastWriteTime -le $targetDate )
- Explanation: this will give the conditioins, here: the Last Write Time is less than a specific time
- Get-ChildItem -Path $subFolder -Recurse -File | Where-Object { $_.LastWriteTime -le $targetDate } | Remove-Item
- Explanation: Remove the files chosen
- Get-ChildItem -Path $subFolder -Recurse -File | Where-Object { $_.LastWriteTime -le $targetDate } | Remove-Item
- Explanation: Recursive for all sub Folders
- Useful info about PowerShell Script:
C - Automate to trigger the Removing Script
This part is similar to the VBScript with some minor differences. We have done this job in the second article
where we made a Task Scheduler: Delete Log Files
Actions:
where
- Program --- the executable file, PowerShell.exe
- C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
- Arguments --- the first argument is to enforce the ExecutionPolicy, the second one is the script we want to run
- -ExecutionPolicy bypass -file D:\LOGS\IIS\Log_File_Deletion.ps1
- Start in
Note:
For PowerShell Script, the start in location is important, otherwise it will cause errors such as
Similar issues:
Trigger
set as Daily running
PowerShell Script:
D - Automate the deployment of the Task
Now we try to automate the deployment process through pipeline by a PowerShell Script.
The following are the major related parts in the script:
Set username and password
Write-LogInfo "Setting DOTNETENVIRONMENT to $dotNetEnvironment"
[System.Environment]::SetEnvironmentVariable('DOTNETENVIRONMENT', $dotNetEnvironment, [System.EnvironmentVariableTarget]::Machine)
# get svc account to run the api
$key = "/CAHCO_CRMHPE/{0}/serviceAccount" -f $dotNetEnvironment
Write-LogInfo "Looking up credentials for $key"
$ssmParameterValue = Get-SSMParameter -Name $key -Region "us-west-2" -WithDecryption 1
$cred = $ssmParameterValue.Value | ConvertFrom-Json
$serviceAccount = New-Object PSObject
$serviceAccount | Add-Member NoteProperty Domain $cred.Domain
$serviceAccount | Add-Member NoteProperty Name $cred.Name
$serviceAccount | Add-Member NoteProperty Password $cred.Password
# Get $user and $password
$user = "{0}\{1}" -f $serviceAccount.Domain, $serviceAccount.Name
$password = $serviceAccount.password
#Write-LogInfo "Creating scheduled task to run $localDirectory\Log_File_Deletion.ps1"
# Add service account to local admin group
Copy File from the Script Folder to Local Folder
# Set the path to the scripts folder
$ScriptsPath = 'D:\Temp\cahco\CAHCO_CRMHPE\deploy\.codeshuttle\scripts\'
Write-Host "Set path to scripts folder: $ScriptsPath"
# copy the ps1 file from $ScriptsPath to the local folder: D:\LOGS\IIS
$localDirectory = 'D:\ScheduledTasks\IIS_Logs_Deletion'
if (!(Test-Path -Path $localDirectory -PathType Container)) {
New-Item -ItemType Directory -Path $localDirectory
Write-Host "Folder created: $localDirectory"
} else {
Write-Host "Folder already exists: $localDirectory"
}
Write-Host "Copy Log_File_Deletion.ps1 from $ScriptsPath to $localDirectory"
$copiedFile = $ScriptsPath + "Log_File_Deletion.ps1"
Copy-Item $copiedFile -Destination $localDirectory
Register the Task Scheduler
# Register a task to delete IIS Log Files
Write-LogInfo "Begin to Register the Task Scheduler."
# delete the scheduled task if it exists
$taskName = 'Delete Log Files'
if (Get-ScheduledTask -TaskName $taskName -ErrorAction 'SilentlyContinue' ) {
Unregister-ScheduledTask -TaskName $taskName -Confirm:$False
}
# create scheduled task to run the Log_File_Deletion.ps1 file
Write-LogInfo "Creating scheduled task to run $localDirectory\Log_File_Deletion.ps1"
$taskDescription = 'Delete IIS Log Files out of 14 days.'
$taskPath = Join-Path -Path $localDirectory -ChildPath 'Log_File_Deletion.ps1'
$PowerShell = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe '
$ExecutionPolicy = ' -ExecutionPolicy bypass'
$taskPath = $powerShell + $ExecutionPolicy + ' -file ' + $taskPath
$workingDirectory = 'D:\LOGS\IIS'
Write-LogInfo "taskPath is $taskPath"
$taskStartTime = '00:01'
$taskAction = New-ScheduledTaskAction -Execute $taskPath -WorkingDirectory $workingDirectory
$taskTrigger = New-ScheduledTaskTrigger -Daily -At $taskStartTime
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -RunOnlyIfNetworkAvailable -DontStopOnIdleEnd
Register-ScheduledTask -TaskName $taskName -Action $taskAction -Trigger $taskTrigger -RunLevel Highest -User $user -Password $password -Settings $settings -Description $taskDescription | out-null
Write-LogInfo "Register Delete IIS Log Files Task Scheduler Successfully."
where
- Register-ScheduledTask command will register the task scheduler
- New-ScheduledTaskAction command will set up the Task Scheduler structure
The output will be like this
References: