VB script for send mail - email

I dont have knowledge about vb scripting. so m asking here please help me... :)
we have one backup batch script which copy all data to another server using robo copy.
we schedule that script, but all the time we have to go that server and check manually that script run or not.
now we have write one vb script that will call that batch script and check that script run properly if script run properly then mail will come as backup completed else backup is not completed.
please if you have any idea about vb script please help me.

You can use mailsend.exe , just have the exe placed in your scripts folder & append the below code to you RoboCopy script at the end. If you don't want to cc or bcc anyone just add +cc & +bcc
type logs.txt | mailsend.exe -smtp smtp_server_ip_or_FQDN -port 25 -d smtp.mail.com -t xyz#mail.com -f seding_from#mail.com -sub "Whatever Subject" -user mail_username#mail.com -pass mailpassword -auth -cc xyz#mail.com -bcc xyz#mail.com

Here's a batch file that uses VBS to send an email.
Read the comments in the script to see how to test it.
:: email.bat :::::::::::::::::::::::::::::::::::::::::::::::::::::
#echo off
setlocal
:: use these settings to send from a gmail account
:: set port=465 and set SSL=True
:: use these settings for standard email SMTP port and no encryption
:: set port=25 and set SSL=False
:: Change these following items to use the same variables all the time
:: or use the command line to pass all the variables
set Port=25
set SSL=False
set From="myemail#myemailserver.com"
set To="recipient#server.com"
set Subject="Subject line"
set Body="Email Body in one line"
set SMTPServer="mailservername.myemailserver.com"
set User="username"
set Pass="password"
set fileattach="d:\myfolder\file.txt"
:: This section sets the command line arguments
:: use this format: CALL email.bat "myname#gmail.com" "RecipientEmailAddress#server.com" "Subject line" "Email Body in one line" "smtp.gmail.com" "myname#gmail.com" "password" "d:\folder\filename to attach.txt"
if "%~7" NEQ "" (
set From="%~1"
set To="%~2"
set Subject="%~3"
set Body="%~4"
set SMTPServer="%~5"
set User="%~6"
set Pass="%~7"
set fileattach="%~8"
)
set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul
set cdoSchema=http://schemas.microsoft.com/cdo/configuration
echo >>"%vbsfile%" Set objArgs = WScript.Arguments
echo >>"%vbsfile%" Set objEmail = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From = %From%
echo >>"%vbsfile%" objEmail.To = %To%
echo >>"%vbsfile%" objEmail.Subject = %Subject%
echo >>"%vbsfile%" objEmail.Textbody = %body%
if exist %fileattach% echo >>"%vbsfile%" objEmail.AddAttachment %fileattach%
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendusing") = 2 ' not local, smtp
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpserver") = %SMTPServer%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpserverport") = %port%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendusername") = %user%
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendpassword") = %pass%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpusessl") = %SSL%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpconnectiontimeout") = 30
echo >>"%vbsfile%" .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send
cscript.exe /nologo "%vbsfile%"
echo email sent (if variables were correct)
del "%vbsfile%" 2>nul
goto :EOF

Related

Robocopy certain filename and latest file

Im kinda need help with scripting robocopy.
I want copy file with "-Full.zip" contain in the filename and the latest file.
[I want copy filename contain -Full.zip]
[1]: https://i.stack.imgur.com/ngJ3V.jpg
Here is my code but not working
#echo off
set Source=D:\Source
set Target=F:\Target
set Logfile=F:\Test\logcopy.log
SET debug=-debug -log blat.log -timestamp
set Scr="%temp%\TempVBS.vbs"
( echo sPath = "%Source%"
echo Set oFSO = CreateObject("Scripting.Filesystemobject"^)
echo sYesterday = FormatDateTime(DateAdd("d", Now(^), 0^),0^)
echo Process sPath
echo Sub Process(sP^)
echo For Each oFile In oFSO.GetFolder(sp^).Files
echo If FormatDateTime(oFile.DateLastModified,2^) = sYesterday _
echo Then oFile.Attributes = 32 _
echo Else oFile.Attributes = 0
echo Next
echo For Each oFolder In oFSO.GetFolder(sP^).SubFolders
echo Process oFolder.Path
echo Next
echo End Sub ) > %Scr%
cscript //nologo %Scr%
del %Scr%
robocopy "*-Full.zip" /a /s "%Source%" "%Target%" /XF /XC /XO /LOG:%Logfile%

