Geeks With Blogs

Lance's TextBox

update:  here's an updated function for uploading an entire directory tree:

## ftprecursiveupload.ps1: Recursive FTP Upload
## Uploads a directory tree to a remote FTP server.
## Returns an objects containing information about the files transferred.
function upload-directory {
param( [string] $server = $( Throw "You must specify an FTP server to logon to."),
[string] $dir = $( Throw "You must specify a local directory to upload (ie, C:\Testing\FTPTest\)"),
[switch] $overwrite = $false,
[System.Management.Automation.PSCredential] $cred = $( Throw "You must provide credentials with which to logon to the FTP server.") )

$files = (get-childitem $dir -r)
foreach ($file in $files) {
$remfilename = $file.FullName.Replace($dir, "")
$remfilename = $remfilename.Replace("\", "/")
if ($file.Attributes.ToString().IndexOf("Directory") -ge 0) {
try
{
send-ftp -server $server -cred $cred -create $remfilename -overwrite:$overwrite
}
catch {} #if the directory already exists, ignore the error
}
else {
send-ftp -server $server -cred $cred -localfile $file.FullName -remotefile $remfilename -overwrite:$overwrite
}
}
}

Original Post:

ckj asked me how to "recursively upload a directory mutiple levels deep via send-ftp". Here is my answer:

For now, the send-ftp cmdlet allows you to upload one file at a time (its a beta). But you can easily use get-children's recursive flag to get a list of all the files to upload, and call send-ftp for each one. Here is a little script to do so.


param( [string] $dir = "C:\Testing\FTPTest\" )

$files = (get-childitem $dir -r)
foreach ($file in $files) {
$remfilename = $file.FullName.Replace($dir, "")
$remfilename = $remfilename.Replace("\", "/")
if ($file.Attributes -eq "Directory") {
send-ftp -server MYSERVER -user TEST -password TEST -create $remfilename
}
else {
send-ftp -server MYSERVER -user TEST -password TEST -localfile $file.FullName -remotefile $remfilename
}
Write-Host $remfilename
}

Technorati : , , ,

Posted on Thursday, December 7, 2006 11:37 AM Programming , Software , PowerShell | Back to top


Comments on this post: NetCmdlets FTP - recursive directory upload

# re: NetCmdlets FTP - recursive directory upload
Requesting Gravatar...
How could I check if the directory already exists before creating it?
Left by Recurfizz on Sep 17, 2007 11:34 AM

# re: NetCmdlets FTP - recursive directory upload
Requesting Gravatar...
The command:

get-ftp -server MYSERVER -user TEST -password TEST

Will return a directory listing.
Left by Lance on Sep 17, 2007 3:12 PM

Your comment:
 (will show your gravatar)


Copyright © Lance Robinson | Powered by: GeeksWithBlogs.net