使用Response Stream上传带有Powershell的文件

时间:2012-01-27 08:58:20

标签: powershell upload

我在尝试使用PowerShell上传文件时遇到问题。我要做的是将.zip文件发送到目标服务器上的目标用户帐户。目标服务器正在运行IIS FTP 7.5并启用了用户隔离,数据通道端口范围为5500-6500(如果这可能很重要)。

下面是我的代码 - 问题是我无法在$responsestream请求上调用空值表达式上的方法。请让我知道,如果我蠢蠢欲动,整个网络......上传文件有很多问题!

另外我想说我使用了一个我要转换上传的下载脚本,因为我之前尝试过的上传脚本没有取得任何成功。

$targetpath = "ftp://10.21.109.202/Recieve/account_apps.zip"
$sourceuri = "D:\AccountManager\Send\$RTMPHOST\account_apps.zip"
$username = "AccountManager"
$password = "test"

# Create a FTPWebRequest object to handle the connection to the ftp server
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)

# set the request's network credentials for"

#an authenticated connection
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false

# send the ftp request to the server
$ftpresponse = $ftprequest.GetResponse()

# get a download stream from the server response
$responsestream = $ftpresponse.GetRequestStream()

# create the target file on the local system and the download buffer
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024

# loop through the download stream and send the data to the target file
do{
    $readlength = $responsestream.Read($readbuffer,0,1024)
    $targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)

$targetfile.close()

2 个答案:

答案 0 :(得分:3)

以下是使用WebClient类将文件上传到URI的更简单方法:

$targetUri = "ftp://10.21.109.202/Recieve/account_apps.zip"
$sourcePath = "D:\AccountManager\Send\$RTMPHOST\account_apps.zip"
$client = New-Object System.Net.WebClient
$client.Credentials = New-Object System.Net.NetworkCredential($username,$password)

$client.UploadFile($targetUri, $sourcePath)

答案 1 :(得分:0)

请勿使用响应进行上传。 FTP协议不使用往返。

$stream = $ftprequest.GetRequestStream()

$stream.Write(...)

$stream.Close()

$ftpresponse= $ftprequest.GetResponse()
#... is success?
$ftpresponse.Close()

请求后的响应(包含所有字节) 将是上传成功或失败。