Creating a directory on remote FTP using powershel

2019-06-22 00:10发布

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:password@example.com/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.

1条回答
我只想做你的唯一
2楼-- · 2019-06-22 00:20

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. ;)

查看更多
登录 后发表回答