如何将请求文件上传到 FTP 服务器并等待从 FTP 服务器取回文件

How to upload a request file to FTP server and wait to get the file back from FTP server

我想连接 DTCC FTP 服务器以获取一些凭据文件。

程序只是创建请求文件,然后检索生成的数据。只需要一个脚本来完成这两件事。

$server="ftp 123.123.123.123"
$user="123456"
$passwd="123456"
$data_Password = "1234"
$RequestCode = "ABCD"
$locationCode= "ABCD"
$lastUsedSeqNum = "0560"



# Create file name for RequestFile
$scriptName = "FTX"+$user.Substring(0,4)+".P" + $user.Substring(5) + ".PB101" + $requestCode + "." + $locationCode + $lastUsedSeqNum 
$scriptPath = (Resolve-Path .\).Path

Write-Host "Current Path is: "$scriptPath
$ScriptName = $MyInvocation.MyCommand.Nameame
Write-Host "Current running script name is: "$scriptName
$ftpFile=$scriptPath + "$scriptName.I"


# Create RequestFile 
$line1 = " "+"PPASSWD0102"+ "              " +$user.Substring(0,4) +"-"+$user.Substring(5)+$data_Password + "  " +$RequestCode.Substring(0,4) +$((Get-Date).ToString('HHMM'))+$lastUsedSeqNum
$line2 = "TD" +$RequestCode +"01HDR"
# Create RequestFile  
Add-content $ftpFile  $line1
Add-content $ftpFile  $line2

我想用powershell来实现这个。以上是我目前正在处理的代码。这是创建一个请求文件。

有一件事是脚本名称不起作用....

我想把这个上传到服务器。然后等待 15 分钟,从 FTP 服务器下载文件。我对powershell真的很困惑...

总是感谢您的帮助!谢谢。

有一件事让我很困惑。您花了所有这些努力来构建文件名:

$scriptName = "FTX"+$user.Substring(0,4)+".P" + $user.Substring(5) + ".PB101" + $requestCode + "." + $locationCode + $lastUsedSeqNum 

然后立即尝试覆盖它。

$ScriptName = $MyInvocation.MyCommand.Nameame

我不确定你想在这里做什么。


至于你的实际问题,我会改编 here 的脚本。

下面的脚本要求您将 FTP 服务器重新格式化为 URI 格式。它将$ftpFile的文件上传到$ftp的位置,等待15分钟,然后从FTP服务器下载相同的文件并保存到$ftpFile,覆盖它。

# Get a FileInfo object for $ftpFile
$ftpFileInfo = Get-Item -Path $ftpFile

# Be sure to include the complete folder path on the server if there is one and
# also be sure to include the trailing /
$ftp = "ftp://ftp.example.com/dir/" 
$user = "user" 
$pass = "Pass"  

# Build a URI to the FTP destination location
$ftpUri = New-Object -TypeName System.Uri -ArgumentList $ftp
$ftpFileUri = New-Object -TypeName System.Uri -ArgumentList $ftpuri, $ftpFileInfo.Name

# Create the web client    
$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $user, $pass

Write-Host "Uploading from $($ftpFileInfo.FullName) to $($ftpFileUri.AbsoluteUri)..."
$webclient.UploadFile($ftpFileUri, $ftpFileInfo.FullName)

# Wait 15 minutes
Write-Host "Waiting until $((Get-Date).AddMinutes(15).ToString('HH:mm:ss'))..."
Start-Sleep -Seconds 900

# Download the file at $ftpFileUri and save it to the path for $ftpFileInfo.FullName
Write-Host "Downloading from $($ftpFileUri.AbsoluteUri) to $($ftpFileInfo.FullName)..."
$webclient.DownloadFile($ftpFileUri, $ftpFileInfo.FullName)

根据 FTP 服务器的要求,这可能有效也可能无效。您可能需要使用类似于 here.

中描述的方法

此外,请记住此方法仅适用于普通 FTP。如果您使用的是 FTPS 或者如果您将其称为 FTP 但实际上是 SFTP,则您需要查看其他内容。 WinSCP 有一个更强大的 .Net 库,您可以使用 PowerShell 编写脚本以与 FTP、FTPS 或 SFTP.

一起使用