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
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
Copy File from the Script Folder to Local Folder
Register the Task Scheduler
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: