Using PowerShell and FTP to Create a Directory

Here’s an example of using PowerShell and FTP to create a directory using credentials to authenticate. If there is an error during the process, we try to see if it’s because the directory already existed. If not, then it must be down to another issue and we can handle the exception accordingly.

$newFolder = "ftp://servername/newfolder/"
$ftpuname = "username"
$ftppassword = "password"
try
{
$makeDirectory = [System.Net.WebRequest]::Create($newFolder);
$makeDirectory.Credentials = New-Object System.Net.NetworkCredential($ftpuname,$ftppassword);
$makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
$makeDirectory.GetResponse();
#folder created successfully
}catch [Net.WebException] 
{
try {
#if there was an error returned, check if folder already existed on server
$checkDirectory = [System.Net.WebRequest]::Create($newFolder);
$checkDirectory.Credentials = New-Object System.Net.NetworkCredential($ftpuname,$ftppassword);
$checkDirectory.Method = [System.Net.WebRequestMethods+FTP]::PrintWorkingDirectory;
$response = $checkDirectory.GetResponse();
#folder already exists!
}
catch [Net.WebException] {				
#if the folder didn't exist, then it's probably a file perms issue, incorrect credentials, dodgy server name etc
}	
}