2014-04-10 2 views
1

네트워크 공유의 특정 파일을 FTP 서버의 특정 위치로 업로드하는 FTP 자동화 스크립트를 작성 중입니다. 아래에서 찾았지만 원하는 대상 디렉토리로 이동하기 위해 편집 할 수 없습니다.PowerShell 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/에 직접해야합니다. 해당 디렉터리를 찾아보고 업로드 할 수있는 권한이 있지만 필자는 본질적으로 해당 위치로 이동하는 방법을 파악할 수 없습니다.

여기받은 현재의 에러는 다음과 같습니다

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 
+0

이 http://stackoverflow.com/questions/22773071/i-download-new-files-from-ftp-site-with-powershell/22782386#22782386 도움이 될 것입니다 – Raf

+0

불행하게도,이 스크립트가 사용됩니다 몇개의 사업 단위에 의해, 그래서 우리는 그들에게 파일을 줄 수 있어야합니다. 라이브러리를 추가하면 지원에 큰 부담이 될 것입니다. – Wes

+1

안녕하세요. 귀하의 질문에 대한 답변을 개발했습니다. 도움이 될 것입니다. 아래를 봐주세요. –

답변

2

당신은 FtpWebRequest 유형을 사용해야합니다. WebClient은 HTTP 트래픽에 사용됩니다.

Send-FtpFile이라는 파일을 FTP 서버에 업로드하는 매개 변수화 된 함수를 작성하고 테스트했습니다. 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; 
+1

Trevor에게 감사드립니다. 변경 (약 1 시간 후)을하면 이것을 시도 할 것입니다. – Wes

+0

@Wescrock : 환영합니다. 어떻게 작동하는지 알려주십시오. –