powershell - Powershell 脚本到电子邮件的最后修改日期
问题描述
我目前是一名系统管理员,试图使用 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!
}
}
推荐阅读
- c# - 在 Xamarin 中使用带有 SQLite 的类中的 CreateTable 时,有没有一种方法可以为该类中的表使用不同的名称?
- sql-server - 禁用 NT AUTHORITY 时登录到 SQL Server 单用户模式
- javascript - 在javascript中下载图像url数组
- python - 如何将 3D 网格绘制到深度图
- node.js - 电子不使用播放 mp3 音频文件
- service - “我们目前正在经历服务中断,目前无法提供配额信息。” 在 OAuth 同意屏幕中
- reactjs - 如何在反应中添加 target=_blank
- algorithm - 检查给定范围内的所有元素是否出现偶数次的查询
- php - 如何在不相互覆盖的情况下合并两个多维数组?
- python-3.x - Python 3 Confluent Kafka 在单个函数中运行生产者和消费者