0

我是 Powershell 的新手,无法将我拥有的两个脚本连接在一起。我想要做的是检查特定文件夹中所有 csv 文件的长度,如果其中任何一个是 0 Kb,我想发送一封警报电子邮件。到目前为止,我有一个成功发送电子邮件的脚本,并且我有一个成功检查大小的脚本,但是我无法将两者结合在一起。

理想情况下,它将发送电子邮件正文中为空的文件的名称。

下面的代码检查文件大小,如果大于 1Kb,则返回 true。

    $file = 'FilePath\File1.csv'
    $Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }

    if ($Result -eq "True") {"File1.csv Contains Data"} ELSE {"File1.csv is      Empty!"}

    $file = 'FilePath\File2.csv'
    $Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }

    if ($Result -eq "True") {"File2.csv Contains Data"} ELSE {"File2.csv is  Empty!"}

    $file = 'FilePath\File3.csv'
    $Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }

    if ($Result -eq "True") {"File3.csv Contains Data"} ELSE   {"File3.csv is Empty!"}

    $file = 'FilePath\File4.csv'
    $Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }

    if ($Result -eq "True") {"File4.csv Contains Data"} ELSE {"File4.csv is Empty!"}

    $file = 'FilePath\FileName5.csv'
    $Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }

    if ($Result -eq "True") {"File5.csv Contains Data"} ELSE {"File5.csv is Empty!"}

    $file = 'FilePath\FileName6.csv'
    $Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }

    if ($Result -eq "True") {"File6.csv Contains Data"} ELSE {"File6.csv is Empty!"}

下面是邮件部分

    $subject = "Emailtest"
    $body =  "test"
    $emailTo = "jbloggs@Madeup.com"
    $emailFrom ="JohnSmith@123.com"
    $smtpServer = “mail.madeup.com”
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $credentials=new-object system.net.networkcredential(”username”,”password”)
    $smtp.credentials=$credentials.getcredential($smtpserver,"25","basic")
    $smtp.Send($emailFrom, $emailTo, $subject, $body)

感谢您的任何帮助。

4

1 回答 1

1

仅仅为了检查空文件就需要做大量的(手动)工作。当您添加第七个时会发生什么 - 您必须编辑脚本吗?

$EmptyFiles = (Get-childItem -Path $FilePath -Filter *.csv | `
    where-object {$_.length -eq 0}|select-object -expandproperty Name)

$MsgBody = "The following files are empty:";
$EmptyFiles | foreach{$MsgBody+="`n$_";};

$MsgBody; # Just to output to console

$secpasswd = ConvertTo-SecureString "password" -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
$subject = "Emailtest"
$body =  "test"
$emailTo = "jbloggs@Madeup.com"
$emailFrom ="JohnSmith@123.com"
$smtpServer = “mail.madeup.com”
send-mailmessage -smtpserver $smtpServer -subject $subject -to $emailto -Credential $credentials -body $MsgBody
于 2013-11-14T17:43:21.233 回答