使用PowerShell在远程FTP上创建一个目录

使用PowerShell在远程FTP上创建一个目录

本文介绍了使用PowerShell在远程FTP上创建一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ File =D:\Dev\somefilename.zip
$ ftp =ftp://用户名:[email protected]/pub/incoming/somefilename.zip

ftp url:$ ftp

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

上传$ File ...

$ webclient.UploadFile($ uri,$ File)

我遇到了一个问题,我试图将文件上传到一个不存在的目录,这个失败。所以我需要先创建目标目录。 GET-MEMBER似乎没有显示任何我可以用来创建目录的方法,只有文件操作。

功能 Create-FtpDirectory

 函数Create-FtpDirectory {
param(
[Parameter(Mandatory = $ true)]
[string]
$ sourceuri,
[Parameter(Mandatory = $ true)]
[string]
$ username,
[参数(强制= $ true)]
[字符串]
$密码

if($ sourceUri -match'\ \ $ | \\\\w + $'){throw'sourceuri应该以文件名结束'}
$ ftprequest = [System.Net.FtpWebRequest] :: Create($ sourceuri);
$ ftprequest.Method = [System.Net.WebRequestMethods + Ftp] :: MakeDirectory
$ ftprequest.UseBinary = $ true

$ ftprequest.Credentials =新对象系统。 Net.NetworkCredential($ username,$ password)

$ response = $ ftprequest.GetResponse();

写主机上传文件完成,状态$ response.StatusDescription

$ response.Close();

取自,您可以在其中找到FTP的其他功能。




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.

解决方案

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

这篇关于使用PowerShell在远程FTP上创建一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:28