1

Good morning!

I have made it to the last (and rather pivotal) stage in my script, which is looping to delete files from a directory. I'm not going to pretend I'm knowledgeable at Powershell (far from it), so I'm sort-of chopping up blocks of code I find on the net, improvising and hoping it works.

I'm hoping someone can decipher what I'm trying to do here and see what I'm doing wrong!

#   Clear FTP Directory
$DelLoop=1
$server = "www.newsbase.com"
$dir = "/usr/local/tomcat/webapps/newsbasearchive/monitors/asiaelec/"
"open $server
user Canttell Youthis
binary  
cd $dir    
" +(
For ($DelLoop=1; $DelLoop -le 5; 5)
    {
        $FileList[$DelLoop] | %{ "delete ""$_""`n" }
        $DelLoop++
    })| ftp -i -in

I know that the 'Open Connection' portion works, it's just the loop. It just keeps complaining about misplaced operators, and when I fix those, it doesn't throw up any errors - but it doesn't do anything either.

I spent the best part of 4 hours researching this yesterday, and I'm hoping one of you guys can help me.

Thanks in advance!

ADDENDUM:

Here is more of the code, as requested:

#   Clear existing .htm file to avoid duplication
Get-ChildItem -path ".\" -recurse -include index.jsp | ForEach-Object {
Clear-Content "index.jsp"
}

#   Set first part of .JSP Body
$HTMLPart1="</br><tr><td colspan=9 align=center><p style=""font-family:Arial"">Here are the links to the last 3 AsiaElec PDFs:</br><ul>"

