You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写PowerShell函数实现文件不存在时发送邮件告警?

关于PowerShell File-Warnings函数是否使用WarningAction的解答

结论:完全不需要用WarningAction

WarningAction是PowerShell用来控制内置警告行为的参数(比如抑制Write-Warning的输出、将警告转为错误等),但你的需求是当特定文件缺失时主动发送邮件告警——这属于自定义业务告警逻辑,和PowerShell原生的警告机制无关,完全不需要依赖WarningAction来实现。

实现File-Warnings函数的示例代码

下面是符合你需求的完整函数,注释清晰,直接可用:

function File-Warnings {
    [CmdletBinding()]
    param(
        # 必填:接收告警的邮箱地址
        [Parameter(Mandatory=$true)]
        [string]$AlertEmail,
        # 可选:要检查的C盘文件夹路径,默认C盘根目录,可自行修改
        [string]$TargetPath = "C:\"
    )

    # 定义需要检查的文件通配符列表
    $requiredFilePatterns = @(
        "file1pop_*.txt",
        "transaction_*.txt",
        "card_*.txt",
        "account_*.txt"
    )

    # 存储缺失的文件模式
    $missingPatterns = @()

    # 逐个检查文件是否存在
    foreach ($pattern in $requiredFilePatterns) {
        # 查找匹配的文件,静默处理路径不存在的错误
        $foundFiles = Get-ChildItem -Path $TargetPath -Filter $pattern -ErrorAction SilentlyContinue
        if (-not $foundFiles) {
            $missingPatterns += $pattern
        }
    }

    # 若有缺失文件,发送邮件告警
    if ($missingPatterns.Count -gt 0) {
        $emailSubject = "【文件缺失告警】C盘目标文件夹缺少指定文件"
        $emailBody = @"
以下文件模式未找到匹配文件:

$($missingPatterns -join "`n")

检查路径:$TargetPath
"@
        
        # 发送邮件,需替换为你的SMTP服务器信息
        Send-MailMessage -From "alert-sender@yourdomain.com" -To $AlertEmail `
                        -Subject $emailSubject -Body $emailBody `
                        -SmtpServer "smtp.yourdomain.com" -Port 587 -UseSsl
    }
}

补充说明

  • 关于-ErrorAction SilentlyContinue:用来抑制当TargetPath不存在时的错误输出,你可以根据需求调整为Stop(让脚本直接终止报错)或其他值。
  • SMTP配置:Send-MailMessage需要正确的SMTP服务器信息,比如企业邮箱的SMTP地址、端口(通常587),如果是个人邮箱(如QQ、163),需要开启SMTP服务并使用授权码作为密码。
  • 若需同时在控制台输出警告:可以在$missingPatterns += $pattern后添加Write-Warning "未找到匹配文件:$pattern",但这时候也不需要用WarningAction,除非你要控制这个警告的显示行为(比如禁止输出)——但你的核心需求是邮件告警,这部分属于可选的控制台提示。

内容的提问来源于stack exchange,提问作者Forgottenluv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:42:42