use for loop to add downloading sections to a powershell script

I want to construct a powershell script that downloads a specific set of files. This set will change periodically, so a for loop is the cleanest way to update the process.
The URLs for each file update on a daily basis with both the date and a unique serial number, but I already have a process in place for extracting that info and saving it to a file. I also have a method for constructing a PS script to download a specific file from such a URL:
set /p file_info=<"<path to file with info>"
set file_dir=<known page directories>
set DL=C:\Users\%USERNAME%\Downloads\test.ps1
echo $url = "http://<domain>.com/%file_dir%/%file_info%" > "%DL%"
echo $output = "C:\Users\%USERNAME%\Downloads\%file_info%" >> "%DL%"
echo (New-Object System.Net.WebClient).DownloadFile($url, $output) >> "%DL%"
I can also loop additions to a PS script:
setlocal enabledelayedexpansion
set /p obj=<"<path to file with list of objects>"
set /p file_info=<"<path to file with info>"
set DL=C:\Users\%USERNAME%\Downloads\test.ps1
:: restarting PS script
echo #new > "%DL%"
for %%f in (%obj%) do (
set a=%%f
echo !a!!file_info! >> "!DL!"
)
However, when I replace echo !a!!file_info! >> "!DL!" with the echo lines from the first script (adapted in the same fashion), the PS script is no longer updated with the looped content (note that I now use the PS username to avoid any issues with delayed expansion):
setlocal enabledelayedexpansion
set /p obj=<"<path to file with list of objects>"
set /p file_info=<"<path to file with info>"
set file_dir=<known page directories>
set DL=C:\Users\%USERNAME%\Downloads\test.ps1
:: restarting PS script
echo #new > "%DL%"
for %%f in (%obj%) do (
set a=%%f
echo $url = "http://<domain>.com/!file_dir!/!a!/!file_info!" >> "!DL!"
echo $output = "C:\Users\$env:UserName\Downloads\!file_info!" >> "!DL!"
echo (New-Object System.Net.WebClient).DownloadFile($url, $output) >> "!DL!"
)
::alternative that doesn't work either:
for %%f in (%obj%) do (
set a=%%f
call echo $url = "http://<domain>.com/!file_dir!/!a!/!file_info!" >> "!DL!"
call echo $output = "C:\Users\$env:UserName\Downloads\!file_info!" >> "!DL!"
call echo (New-Object System.Net.WebClient).DownloadFile($url, $output) >> "!DL!"
)
Why are there issues using a for loop to add URL download sections to a PS script? Is there a way to avoid these issues?
The main problem with your code is that your echoed closing parentheses are prematurely closing the for loop parentheses. In my example below, I've escaped those with carets, ^.
Example:
#Echo Off
SetLocal EnableExtensions
Set /P "obj=" 0< "<path to file with list of objects>"
Set /P "file_info=" 0< "<path to file with info>"
Set "file_dir=<known page directories>"
Set "DL=C:\Users\%USERNAME%\Downloads\test.ps1"
( For %%G In (%obj%) Do (
Echo $url = "http://<domain>.com/%file_dir%/%%G/%file_info%"
Echo $output = "C:\Users\$Env:UserName\Downloads\%file_info%"
Echo (New-Object System.Net.WebClient^).DownloadFile($url, $output^)
)
) 1> "%DL%"

Manage a Batch-based server in PowerShell

