Using Powershell and FTP to Create a Directory on a Server

Here’s an example of how we can use Powershell and an FTP request (with credentials) to create a directory on a server somewhere.  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
	}	
}