可以记录已扫描文件并在下次运行时忽略它们的 Powershell 脚本? [英] Powershell script that can log already scanned files and ignore them on next run?

查看:69
本文介绍了可以记录已扫描文件并在下次运行时忽略它们的 Powershell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本,该脚本将递归扫描目录、带有.Error"扩展名的本地文件,然后通过电子邮件向一组人发送文件列表.我计划通过 Control-M 运行此脚本并让它每 20 分钟运行一次.我希望脚本记录自上次运行以来已扫描的文件,而不将它们包含在电子邮件中.我是一个 powershell 新手,所以我不知道如何做到这一点.以下是我必须扫描文件并发送电子邮件的代码的无菌版本.我会非常感谢任何人的帮助.

I am attempting to write a script that will recursively scan a directory, local files with the '.Error' extension, then email a group of people with a list of the files. I am planning on running this script through Control-M and have it run every 20 minutes. I would like for the script to log the files that have already been scanned since the last run and not include them in the email. I am very much a powershell novice so I am not sure how to do this. Below is a sterilized version of the code I have to scan the files and send the email. I would greatly appeciate anyones help.

function sendEmail {
    $SMTPServer = "relay.EXAMPLE.com"
    $SMTPFrom = "Test@EXAMPLE.com" 
    $EmailAddress = "user@EXAMPLE.com"
        send-mailmessage -to $EmailAddress -from $SMTPFrom -Subject "Error loading XPOLL File - $file" -body "This is the body" -smtpserver $SMTPServer 
}

##Search for .Error files
$array = @((Get-ChildItem -Path \\SERVER\FOLDER -Recurse -Include *.Error).Fullname)
foreach ($file in $array) {
    sendEmail
}
##

推荐答案

尝试将任务分解为简单的步骤:

Try breaking the task into simple steps:

  • 从文件中读取排除列表
  • 发现文件
  • 根据排除列表过滤文件
  • 发送电子邮件
  • 将新的排除列表附加到文件中
$exclusionFilePath = '.\path\to\exclusions\file.txt'
if(-not(Test-Path $exclusionFilePath)){
    # Create the exclusion file if it doesn't already exist
    New-Item $exclusionFilePath -ItemType File
}

# read list of exclusions from file
$exclusions = Get-Content -Path $exclusionFilePath

# discover files
$array = @((Get-ChildItem -Path \\SERVER\FOLDER -Recurse -Include *.Error).Fullname)

# filter current files against list of exclusions
$array = $array |Where-Object {$exclusions -notcontains $_}

foreach($file in $array){
  # send emails
  sendEmail

  # append new file path to exclusions file
  $file |Add-Content -Path $exclusionFilePath
}

<小时>

额外提示:参数化您的函数

依赖调用上下文中的变量有点反模式,我强烈建议将您的 sendEmail 函数重构为:

function Send-ErrorFileEmail {
    param(
        [string]$File
    )
    $MailMessageArgs = @{
        SMTPServer = "relay.EXAMPLE.com"
        From       = "Test@EXAMPLE.com" 
        To         = "user@EXAMPLE.com"
        Subject    = "Error loading XPOLL File - $file" 
        Body       = "This is the body" 
    }
    Send-MailMessage @MailMessageArgs
}

然后在脚本中使用它,如:

Then use it in the script like:

Send-ErrorFileEmail -File $file

这篇关于可以记录已扫描文件并在下次运行时忽略它们的 Powershell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