I downloaded the binaries of a web server app. Extracting it leaves me with the following directory tree:
./
bin/
start.bat
stop.bat
lib/
*.jar
*.*
As a PowerShell fan, I would rather call Start-MyWebServer.ps1 than start.bat.
This task would be simple if it wasn't for start.bat: it writes the logs directly in the console, and asks to Press a key to continue... before exiting (pause?). The same goes for stop.bat.
I've tried various solutions based on Start-Process -FilePath "...\start.bat" -NoNewWindow, with an without -Wait in order to start the server in the background...
I also tried using Start-Job:
Start-Job -Name "MyWebServer" -ScriptBlock {
Start-Process -FilePath "...\start.bat" -Wait -NoNewWindow
} | Out-Null
This last solution almost works, i.e. when Start-MyWebServer.ps1 returns, the server is still initializing, even though the job is marked as completed. Is there a better solution to my problem that polling the server until it's ready? Or is it the expected behavior of a Start-* commandlet?
Here is the content of start.bat (actually named startup.bat, credit: GeoServer):
#echo off
rem -----------------------------------------------------------------------------
rem Startup Script for GeoServer
rem -----------------------------------------------------------------------------
cls
echo Welcome to GeoServer!
echo.
set error=0
rem JAVA_HOME not defined
if "%JAVA_HOME%" == "" goto trySystemJava
rem JAVA_HOME defined incorrectly
if not exist "%JAVA_HOME%\bin\java.exe" goto badJava
rem Setup the java command and move on
set RUN_JAVA=%JAVA_HOME%\bin\java
echo JAVA_HOME: %JAVA_HOME%
echo.
:checkGeoServerHome
rem GEOSERVER_HOME not defined
if "%GEOSERVER_HOME%" == "" goto noHome
rem GEOSERVER_HOME defined incorrectly
if not exist "%GEOSERVER_HOME%\bin\startup.bat" goto badHome
goto checkDataDir
:trySystemJava
for /f %%i in ('where java') do set RUN_JAVA=%%i
rem --- we might be on amd64 having only x86 jre installed ---
if "%RUN_JAVA%"=="" if DEFINED ProgramFiles(x86) if NOT "%PROCESSOR_ARCHITECTURE%"=="x86" (
rem --- restart the batch in x86 mode---
echo Warning: No java interpreter found in path.
echo Retry using Wow64 filesystem [32bit environment] redirection.
%SystemRoot%\SysWOW64\cmd.exe /c %0 %*
exit /b %ERRORLEVEL%
)
if "RUN_JAVA%"=="" goto noJava
goto checkGeoServerHome
:noJava
echo The JAVA_HOME environment variable is not defined, and no Java executable could be found.
goto JavaFail
:badJava
echo The JAVA_HOME environment variable is not defined correctly.
goto JavaFail
:JavaFail
echo Please install Java or, if present but not in the path, set this environment variable via the following command:
echo set JAVA_HOME=[path to Java]
echo Example:
echo set JAVA_HOME=C:\Program Files\Java\jdk8
echo.
set error=1
goto end
:noHome
if exist ..\start.jar goto noHomeOK
echo The GEOSERVER_HOME environment variable is not defined.
goto HomeFail
:badHome
if exist ..\start.jar goto badHomeOK
echo The GEOSERVER_HOME environment variable is not defined correctly.
goto HomeFail
:HomeFail
echo This environment variable is needed to run this program.
echo.
echo Set this environment variable via the following command:
echo set GEOSERVER_HOME=[path to GeoServer]
echo Example:
echo set GEOSERVER_HOME=C:\Program Files\GeoServer
echo.
set error=1
goto end
:noHomeOK
echo The GEOSERVER_HOME environment variable is not defined.
goto setHome
:badHomeOK
echo The GEOSERVER_HOME environment variable is not defined correctly.
goto setHome
:setHome
echo Temporarily setting GEOSERVER_HOME to the following directory:
cd ..
set GEOSERVER_HOME=%CD%
echo %GEOSERVER_HOME%
echo.
goto checkDataDir
:checkDataDir
rem GEOSERVER_DATA_DIR not defined
if "%GEOSERVER_DATA_DIR%" == "" goto noDataDir
goto setMarlinRenderer
:noDataDir
rem if GEOSERVER_DATA_DIR is not defined then use GEOSERVER_HOME/data_dir/
if exist "%GEOSERVER_HOME%\data_dir" goto setDataDir
echo No valid GeoServer data directory could be located.
echo Please set the GEOSERVER_DATA_DIR environment variable.
echo.
echo Set this environment variable via the following command:
echo set GEOSERVER_DATA_DIR=[path to data_dir]
echo Example:
echo set GEOSERVER_DATA_DIR=C:\Program Files\GeoServer\data_dir
echo.
set error=1
goto end
:setDataDir
set GEOSERVER_DATA_DIR=%GEOSERVER_HOME%\data_dir
echo The GEOSERVER_DATA_DIR environment variable is not defined correctly.
echo Temporarily setting GEOSERVER_DATA_DIR to the following directory:
echo %GEOSERVER_DATA_DIR%
echo.
goto setMarlinRenderer
:setMarlinRenderer
cd %GEOSERVER_HOME%
for /f "delims=" %%i in ('dir /b/s "%GEOSERVER_HOME%\webapps\geoserver\WEB-INF\lib\marlin*.jar"') do set MARLIN_JAR=%%i
if "%MARLIN_JAR%" == "" (
echo Marlin renderer jar not found
goto run
)
set MARLIN_ENABLER=-Xbootclasspath/a:"%MARLIN_JAR%" -Dsun.java2d.renderer=org.marlin.pisces.MarlinRenderingEngine
set JAVA_OPTS=%JAVA_OPTS% %MARLIN_ENABLER%
goto run
:run
cd %GEOSERVER_HOME%
echo Please wait while loading GeoServer...
echo.
"%RUN_JAVA%" %JAVA_OPTS% -DGEOSERVER_DATA_DIR="%GEOSERVER_DATA_DIR%" -Djava.awt.headless=true -DSTOP.PORT=8079 -DSTOP.KEY=geoserver -jar start.jar
cd bin
goto end
:end
if %error% == 1 echo Startup of GeoServer was unsuccessful.
echo.
pause
Did you consider the capturing of the output of the start.bat?
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = '...\start.bat'
$psi.RedirectStandardOutput = $true
$psi.UseShellExecute = $false
$psi.WindowStyle = 'Minimized'
$bytes = New-Object System.Collections.ArrayList
$s = ''
$enc = [System.Text.Encoding]::ASCII
$done = 'Press any key to continue'
$p = [System.Diagnostics.Process]::Start($psi)
for() {
$i = $bytes.add($p.StandardOutput.BaseStream.ReadByte())
if( $bytes[$i] -lt 0 ) { break }
$s = $enc.GetString($bytes)
if( $s -match "`n${done}$" ) { break }
}
if( !$p.HasExited ) {
$p.Kill()
Write-Host 'done...'
}
$p.Dispose()

