如何在FTP服务器上从powershell创建目录?

时间:2015-06-03 18:29:09

标签: powershell ftp

我想在发布到FTP服务器时运行PS脚本。我把这个脚本作为结构:structure script

我的文件夹非常简单:

C:\Uploadftp\Files\doc.txt
C:\Uploadftp\Files\Files2
C:\Uploadftp\Files\Files2\doc2.txt
那里没什么好看的。

这是我的剧本:

cd C:\Uploadftp
$location = Get-Location
"We are here: $location"
$user = "test"  # Change
$pass = "test" # Change
## Get files
$files = Get-ChildItem -recurse  
## Get ftp object
$ftp_client = New-Object System.Net.WebClient

$ftp_client.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  
$ftp_address = "ftp://test/TestFolder"
## Make uploads
foreach($file in $files)
{

   $directory = "";
    $source = $($file.DirectoryName + "/" + $file);
    if ($file.DirectoryName.Length -gt 0)
    {
        $directory = $file.DirectoryName.Replace($location,"")
    }

     $directory = $directory.Replace("\","/")
     $source = $source.Replace("\","/")
    $directory += "/";
    $ftp_command = $($ftp_address + $directory + $file)
     # Write-Host $source
    $uri = New-Object System.Uri($ftp_command)
    "Command is " + $uri + " file is $source"
    $ftp_client.UploadFile($uri, $source)
}

我一直收到这个错误:

Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."

如果我对$uri的特定文件夹进行硬编码并告诉源是我的计算机上的某个特定文件夹,则此脚本不会创建目录,而是会创建一个文件。我究竟做错了什么?

P.S。不要打我太厉害,这是我第一次用力量做一些东西。

1 个答案:

答案 0 :(得分:1)

尝试https://github.com/stej/PoshSupport/blob/master/Ftp.psm1

中的“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();
}