Link to home
Start Free TrialLog in
Avatar of E=mc2
E=mc2Flag for Canada

asked on

Convert FTP commands to Powershell or VB Script

I would like to use a powershell/vbs script to run the following commands currently found in a .bat file:


@echo off
setlocal 

set password=xxxxxxxx
set /p password=<%~nx0:password
if not "%password%"=="" goto OK
set /p password=Enter password: 
echo %password%>%~nx0:password
:OK

set localdir=\\srv\folder\NewInbound\folder
set remotedir=/out_folder
set ftpserver=ftp.server.com
set username=xxxxxxxx

::del "%localdir%\*.*" /q

call :GetFtpFiles
call :ClearFTPFiles

exit /b

:GetFTPFiles
    (echo open %ftpserver%
    echo user %username% %password%
    echo bin
    echo cd %remotedir%
    echo lcd "%localdir%"
    echo mget *.*
    echo quit
    ) | ftp -n -i
    exit /b

:ClearfTPFiles
    (echo open %ftpserver%
    echo user %username% %password%
    echo cd %remotedir%
    (for /f "tokens=*" %%a in ('dir /b /a-d "%localdir%\*.*"') do @echo dele "%%~a")
    echo quit
    ) | ftp -n -i -d

Open in new window

Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

You can use .NET libraries such as System.Net.WebClient. Let me know if you need help with it
https://stackoverflow.com/questions/1867385/upload-files-with-ftp-using-powershell
Avatar of E=mc2

ASKER

Hi Shaun, thanks so much.
Yes, I would need help with it actually.
Would I add this script to a batch file?

Also, how would I change this so that it downloads the files instead?

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

Many thanks,
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.