根据if语句更改电子邮件的$ smtpTo

时间:2016-05-23 19:58:10

标签: powershell powershell-v2.0

在我的注册事件操作中,我有一个if语句,用于检查路径是否匹配,如果他们这样做,我将电子邮件设置为$smtpTo到正确的电子邮件地址。但是我得到一个错误"The parameter 'to' cannot be an empty string.我知道路径是正确的,因为他们在if语句中写入控制台。

$MonitorFolder = Get-Content "C:\Desktop\ScanFTPDeptClients\OutgoingPathlist.txt"
$MonitorStopFile = "monitor.die"

$smtpServer = "mail.test.org"
$smtpFrom = "SYSTEMFUNCTION@test.org" 
$smtpSubject = "Completed files have arrived in FTP"
$smtpTo= ""
$SourceID = "MonitorFiles"


foreach ($path in $MonitorFolder){

    $i+=1
    $watcher = New-Object System.IO.FileSystemWatcher $path
    #Files only. Default is files + directory
    $watcher.NotifyFilter = [System.IO.NotifyFilters]'FileName,LastWrite'

    #Using a thread-safe collection (in global scope so Action-block can reach it) to store the log just to be safe.
    $global:newFiles = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))

    $newFileSubscription = Register-ObjectEvent $watcher Created -SourceIdentifier $i+"NewFileCreated" -Action {
        Write-Host "New file named '$($Event.SourceEventArgs.Name)' arrived in $(split-path $Event.SourceEventArgs.FullPath)"

        #Check the path
        $deptClient= "$(split-path $Event.SourceEventArgs.FullPath)"

        #set the email based on folder path
        if ("$($deptClient)" -eq "\\vavm\FTP\C\O\RuthWebster"){
            Write-host "$($deptClient)"
            $smtpTo = "test@test.org"
        }

        #add files to content of body email
        $global:newFiles.Add("`n[$(Get-Date -Format HH:mm:ss)]`t $($Event.SourceEventArgs.Name)has been completed and arrived in $(split-path $Event.SourceEventArgs.FullPath) ")

        if($Event.SourceEventArgs.Name -eq $MonitorStopFile) {
            Write-Host "Monitoring stopped"
            #Stop monitoring
            Unregister-Event -SubscriptionId $newFileSubscription.Id
            #Dispose FileSystemWatcher
            $watcher.Dispose()
        }
    }

}

$smtp = New-Object -TypeName "Net.Mail.SmtpClient" -ArgumentList $smtpServer

while ($watcher.EnableRaisingEvents -or $global:newFiles.Count -gt 0) {   

    #Sleep
    Start-Sleep -Seconds 10

    if($global:newFiles.Count -gt 0) {
        #Convert list of strings to single string (multiline)
        $smtpbody = $global:newFiles 

        $smtp.Send($smtpFrom, $smtpTo, $smtpSubject, $smtpBody) 

        #Mail sent, Empty array
        $global:newFiles.Clear()
    }

}

1 个答案:

答案 0 :(得分:2)

尝试使用$smtpTo作为全局变量。将所有$smtpTo替换为$global:smtpTo

顺便说一下。你不需要在字符串和子表达式中包含split-path。尝试:

$deptClient= split-path $Event.SourceEventArgs.FullPath

#set the email based on folder path
if ($deptClient -eq "\\vavm\FTP\C\O\RuthWebster"){
    Write-host $deptClient
    $smtpTo = "test@test.org"
}