[英]Powershell script to FTP files to a remote windows server
我一直在努力讓一個腳本可以工作,該腳本可以將文件通過 FTP 傳輸到遠程 Windows 服務器,我想看看我是否能得到一些幫助。 我在 StackOverflow 和 Google 上搜索了多個頁面,但到目前為止都沒有成功。下面是我的代碼
邏輯如下:
我嘗試將文件通過 FTP 傳輸到服務器的代碼似乎失敗了 - $webclient.UploadFile($uri,$latestfile)
得到這個異常:
使用“2”個參數調用“UploadFile”的異常:“WebClient 請求期間發生異常。” 在 C:\\Downloads\\powershell\\testmove3.ps1:22 char:26 + $webclient.UploadFile <<<< ($uri,$latestfile) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException +fullyQualifiedErrorId : DotNetMethodException
$source = "C:\downloads\"
$destination = "C:\dest\"
Get-ChildItem -Path C:\downloads | Where-Object { $_.name -like "TEST.CSV-PlainText*.txt" }
$latestfile=gci -path $source | Where-Object { $_.name -like "TEST.CSV-PlainText*.txt"} | sort FirstWriteTime | select -last 1
"Oldest File $latestfile"
## Get ftp object
$ftp_client = New-Object System.Net.WebClient
$user="someuser"
$pass="somepass"
$ftp_address = "ftp://ftp.testserver.com"
## Make uploads
$uri = New-Object System.Uri($ftp+$item.Name)
"Item is $latestfile"
$webclient.UploadFile($uri,$latestfile)
"File uploaded to remote servr"
Move-Item $latestfile.FullName $destination
"File $latestfile moved"
好的,一夜之間,很高興地報告我得到了一個解決方案 - yeeehaw !
我什至添加了一個邏輯來捕獲異常並發送電子郵件通知。 希望這可以幫助任何使用 Powershell 解決 FTP 問題的人。 最后,它向調用程序返回成功或失敗代碼。
#PowerShell.exe -File "C:\temp\FTP.ps1"
trap [Exception] {
$recipient = "recipient@yahoo.com"
$sender = "sender@yahoo.com"
$server = "test.mailserver.com"
$subject = "FTP Test"
$body = "Exception Title: " + $_.Exception.GetType().FullName + "`r`n`r`n" + "Exception Details: " + $_.Exception.Message
$msg = new-object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$client.Send($msg)
exit 1
}
$ftpuser = "testuser"
$ftppass = "testpass"
$ftpserver = "ftp://ftp.testserver.com/"
$file = "C:\temp\one.txt"
$filenewname = "one.txt"
$webclient = New-Object System.Net.WebClient
$ftp = $ftpserver+$filenewname
$uri = New-Object System.Uri($ftp)
#Error was happening because the method call was attempting to use the HttpProxy on the Server machine.
#If the proxy is not set to null explicitly in your code, then you will get error - "An exception occurred during a webclient request"
$webclient.Proxy = $NULL
$webclient.Credentials = New-Object System.Net.NetworkCredential($ftpuser,$ftppass)
"Uploading $filenewname in $ftpserver"
$webclient.UploadFile($uri,$file)
"Uploaded $filenewname in $ftpserver"
return 0
如果要在任何實時支持環境中使用它,我建議使用密碼提示:
$ftppass = Read-Host "Enter password" -AsSecureString
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.