#   Recurse through directory, looking for 3 most recent .PDF files 3 times
$Directory="C:\PDFs"
$HTMLLinePrefix="<li><a style=""font-family:Arial""href="""
$HTMLLineSuffix="</a></li>"
$HTMLLine=@(1,2,3,4)
$Loop=1
$PDF=@(1,2,3,4)
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object {
        $PDF[$Loop]=$_.name
        $HTMLLine[$Loop]=$HTMLLinePrefix + $_.name + """>" + $_.name + $HTMLLineSuffix
        $Loop++
    }

#   Final .JSP File Assembly
Get-Content "header.html" >> "index.jsp"
$HTMLPart1 >> "index.jsp"
$LineParse=""
$Loop2=1
For ($Loop2=1; $Loop2 -le 3; 3)
    {
        $HTMLLine[$Loop2] >> "index.jsp"
        $Loop2++
    }
Get-Content "tail.html" >> "index.jsp"

#   Prepare File List
$FileList=@(1,2,3,4,5)
$FileList[2]=$PDF[2]
$FileList[3]=$PDF[3]
$FileList[4]="index.jsp"

#   Clear FTP Directory
$DelLoop=1
$server = "www.newsbase.com"
$dir = "/usr/local/tomcat/webapps/newsbasearchive/monitors/asiaelec/"
"open $server
user derek bland1ne
binary  
cd $dir    
" +(
For ($DelLoop=1; $DelLoop -le 5; 5)
    {
        $FileList[$DelLoop] | %{ "delete ""$_""`n" }
        $DelLoop++
    })| ftp -i -in

This isn't all of it, but I believe it contains all the relevant info.

N3cRiL
  • 85
  • 2
  • 3
  • 8
  • Why not take a look at a PS module? http://gallery.technet.microsoft.com/scriptcenter/PowerShell-FTP-Client-db6fe0cb – Frode F. Jan 30 '13 at 08:49
  • I've looked at and tried the actual PowerShell way of doing it, but I simply couldn't understand it, nor get it to work, although all the parameters were correct. I have tried this block of code, it works, now I just need it to work while incorporated into the bulk of my script. – N3cRiL Jan 30 '13 at 08:58
  • kk, just a suggestion. That module makes it alot easier then using the .Net classes manually :-) – Frode F. Jan 30 '13 at 08:59
  • The .Net classes are exactly what I tried, and they were confusing as hell :( They didn't seem to want to do what I wanted to do – N3cRiL Jan 30 '13 at 09:12
  • READ the comment. I said the Module(a collection of FUNCTIONS) makes it EASIER then using .NET. the functions work just like `Get-ChildItem` (dir) etc. – Frode F. Jan 30 '13 at 09:14
  • I'm not a programmer by profession, I do it as a hobby/to help out occasionally. I'm not going to understand specific jargon for tasks I do once a month when it's flung at me. I'm sure your solution works, and is better than mine, but you can't expect me to understand what you're saying without explanation. – N3cRiL Jan 30 '13 at 09:38
  • You mind sharing a bit more of your code? Especially what does $fileList contain? The module that @Graimer mentions does make this easier, but I understand how just looking at code like that could make someone new's head spin. – malgca Jan 30 '13 at 09:43
  • Done! Please bear in mind everything before the block I showed you works perfectly, I've been writing block-by-block, testing and amending as I needed to. – N3cRiL Jan 30 '13 at 09:48

1 Answers1

2

Your $dir path looks like you're on a unix system so this may be a little different, but all you need to do is change your final loop a little bit:

For ($DelLoop=1; $DelLoop -le 5; $DelLoop++)
{
    $FileList[$DelLoop] | % { rm $FileList[$DelLoop] }
} 

This is assuming that $FileList contains the files you want to delete and not only (what I'm guessing are dummy) numbers. I also suggest that you download the Module that @Graimer mentions and then put it in WindowsPowerShell > Modules > %ModuleFolder% > %Module.psm1% and import it from your profile.

You can then just use PS> Remove-FTPItem -Path "/myFolder" -Recurse to remove your FTP stuff. Making your life easier.

Tweaking the solution to this post may also help Upload files with FTP using PowerShell

e.g:

Using $ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile to delete the file,

and $response = $ftp.GetResponse() to find out if things went smoothly.

EDIT

Wrote this function after doing a little bit of research from here http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/17a3abbc-6144-433b-aadd-1f776c042bd5 and adapting the code from the Accepted Answer in the above link as well as the module @Graimer talked about.

function deleteFTPSide 
{
    Param(
        [String] $ftpUserName = "muUserName",
        [String] $ftpDomain = "ftp.place.com", # Normal domains begin with "ftp" here
        [String] $ftpPassword = "myPassword",
        [String] $ftpPort = 21, # Leave as the default FTP port
        [String] $fileToDelete = "folder.domain.com/subfolder/file.txt"
    )

    # Create the direct path to the file you want to delete
    [String] $ftpPath = "ftp://"+"$ftpUserName"+":"+"$ftpPassword@$ftpDomain"+":"+"$ftpPort/$fileToDelete"

    # create the FtpWebRequest and configure it
    $ftp = [System.Net.FtpWebRequest]::Create($ftpPath)

    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile

    $ftp.Credentials = new-object System.Net.NetworkCredential($ftpUserName,$ftpPassword)

    $ftp.UseBinary = $true
    $ftp.UsePassive = $true

    $response = [System.Net.FtpWebResponse]$ftp.GetResponse()
    $response.Close()
}

While, admittedly, not one of the most elegant solutions written, I've tested it and it works at deleting a specified file off an FTP server.

Community
  • 1
  • 1
malgca
  • 2,707
  • 2
  • 16
  • 9
  • Ahh thank you - But you see, the script will be run on 30+ computers, not just mine, and having all of my guys download and install (and most likely having to support them) sounds more like a chore :( – N3cRiL Jan 30 '13 at 10:19
  • I see, in that case try looking at the Link I posted. It gives you some code for getting into and working with an ftp server. It only needs a little tweaking for deleting from it. The small change I've given you will delete things on your local side. – malgca Jan 30 '13 at 10:28
  • Haha, that's funny, that's the solution I tried, and couldn't get to work... Look at the solution with 7 votes up. It'll look awfully familiar. – N3cRiL Jan 30 '13 at 11:03
  • True :) But I was referring to the accepted answer, with 22 votes up :) Have you tried that one? – malgca Jan 30 '13 at 11:36
  • I have, that's the one I tried. I couldn't get it working, it'd keep giving me FTP errors, even though all the parameters were correct. – N3cRiL Jan 30 '13 at 11:53
  • Absolutely amazing. Thank you so much! – N3cRiL Jan 30 '13 at 15:58
  • Actually, this doesn't seem to work either... Doesn't throw up any errors, but it does nothing. I'm sure this is my own mistake, but I can't see any... I'm trying to Write-Host the $ftpPath after it's been concatenated, but it's not coming up with anything. – N3cRiL Jan 31 '13 at 08:38
  • Swapped some dummy values in to try to make it clearer. Also important that $fileToDelete doesn't start with "/". $ftpPath should otherwise show up if you write host it (I juts tried :)) – malgca Jan 31 '13 at 09:05
  • Sorry, I'm an idiot. I just realised you gave me a FUNCTION, not a block of code. However, now I'm faced with a rather annoying (and familiar) error - The Path is + ftp://user:pass@www.newsbase.com:21/newsbasearchive/monitors/asiaelec/index.jsp Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (550) File unavailable (e.g ., file not found, no access)." The path is right, but I can't browse to it with any web browsers using the FTP:// protocol. Swapping the "www" with "ftp" returns me with 530: not logged in. – N3cRiL Jan 31 '13 at 09:15
  • Do you have the access rights with your credentials? And does the file you're looking for exist on the server? – malgca Jan 31 '13 at 09:20
  • My user is full RWX across the board, especially in that directory (I made sure of that before I started). The directory does exist, too, because I can browse to it with http://. – N3cRiL Jan 31 '13 at 09:24
  • have you enabled ftp on your own machine? (Assuming you're using Windows), is it enabled on the server side? Is your firewall perhaps blocking you? – malgca Jan 31 '13 at 09:43
  • Well, I was able to do the same thing using the FTP function of CMD, or does that operate differently? – N3cRiL Jan 31 '13 at 09:56
  • I get the same problem when the file I'm trying to delete doesn't exist on the server. Make sure that "index.jsp" exists on the server you're trying to delete it from. Also your ftp connection should be somthing like `user:pass@ftp.newsbase.com:21....` instead of `user:pass@www.newsbase.com:21...` changing the "www" for "ftp", lastly, make sure the path to the file is correct as the FTP server sees it, so if its `newsbasearchive.monitors.asiaelec/index.jsp` type it in as such, instead of `newsbasearchive/monitorsasiaelec/index.jsp` – malgca Jan 31 '13 at 10:24