运维小笔记:清理指定后缀名文件的 powerhsell 小脚本

简介: 在运维值班每天都需要从系统导出这种数据,压缩好放在工作电脑上,解压用脚本做汇总。但是长期都没删除各个日期下的压缩包。几年下来,有上千个目录,也不知道哪些目录中有没有删除的压缩包。一个一个手删太累了,不妨做个 powershell 小脚本一键搞定吧。

清理指定后缀名文件的 powerhsell 小脚本


jcLee95

已入驻阿里云博客

邮箱 :291148484@163.com
本文地址
- https://developer.aliyun.com/article/
- https://blog.csdn.net/qq_28550263/article/details/129121074

1.介绍

2.目录结构

3.主函数部分

4.正则匹配压缩文件后缀名 - 筛选压缩文件

5.由路径删除文件,失败时提示

6.完整 clear_zip_7Z.ps1 代码


1.介绍

在运维值班每天都需要从系统导出这种数据,压缩好放在工作电脑上,解压用脚本做汇总。但是长期都没删除各个日期下的压缩包。几年下来,有上千个目录,也不知道哪些目录中有没有删除的压缩包。一个一个手删太累了,不妨做个 powershell 小脚本一键搞定吧。

这个脚本同样适合于删除目录中其它后缀名的文件。

相关工具代码

后文用到了两个工具模块,这两个模块在我之前的两篇博客中有完整介绍和源代码:

2.目录结构

项目结构

日志结构

3.主函数部分

为了以后方便指定仅针对某个年份,或者修改为其它需要考虑年份的脚本,可以不要直接读取日志根目录中所有文件,而是逐个遍历所有年份下的文件夹:

function main($BASE_DIR) {
    $logger.Trace("Start compute...")
    $logger.Trace($BASE_DIR)
    $items = [Path]::get_items($BASE_DIR)
    foreach ($item in $items) {  
        Write-host -ForegroundColor 'Gray' "=========================================================================================================="
        # 对于目录
        $logger.Info("Current folder is: " + $item)
        if ([Path]::is_dirname($item)) {
            write-host -ForegroundColor 'DarkBlue' "=====> This is a folder!"
            foreach ($item in [Path]::get_descendants($item) ) {
                write-host -ForegroundColor 'DarkGreen' "=> This is a file!"$item
                if (IsArchiveFile($item)) {
                    write-host -ForegroundColor 'Yellow' " * This is a archive file, and it will be remove:"
                    write-host -ForegroundColor 'Green' "  "$item
                    deleteFileByPath($item)
                }
                else {
                    write-host -ForegroundColor 'Gray' " - But not a archive file"
                }
            }
            # 对于文件
        }
        elseif ([Path]::is_filename($item)) {
            write-host -ForegroundColor 'DarkGreen' "=> This is a file!"$item
            if (IsArchiveFile($item)) {
                write-host -ForegroundColor 'Yellow' " * This is a archive file, and it will be remove!"
                write-host -ForegroundColor 'Green' "  "$item
                deleteFileByPath($item)
            }
            else {
                write-host -ForegroundColor 'Gray' " - But not a archive file"
            }
        }
    }
}

4.正则匹配压缩文件后缀名 - 筛选压缩文件

function IsArchiveFile([string]$file_path) {
    $is7z = $file_path -match "\.7z$"
    $isZip = $file_path -match "\.zip$"
    $isTar = $file_path -match "\.tar$"
    $isWim = $file_path -match "\.wim$"
    $isAechiveFile = $is7z -or $isZip -or $isTar -or $isWim
    return $isAechiveFile
}

5.由路径删除文件,失败时提示

function deleteFileByPath([string]$file_path) {
    try{
        Remove-Item -Path $file_path
        write-host -ForegroundColor 'Blue' "Ok, this file has been removed!"
        return $True
    }catch{
        Write-Warning "An error occurred While delete file:"
        Write-Host $_
        return $False
    }
}

6.完整 clear_zip_7Z.ps1 代码

