我有一项任务是监控某些文件夹中是否存在文件超过5分钟。如果文件存在时间超过5分钟,我需要脚本才能发送电子邮件。现在脚本将运行并通过电子邮件发送给我,但是我无法正确地输出格式。
我希望电子邮件中包含CSV,公司的第一列,get-childitem的路径和输出。我将删除写主机,因为脚本将通过计划任务运行。 CSV具有以下格式..
\\some\share
\\some\share2
\\some\share3
虽然我想把它作为......
Company1,\\some\share
Company2,\\some\share2
Company3,\\some\share3
这样我就可以在电子邮件中加入第一个标题
到目前为止,我的代码是什么。
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$SmtpClient.Host = "smtp.some.address"
$MailMessage.from = ($ServerName + "@someaddress.com")
$MailMessage.To.add("me@someaddress.com")
$MailMessage.Subject = "File Monitor"
$date = (get-date).AddMinutes(-5)
foreach($path in get-content "C:\Scripts\servers_path.txt") {
if ((Test-Path -path $path)) {
$item = get-childitem $path *.* | where-object {$_.LastWriteTime -lt $date}
$item | Select FullName, Name, LastWriteTime
if ($item) {
$MailMessage.Body += "$path `n"
$MailMessage.Body += "$item `n`n"
$MailMessage.Body += "---------------------------------------------------------------------------------------------------------`n"
}
}
elseif (!(Test-Path $path)) {
Write-Host "The folder," $path "does not exist" -fore red
}
}
$SmtpClient.Send($MailMessage)
谢谢
答案 0 :(得分:0)
我认为最初我把你的输入混淆为问题中的输出。那么这样的事呢?假设"c:\temp\data.txt"
中包含以下输入数据。
Company1,\\some\share
Company2,\\some\share2
Company3,\\some\share3
阅读代码中的注释,以了解正在发生的事情。此代码将代替您理论上已有的ForEach
循环。您需要使用输出来获得所需的结果。如果我不在基地,请尽可能详细。
$date = (get-date).AddMinutes(-5)
# Import the data as a csv into PowerShell specifying the headers since they dont exist.
Import-csv -Path "c:\temp\data.txt" -Header "Company","Path" | ForEach-Object{
# Check if the path is valid for this item.
If(Test-Path $_.Path){
# This folder exists. Check the contents for certain files.
$data = Get-ChildItem $_.Path | Where-Object {$_.LastWriteTime -lt $date}
If($data){
# Output the company name and path on a separate line.
$message = "`r`n$($_.Company)`r`n$($_.Path)`r`n"
# Output each file on its own line.
$message += "$(($data | Select-Object -ExpandProperty Name) -Join "`r`n")"
# Append built string to the body of the email.
$MailMessage.Body += $message
}
} Else {
# Path does not exist. Have message stating such.
$MailMessage.Body += "`r`n$($_.Company)`r`n$($_.Path) does not exist `r`n"
}
}
如果您想要返回更多属性,例如LastWriteTime
,如果我们替换这一行,我们可以这样做
$message += "$(($data | Select-Object -ExpandProperty Name) -Join "`r`n")"
有这样的事情:
$data | ForEach-Object{
$message += "Name: '{0}' - Last Write Time: '{1}'" -f $_.Name, $_.LastWriteTime
}