powershell - Powershell脚本到电子邮件的最新修改日期

标签 powershell powershell-2.0 powershell-3.0

我目前是一名系统管理员,试图使用Powershell脚本将文件夹的上次修改日期与今天的日期进行比较,以查看备份是否已超过7天。如果是,那么它将向我们的公司帐户发送一封电子邮件,提醒我们。

电子邮件部分工作正常,但问题是将每个人的备份文件夹(在NAS上)排列在阵列中,并被称为要检查。到目前为止的代码是这样的:

$paths = ($backup1 = "Y:\DESKTOP-OQRSLAU\Backup Set*"),
     ($backup2 = "V:\DESKTOP-I6B29SG\Backup Set*")

$lastWrite = (get-item $paths).LastWriteTime

foreach($backup in $paths){
if ($lastWrite -ge (get-date).AddDays(-7).ToString("yyyy-MM-dd")){
Write-Output "Success!"
$message = new-object Net.Mail.MailMessage;
    $message.From = $email_from_address;
    foreach ($to in $email_to_addressArray) {
        $message.To.Add($to);
    }
    $message.Subject =  ("BACKUP WARNING: " + "Out of Date Backup");
    $message.Body =     "`r`n`r`n";
    $message.Body +=    " ";
    $message.Body +=    " ";
    $message.Body +=    ("The following machines backup is out of date:     " + $env:computername + "`r`n");
    $message.Body +=    "`r`n";
    $message.Body +=    "`r`n";
    $message.Body +=    ("The latest backup for this machine is:   " + $lastWrite + "`r`n");
    $message.Body +=    "`r`n";
    $message.Body +=    "`r`n";
    $message.Body +=    ("***This warning will fire when a backup is older than seven days***");
            $message.Body +=        ""

    $smtp = new-object Net.Mail.SmtpClient($email_smtp_host, $email_smtp_port);
    $smtp.EnableSSL = $email_smtp_SSL;
    $smtp.Credentials = New-Object System.Net.NetworkCredential($email_username, $email_password);
    $smtp.send($message);
    $message.Dispose();
    write-host "... E-Mail sent!" ; 
} 
else {
exit
}
}

我现在作为电子邮件收到的回复仅适用于上面列出的第一个路径(Y:驱动器)。知道我在做什么错吗?我对Powershell不太了解。提前致谢!

最佳答案

您需要在循环的路径中获取LastWriteTime。我还建议您以更标准的数组格式设置$ Paths。

$paths = @("Y:\DESKTOP-OQRSLAU\Backup Set*","V:\DESKTOP-I6B29SG\Backup Set*")
foreach ($backup in $paths) {
  $lastWrite = (get-item $backup).LastWriteTime
  if ($lastWrite -ge (get-date).AddDays(-7).ToString("yyyy-MM-dd")) {
    # Do Stuff...
  }
  else {
    # Some other action NOT exit!
  }
}

关于powershell - Powershell脚本到电子邮件的最新修改日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100008/

相关文章:

powershell - Powershell和Plink-如何捕获消息 “Access Denied”

powershell - 在 Powershell 中设置像 yyyy-mm-dd 这样的默认日期格式?

PowerShell 多个动态参数

powershell - 使用 powershell 安装多个应用程序

powershell - 为什么以及何时使用 32 位或 64 位 PowerShell 或 ISE?

windows - powershell 传递命令行参数

powershell - 使用PowerShell如何拆分选定属性的字符串

regex - 将长正则表达式拆分为多行?

windows - lastLogonTimeStamp 属性的 1601/01/01

powershell - bash 上相当于 `which` 的 cmd/powershell 是什么?