<#
@Author: Jack Lee;
@Email: 291148484@163.com;
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>
using module .\utils\jcpath.psm1
using module .\utils\jclogger.psm1
$PRODUCTION_BASE_DIR = [Path]::get_dirpath([Path]::get_dirpath($MyInvocation.MyCommand.source))
$logger = [Logger]::new([Path]::Join($PRODUCTION_BASE_DIR, 'logs'));
function IsArchiveFile([string]$file_path) {
    $is7z = $file_path -match "\.7z$"
    $isZip = $file_path -match "\.zip$"
    $isTar = $file_path -match "\.tar$"
    $isWim = $file_path -match "\.wim$"
    $isAechiveFile = $is7z -or $isZip -or $isTar -or $isWim
    return $isAechiveFile
}
function deleteFileByPath([string]$file_path) {
    try {
        Remove-Item -Path $file_path
        write-host -ForegroundColor 'Blue' "Ok, this file has been removed!"
        return $True
    }
    catch {
        Write-Warning "An error occurred While delete file:"
        Write-Host $_
        return $False
    }
}
function main($BASE_DIR) {
    $logger.Trace("Start compute...")
    $logger.Trace($BASE_DIR)
    $items = [Path]::get_items($BASE_DIR)
    foreach ($item in $items ) {  
        Write-host -ForegroundColor 'Gray' "=========================================================================================================="
        # 对于目录
        $logger.Info("Current folder is: " + $item)
        if ([Path]::is_dirname($item)) {
            write-host -ForegroundColor 'DarkBlue' "=====> This is a folder!"
            foreach ($item in [Path]::get_descendants($item) ) {
                write-host -ForegroundColor 'DarkGreen' "=> This is a file!"$item
                if (IsArchiveFile($item)) {
                    write-host -ForegroundColor 'Yellow' " * This is a archive file, and it will be remove:"
                    write-host -ForegroundColor 'Green' "  "$item
                    deleteFileByPath($item)
                }
                else {
                    write-host -ForegroundColor 'Gray' " - But not a archive file"
                }
            }
            # 对于文件
        }
        elseif ([Path]::is_filename($item)) {
            write-host -ForegroundColor 'DarkGreen' "=> This is a file!"$item
            if (IsArchiveFile($item)) {
                write-host -ForegroundColor 'Yellow' " * This is a archive file, and it will be remove!"
                write-host -ForegroundColor 'Green' "  "$item
                deleteFileByPath($item)
            }
            else {
                write-host -ForegroundColor 'Gray' " - But not a archive file"
            }
        }
    }
}
main($PRODUCTION_BASE_DIR)
相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
2月前
|
存储 运维 安全
2024.3.18隐语训练营第1讲笔记:数据可信流通,从运维信任到技术信任
数据二十条提出了要建立数据可信流通体系,使得数据可以安全的流转起来。但由于在数据流通中存在的各种风险,使得信任四要素全部遭到破坏,导致信任降级甚至崩塌。为了应对这些风险,要实现从运维信任到技术信任的转变,针对信任的各个要素,提出了解决方案。最后简要介绍了安全可信基础设施的融合布局。
46 3
|
4月前
|
缓存 网络协议 数据安全/隐私保护
[运维笔记] - (命令).Windows server常用网络相关命令总结
[运维笔记] - (命令).Windows server常用网络相关命令总结
200 0
|
2月前
|
运维 监控 Linux
linux脚本自动化运维任务
Linux自动化运维通过脚本提升效率,涵盖服务管理(启停服务、异常恢复)、系统监控(资源警报)、日志管理(清理分析)、备份恢复、补丁更新、自动化部署(如Ansible)、网络管理、定时任务(cron)和故障排查。结合shell、Python及工具,形成高效运维体系。
29 3
|
5月前
|
Linux Shell 索引
Python自动化脚本-运维人员宝典第一章 Python脚本概述
在学习本书前,你应该了解一些 Python 编程的基础知识,比如基础语法、变量类型、元组数据类型、列表字典、函数、字符串和方法。在python.org/downloads/上有3.7.2和2.7.15两个版本可供下载。本书中我们将使用3.7这一版本来作为代表示例和包的安装。
238 11
|
2月前
|
运维 安全 区块链
隐语训练营第1讲笔记:数据可信流通,从运维信任到技术信任
数据可信流通需要从运维信任转向技术信任,需要安全可信基础设施的融合布局。
42 1
|
2月前
|
存储 运维 安全
[隐私计算实训营笔记]第一课——数据可信流通,从运维信任到技术信任
本课以数据要素可信流通,重构技术信任体系为主题,介绍了信任四要素,以及其对应破环的原因,因此需要从运维信任走向技术信任的路线,并最终完成安全可信基础设施的融合布局。 感谢授课人韦韬老师~
|
2月前
|
运维 安全 数据安全/隐私保护
|
2月前
|
运维 NoSQL Linux
运维排错笔记
运维排错笔记
18 1
|
3月前
|
存储 运维 监控
「笔记」某移动 SRE 运维体系交流
「笔记」某移动 SRE 运维体系交流