创建定时任务和PowerShell脚本释放磁盘空间

背景介绍

此文档探索基于Windows系统自带的任务计划程序(Task Scheduler)和PowerShell脚本,实现定期删除临时文件的方案。此外,也可以借助其它三方工具(如AutoDelete),实现临时文件删除。

任务目标

  1. 实现定时检查和删除指定位置文件
  2. 提供删除记录供查看和统计
  3. 熟悉定时任务创建和配置
  4. 熟悉PowerShell基本用法

目标文件

  • 脚本文件:clean_junk_files.ps1
  • 日志文件:clean_junk_files.log
  • 配置文件:clean_junk_files.xml

参考文件结构

PS C:\Scripts> tree . /F
Folder PATH listing for volume Windows
C:\SCRIPTS
│  clean_junk_files.log
│  clean_junk_files.ps1
│  clean_junk_files.xml
│
└─tmp
    │  afasefea.pdf
    │  logs.txt
    │
    ├─tmp2
    │      logs.txt
    │      ooa9afry.zip
    │
    └─tmp3
            logs.txt
            sd3929df.pdf

脚本测试

基于上述文件结构,运行文件脚本clean_junk_files.ps1

powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -File "C:\Scripts\clean_junk_files.ps1"

应删除在脚本clean_junk_files.ps1中配置的JUNK_FOLDERS目录下DAYS_BEFORE天以前的文件,

Set-Variable -Option ReadOnly -Name "JUNK_FOLDERS" -Value "C:\Scripts\tmp", "C:\Scripts\tmp2"
Set-Variable -Option ReadOnly -Name "DAYS_BEFORE" -Value 1 

并在对应的日志文件clean_junk_files.log中应生成如下日志信息

......
2024-05-17 14:44:24 >>> space available: 353.8GB, total: 475.7GB, per: 74.4%
2024-05-17 14:44:24 removed 3 files 1 days before, freed 201208815 bytes
2024-05-17 14:44:24 <<< space available: 353.8GB, total: 475.7GB, per: 74.4%
......

脚本内容见附录部分

设置计划任务

ChatGPT Prompt: How to schedule to execute a PowerShell script task on Windows Server 2019

通过在任务计划程序(Task Scheduler)中设置定时任务运行指定PowerShell脚本,实现定时检查和删除临时文件的目标。任务计划可手动设置,也可以从配置文件导入。

任务配置文件示例:clean_junk_files.xml

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2024-05-16T11:00:48.7215048</Date>
    <Author>lingxuxiong@foxmail.com</Author>
    <URI>\CloudPrint\FileConvert\Clean Junk Files</URI>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <Repetition>
        <Interval>PT1M</Interval>
        <Duration>P3D</Duration>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2024-05-16T11:00:13</StartBoundary>
      <Enabled>true</Enabled>
    </TimeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-21-3764732182-236826484-1307600189-1001</UserId>
      <LogonType>S4U</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>true</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>powershell.exe</Command>
      <Arguments>-WindowStyle Hidden -ExecutionPolicy Bypass -File "C:\Scripts\clean_junk_files.ps1"</Arguments>
    </Exec>
  </Actions>
</Task>

附录

脚本文件:C:\Scripts\clean_junk_files.ps1

 <#
.SYNOPSIS
    Returns summary of current disk usage.

.DESCRIPTION
    This function returns the general usage information regarding the specified disk,
    in terms of free space, total space, and available space in percentage.

.PARAMETER DeviceID
    The device ID to be used as a filter, defaults to the home drive.

.EXAMPLE
    PS> Get_Disk_Storage_Info
    Call with default parameter, returns something like "free: 353.9GB, total: 475.7GB, per: 74.4%"

.EXAMPLE
    PS> Get_Disk_Storage_Info -DeviceID "C:"
    Call with explicit value of the DeviceID parameter.

.NOTES
    The value of DeviceID parameter should be postfixed with ":", 
    so "C:" is correct whereas "C" is not as expected.

.LINK
#>
function Get_Disk_Storage_Info {
    param (
        [string] $DeviceID = "$($env:HomeDrive)"
    )

    $disk = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='$DeviceID'"
    $freeSizeGB = [math]::Round(($disk.FreeSpace / 1GB), 1)
    $totalSizeGB = [math]::Round(($disk.Size / 1GB), 1)
    $freeSizePercent = [math]::Round(($freeSizeGB / $totalSizeGB) * 100, 1)

    return "free: $($freeSizeGB)GB, total: $($totalSizeGB)GB, per: $($freeSizePercent)%"
}

<#
.SYNOPSIS
    Returns formatted timestamp.
#>
function Get_Formatted_DateTime {
    return (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
}

<#
.SYNOPSIS
    Append message, prefixed with timestamp, to log file.

.PARAMETER LogFilePath
    The full path of the target log file, defaults to cleanup.log which locates in
    the same folder as the script being executed.

.PARAMETER Message
    The message to be written to the target log file.

.EXAMPLE
    PS> Dump_Log_Message -Message "new log message"
    Dump the specified log message to the default log file.

.EXAMPLE
    PS> Dump_Log_Message -LogFilePath "$($env:HomeDrive)$($env:HomePath)\cleanup.log" -Message "new log message"
    Dump the specified log message to specified log file.

.NOTES
    Note that the script might not have permission to get access to the target log file, 
    so be sure to choose the write file location where write permission is granted.    
#>

function Dump_Log_Message {
    param (
        [string] $LogFilePath = "$PSScriptRoot\cleanup.log",
        [string] $Message               
    )

    "$(Get_Formatted_DateTime) $Message" | Out-File $LogFilePath -Append #-NoNewLine
}


# Specify the target folder in which the old files locate
#$FOLDER_PATH = "C:\Scripts\tmp"
Set-Variable -Option ReadOnly -Name "FOLDER_PATH" -Value "C:\Scripts\tmp" 

# Delete files older than this days
Set-Variable -Option ReadOnly -Name "DAYS_OLD" -Value 1
#$DAYS_OLD = 1

# Get the list of files in the folder
$fileList = Get-ChildItem -Path $FOLDER_PATH -File

# Enumerate files older than the config
$oldFiles = Get-ChildItem -Path $FOLDER_PATH | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$DAYS_OLD) }

# Log disk info before clean up
Dump_Log_Message -Message ">>> $(Get_Disk_Storage_Info)"

# Iterate through each file and sum up their sizes
$totalSize = 0
$totalCount = 0
foreach ($file in $oldFiles) {
    $totalCount += 1
    $totalSize += $file.Length
    Remove-Item -Force -Path $file.FullName
}

# dump statistics for this clean up
# $logMessage = "Removed $($totalCount) files older than $($DAYS_OLD) days, $($totalSize) bytes in total" 
# $logMessage | Out-File $logFilePath -Append
Dump_Log_Message -Message "Removed $($totalCount) files older than $($DAYS_OLD) days, $($totalSize) bytes in total" 

# Log disk info after clean up
Dump_Log_Message -Message "<<< $(Get_Disk_Storage_Info)" 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,392评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,258评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,417评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,992评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,930评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,199评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,652评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,327评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,463评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,382评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,432评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,118评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,704评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,787评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,999评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,476评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,057评论 2 341

推荐阅读更多精彩内容