如何编写一个 powershell 函数来在文件不存在时发送警告?

问题描述 投票:0回答:1

我是 powershell 脚本编写的新手,我正在尝试创建一个函数,如果我的 C: 驱动器文件夹中不存在文件列表,该函数会向我的电子邮件发送警告。我正在寻找的文件列表是:

file1pop_*.txt

交易_*.txt

卡_*.txt

账户_*.txt

我知道要创建一个函数,我这样写

function File-Warnings

对于这个特定场景,我是否使用

WarningAction

powershell
1个回答
0
投票

这就是您需要的功能:

function Send-FileWarnings {
    param (
        [string]$FolderPath,
        [string]$SmtpServer,
        [string]$From,
        [string]$To,
        [string]$Subject
    )
    $filesList = @("file1pop_*.txt", "transaction_*.txt", "card_*.txt", "account_*.txt")
    $missingFiles = @()
    foreach ($pattern in $filesList) {
        $files = Get-ChildItem -Path $FolderPath -Filter $pattern -ErrorAction SilentlyContinue
        if ($files.Count -eq 0) {
            $missingFiles += "No files found matching pattern: $pattern"
        }
    }
    if ($missingFiles.Count -gt 0) {
        $body = "WARNING: The following file patterns are missing in folder $FolderPath :`n`n" + ($missingFiles -join "`n")
        Send-MailMessage -SmtpServer $SmtpServer -From $From -To $To -Subject $Subject -Body $body
    }
}

使用示例:

Send-FileWarnings -FolderPath "C:\Folder" -SmtpServer "smtpserver" -From "[email protected]" -To "[email protected]" -Subject "File Alert"

使用的 cmdlet 信息:

问候!

© www.soinside.com 2019 - 2024. All rights reserved.