Create directories from path on FTP with Powershell

Probably many of you used FTP to store some data using different libraries of different languages. As PowerShell is based on .NET Framework, I’ll show you up how to check and if necessary, create directories from path on FTP we’re planning to send data to with a simple Powershell function.

Getting started

So we’re starting with a simple FTP path, let’s say:

To make our life a little easier, let’s split it into two parts – $ServerPath, that is a path to root of FTP server and $DirectoryPath, that is local, relative path to directory from FTP server itself. I will simplify that part given the fact that you’ll probably have ftp inputted yourself and hardcoded inside the script. If you want to make that more universal, you can edit code a little what will also parse “ftp://” part.

Hardcoded way:

Easy, universal way using System.Uri:

Let’s also prepare login data so we can actually connect to FTP with credentials we want to:

The idea

Ok, we have everything we need to connect to FTP. However, if we’ll attempt to upload a file to a directory that doesn’t exist on FTP, we’ll get prompted with error:

We need to figure it out how to go down the directory tree, to the target directory.
If you use the ‘easy universal way’, you’ll be already provided with array created from relative path splitted into directories using $FtpPath.Segments:

    System.URI Segments ToString()

If you’re about to go with hardcoded way, split the string with a standard String.Split() method with a “/” as an argument like this:

The output we’ll get will be the same as above, as both System.Uri.Segments and String.Split() will return us an array of strings.
Finally, let’s go through the whole directory tree, adding directories one by one to the path and figuring out whether we need to create directory for ourselves or not. To keep on track with current position in our process, let’s use additional variable called $Position. We’ll also be watching out for some errors with usage of try-catch block:

The reason why we’re letting function continue after catching Net.WebException is that if directory actually exists, $WebRequest will fail to make directory.

Final wrap up

Function itself:

Usage of the function:


Please note that, script is adapted to use Uri with ‘/’ at the end. If you’re intending to use Uri without ‘/’ on the end, you’ll need to make loop work one more time, that is ‘-1’ excluded:

Also, if you’re gonna use $FtpPath.Segments, delete ‘+ “/”‘ from string concatenation on the first line of try block, as it still consists “/”, so no need to add additional one:

Don’t forget to properly add scopes to your code. I’ve not used them for code simplification but you should definitely take care of it!

Leave a Reply

Your email address will not be published. Required fields are marked *