如何在失败或成功连接到sftp时使用powershell电子邮件

时间:2017-05-03 06:16:22

标签: powershell

下面是一个脚本(来自winscp)的修改示例,该脚本连接到远程sftp站点并将最新文件下载到我的本地服务器之一。

如果无法连接到SFTP或无法找到文件,我希望此脚本通过电子邮件发送给我们的发行版。这有可能吗?我们正在运行Office 365,但也有本地SMTP服务器。

param (
    $localPath = "\\70.70.49.20\d$\Reports\GILL",
    $remotePath = "/home/temp/"
)

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Temp\WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "73.89.10.17"
        UserName = "Username"
        Password = "Password"
        SshHostKeyFingerprint = "ssh-rsa 2048 5d:cd:8d:d9:df:d3:db:dd:ed:fd:8d:ed:cd:d2:fd:9d"
    }

    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.Open($sessionOptions)

        # Get list of files in the directory
        $directoryInfo = $session.ListDirectory($remotePath)

        # Select the most recent file
        $latest =
            $directoryInfo.Files |
            Where-Object { -Not $_.IsDirectory } |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1

        # Any file at all?
        if ($latest -eq $Null)
        {
            Write-Host "No file found"
            exit 1
        }

        # Select latest folder in localpath
        $folder = Get-ChildItem '\\70.70.49.20\d$\Reports\GILL' | ?{ $_.PSIsContainer } | sort CreationTime -Descending | select -First 1

        # Download the selected file
        $session.GetFiles($session.EscapeFileMask($remotePath + $latest.Name), $localPath + $folder.Name + "\Spots\").Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}

2 个答案:

答案 0 :(得分:0)

将代码放在try之前的某个位置,只需调用try中的函数并捕获不同的消息:

$Username = "MyUserName";
$Password= "MyPassword";

function Send-ToEmail([string]$email, [string]$attachmentpath){

    $message = new-object Net.Mail.MailMessage;
    $message.From = "YourName@gmail.com";
    $message.To.Add($email);
    $message.Subject = "subject text here...";
    $message.Body = "body text here...";
    $attachment = New-Object Net.Mail.Attachment($attachmentpath);
    $message.Attachments.Add($attachment);

    $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "587");
    $smtp.EnableSSL = $true;
    $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
    $smtp.send($message);
    write-host "Mail Sent" ; 
    $attachment.Dispose();
}

Send-ToEmail  -email "reciever@gmail.com" -attachmentpath $path;

答案 1 :(得分:0)

添加catch块

Send-MailMessage -To 'DL@MyDomain.com' -From 'SFTConnector@MyDomain.com' -Subject 'SFTP connection failed' -SmtpServer mail.mydomain.com

您可以根据需要进行配置。阅读更多MSDN

另一个问题/建议。我会尽量避免嵌套的try / catch / finally块。尝试构建脚本逻辑以避免它并且一个接一个地放入,而不是一个在另一个内部。