【问题标题】:How to create directories from powershell on FTP server?如何从 FTP 服务器上的 powershell 创建目录?
【发布时间】:2015-08-18 02:58:38
【问题描述】:

当我想发布到 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 硬编码特定文件夹并告诉源是我计算机上的某个特定文件夹,则此脚本不会创建目录,它会创建一个文件。我究竟做错了什么?

附:不要打我太重,这是我第一次在 power shell 中做某事。

【问题讨论】:

标签: powershell ftp


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2010-10-26
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2014-06-02
    • 1970-01-01
    相关资源
    最近更新 更多