Password set in batch file not taking last character

I have a batch file that accept input from the user for the password. It does not take the last character for some reason and I cannot figure it out.
powershell -Command $pword = read-host "Enter password " -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt
echo psexec \\%computerName% -u %domainName%\%userName% -p %password% cmd
I know it is not the powershell command because I tested it with set /p password="Enter password: " and still fails to echo the last character.
As per my comment, here are the if statements I used:
set /P domainName=
set params = %*:"=""?!
if "%domainName%" == "1" (
set "domainName=domain1"
goto nextstep
)
if "%domainName%" == "2" (
set "domainName=domain2"
goto nextstep
)
if "%domainName%" == "3" (
set "domainName=domain3"
goto nextstep
) else (
goto resetfile
)
:nextstep
My problem is that for 2 of the 3 domains, psexec runs. For domain1, it does not run. I echoed out the command, and it prints perfectly. When I remove echo from the command, it skips all of that and restarts the file.
nextstep is:
:nextstep
set /p userName="Enter your Admin username: "
powershell -Command $pword = read-host "Enter password " -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt
psexec \\%computerName% -u %domainName%\%userName% -p %password% cmd
:resetfile
set resetfile=
set /p resetfile="Do you want to restart this file? Press 'y' for Yes or 'n' for No then Press ENTER: "
if not '%resetfile%'=='' set resetfile=%resetfile:~0,1%
if '%resetfile%'=='y' goto start
The script does not even ask if I want to restart the script. It just loops back to :start, which is at the beginning of the script.
Please help, thank you!
Try first this with your password, to see if it's complete
setlocal EnableDelayedExpansion
set /p password=
echo my password '!password!'
If this still fails there must be a non ascii character involved.
Then you should change the codepage with chcp.
Then you can use it with your code
psexec \\%computerName% -u %domainName%\%userName% -p !password! cmd

