【问题标题】:PowerShell FTP automation issuePowerShell FTP 自动化问题
【发布时间】:2014-04-10 15:07:23
【问题描述】:

我正在编写一个 FTP 自动化脚本,该脚本会将某些文件从网络共享上传到 FTP 服务器上的特定位置。我找到了以下内容,但无法对其进行编辑以导航到所需的目标目录。

#ftp server 
$ftp = "ftp://SERVER/OtherUser/" 
$user = "MyUser" 
$pass = "MyPass"  

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  

#list every sql server trace file 
foreach($item in (dir $Dir "*.trc")){ 
    "Uploading $item..." 
    $uri = New-Object System.Uri($ftp+$item.Name) 
    $webclient.UploadFile($uri, $item.FullName) 
 } 

我有 FTP 服务器的凭据,但默认为 /home/MyUser/,我需要定向到 /home/OtherUser/。我确实有权浏览并上传到该目录,但我不知道如何从本质上 cd 到该位置。

这是当前收到的错误:

Exception calling "UploadFile" with "2" argument(s): "The remote server returned an erro
r: (550) File unavailable (e.g., file not found, no access)."
At line:26 char:26
+     $webclient.UploadFile <<<< ($uri, $item.FullName) 
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

【问题讨论】:

  • 不幸的是,这个脚本将被多个业务部门使用,所以我们需要能够简单地给他们文件。我觉得为他们添加一个库会造成很大的支持负担。
  • 您好,我已经为您的问题制定了一个答案,我认为您会发现它对您有所帮助。请看下文。

标签: powershell ftp automation


【解决方案1】:

您需要使用FtpWebRequest 类型。 WebClient 用于 HTTP 流量。

我已经编写并测试了一个参数化函数,它将文件上传到 FTP 服务器,称为Send-FtpFile。我使用sample C# code from MSDN 将其转换为 PowerShell 代码,效果很好。

function Send-FtpFile {
    [CmdletBinding()]
    param (
          [ValidateScript({ Test-Path -Path $_; })]
          [string] $Path
        , [string] $Destination
        , [string] $Username
        , [string] $Password
    )
    $Credential = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $Username,$Password;

    # Create the FTP request and upload the file
    $FtpRequest = [System.Net.FtpWebRequest][System.Net.WebRequest]::Create($Destination);
    $FtpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile;
    $FtpRequest.Credentials = $Credential;

    # Get the request stream, and write the file bytes to the stream
    $RequestStream = $FtpRequest.GetRequestStream();
    Get-Content -Path $Path -Encoding Byte | % { $RequestStream.WriteByte($_); };
    $RequestStream.Close();

    # Get the FTP response
    [System.Net.FtpWebResponse]$FtpRequest.GetResponse();
}

Send-FtpFile -Path 'C:\Users\Trevor\Downloads\asdf.jpg' `
    -Destination 'ftp://google.com/folder/asdf.jpg' `
    -Username MyUsername -Password MyPassword;

【讨论】:

  • 谢谢特雷弗。当我得到改变时(大约一个小时),我会试试这个。
猜你喜欢
  • 2018-08-31
  • 2017-10-02
  • 2016-09-30
  • 2010-10-02
  • 2010-12-06
  • 1970-01-01
  • 2012-06-15
  • 2022-08-05
  • 1970-01-01
相关资源
最近更新 更多