以下は、リモートのsftpサイトに接続し、最新のファイルを自分のローカルサーバーの1つにダウンロードするスクリプト(winscpから)の変更例です。sftpへの接続失敗または成功時にpowershell電子メールを受け取る方法
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
}
メールをcatchブロックに送信するだけで、エラーが発生したときにトリガーするようにしてください。 – bluuf