Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a directory on remote FTP using powershell

I"m able to put a file up to a remote FTP with a modified version of...

          $File = "D:\Dev\somefilename.zip"
          $ftp = "ftp://username:[email protected]/pub/incoming/somefilename.zip"

           "ftp url: $ftp"

          $webclient = New-Object System.Net.WebClient
          $uri = New-Object System.Uri($ftp)

          "Uploading $File..."

          $webclient.UploadFile($uri, $File)

I'm running into the problem that I"m trying to upload a file to a directory that doesn't exist, the put fails. So I need to create the target directory first. GET-MEMBER doesn't seem to show any methods I can invoke to create a directory, only file operations.

like image 521
ryan Avatar asked Apr 21 '11 04:04

ryan


1 Answers

I use function Create-FtpDirectory

function Create-FtpDirectory {
  param(
    [Parameter(Mandatory=$true)]
    [string]
    $sourceuri,
    [Parameter(Mandatory=$true)]
    [string]
    $username,
    [Parameter(Mandatory=$true)]
    [string]
    $password
  )
  if ($sourceUri -match '\\$|\\\w+$') { throw 'sourceuri should end with a file name' }
  $ftprequest = [System.Net.FtpWebRequest]::Create($sourceuri);
  $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
  $ftprequest.UseBinary = $true

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

  $response = $ftprequest.GetResponse();

  Write-Host Upload File Complete, status $response.StatusDescription

  $response.Close();
}

Taken from Ftp.psm1 where you can find also other functions for FTP.

To others: sorry for not following well known verb-noun pattern. ;)

like image 138
stej Avatar answered Sep 21 '22 02:09

stej