Timsen
Timsen

Reputation: 4126

How to create directories from powershell on FTP server?

I want to run a PS script when I want to publish to FTP server. I took this script as structure : structure script.

I have very simple folder :

C:\Uploadftp\Files\doc.txt
C:\Uploadftp\Files\Files2
C:\Uploadftp\Files\Files2\doc2.txt

nothing fancy there.

Here is my script :

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)
}

I keep getting this error :

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

If I hardcode specific folder for $uri and tell source to be some specific folder on my computer, this script doesn't create directory, it creates a file. What am I doing wrong?

P.S. dont hit me too hard, its my fist time ever doing something in power shell.

Upvotes: 0

Views: 2354

Answers (1)

Brian Reynolds
Brian Reynolds

Reputation: 411

Try the "Create-FtpDirectory" function from https://github.com/stej/PoshSupport/blob/master/Ftp.psm1

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

Upvotes: 1

Related Questions