Upload each file
# Set variables
$ftpServer = "ftp://yourserver.com"
$ftpUsername = "yourUsername"
$ftpPassword = "yourPassword"
$localFolder = "C:\Path\To\Your\Local\Folder"
$remoteFolder = "/path/to/remote/folder"
# Function to create the FTP Uri for files and directories
function Get-FtpUri {
param (
[string]$server,
[string]$remoteFolder,
[string]$relativePath
)
return "$server/$remoteFolder/$relativePath" -replace "\\", "/"
}
# Function to create directories on FTP
function Create-FtpDirectory {
param (
[string]$ftpUri,
[string]$username,
[string]$password
)
try {
$request = [System.Net.WebRequest]::Create($ftpUri)
$request.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
$request.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$response = $request.GetResponse()
$response.Close()
Write-Host "Created directory $ftpUri"
} catch {
Write-Host "Directory $ftpUri may already exist or could not be created. Error: $_"
}
}
# Function to upload a single file
function Upload-File {
param (
[string]$filePath,
[string]$ftpUri,
[string]$username,
[string]$password
)
try {
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$webclient.UploadFile($ftpUri, $filePath)
Write-Host "Uploaded $filePath to $ftpUri"
} catch {
Write-Host "Failed to upload $filePath to $ftpUri. Error: $_"
}
}
# Function to recursively upload files and create folders
function Upload-FolderRecursively {
param (
[string]$localFolderPath,
[string]$remoteFolderPath
)
# Create corresponding remote folder
$relativePath = $localFolderPath.Substring($localFolder.Length).TrimStart("\")
$ftpUri = Get-FtpUri -server $ftpServer -remoteFolder $remoteFolder -relativePath $relativePath
if ($relativePath -ne "") {
Create-FtpDirectory -ftpUri $ftpUri -username $ftpUsername -password $ftpPassword
}
# Get all files and directories in the current folder
$items = Get-ChildItem -Path $localFolderPath
foreach ($item in $items) {
if ($item.PSIsContainer) {
# If item is a directory, recursively call the function
Upload-FolderRecursively -localFolderPath $item.FullName -remoteFolderPath $remoteFolderPath
} else {
# If item is a file, upload it
$relativeFilePath = $item.FullName.Substring($localFolder.Length).TrimStart("\")
$ftpFileUri = Get-FtpUri -server $ftpServer -remoteFolder $remoteFolder -relativePath $relativeFilePath
Upload-File -filePath $item.FullName -ftpUri $ftpFileUri -username $ftpUsername -password $ftpPassword
}
}
}
# Start recursive upload
Upload-FolderRecursively -localFolderPath $localFolder -remoteFolderPath $remoteFolder
Write-Host "All files and folders uploaded."