Script to start service if not running then email results

I need to create a script which checks if a service is running and starts it if failed. Regardless of the outcome I would like an email which tells me the results. I would like this to be in a .bat file although .vbs is acceptable.
I have found various posts on how to do this. I am currently using:
set service=###
for /F "tokens=3 delims=: " %%H in ('sc query %service% ^ | findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (net start %service%)
This runs successfully and will start the service if stopped however I am getting
%%H was unexpected at this time
This causing it to register as failed on Task scheduler
The second part of the script I am using is:
for /F "tokens=3 delims=: " %%H in ('sc query %service% ^| findstr " STATE"') do (
if /I "%%H" EQ "RUNNING" (
SendMail /smtpserver localhost /to me#mydomain.com /from watchdog#mydomain.com /subject Service Autostart Notification /body Autostart on service %service% succeded.
) else (
SendMail /smtpserver localhost /to me#mydomain.com /from watchdog#mydomain.com /subject Service Autostart Notification /body Autostart on service %service% failed.
)
)
)
)
This is not sending the email as "Sendmail is not recognised as an internal or external command, operable command or batch file"
Please could someone give me assistance with this. I have tried to find solutions online but have been unsuccessful thus far.
Kind Regards
This batch file allows you to send an email with no third party software, if your IT has not locked down windows scripting host.
Change the port and SSL encryption if your email server needs it - read the first part of the batch file.
You can call the batch file like this:
CALL email.bat "myname#gmail.com" "RecipientEmailAddress#server.com" "Subject line" "Email Body in one line" "smtp.gmail.com" "myname#gmail.com" "password" "d:\folder\filename to attach.txt"
Email.bat
:: email.bat :::::::::::::::::::::::::::::::::::::::::::::::::::::
#echo off
setlocal
:: use these settings to send from a gmail account
:: set port=465 and set SSL=True
:: use these settings for standard email SMTP port and no encryption
:: set port=25 and set SSL=False
:: Change these following items to use the same variables all the time
:: or use the command line to pass all the variables
set Port=25
set SSL=False
set From="myemail#myemailserver.com"
set To="recipient#server.com"
set Subject="Subject line"
set Body="Email Body in one line"
set SMTPServer="mailservername.myemailserver.com"
set User="username"
set Pass="password"
set fileattach="d:\myfolder\file.txt"
:: This section sets the command line arguments
:: use this format: CALL email.bat "myname#gmail.com" "RecipientEmailAddress#server.com" "Subject line" "Email Body in one line" "smtp.gmail.com" "myname#gmail.com" "password" "d:\folder\filename to attach.txt"
if "%~7" NEQ "" (
set From="%~1"
set To="%~2"
set Subject="%~3"
set Body="%~4"
set SMTPServer="%~5"
set User="%~6"
set Pass="%~7"
set fileattach="%~8"
)
set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul
set cdoSchema=http://schemas.microsoft.com/cdo/configuration
echo >>"%vbsfile%" Set objArgs = WScript.Arguments
echo >>"%vbsfile%" Set objEmail = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From = %From%
echo >>"%vbsfile%" objEmail.To = %To%
echo >>"%vbsfile%" objEmail.Subject = %Subject%
echo >>"%vbsfile%" objEmail.Textbody = %body%
if exist %fileattach% echo >>"%vbsfile%" objEmail.AddAttachment %fileattach%
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendusing") = 2 ' not local, smtp
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpserver") = %SMTPServer%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpserverport") = %port%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendusername") = %user%
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendpassword") = %pass%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpusessl") = %SSL%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpconnectiontimeout") = 30
echo >>"%vbsfile%" .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send
cscript.exe /nologo "%vbsfile%"
echo email sent (if variables were correct)
del "%vbsfile%" 2>nul
goto :EOF