VBScript to execute a batch file on a remote server [closed] - batch-file

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Friends please help me with a VBscript code or a batch script or any possible way that executes a batch file on remote desktop.
I tried a lot but couldn't succeed.
Note: psexec or any other external tools are not provided.

I'd recommend a use of a batch file with psexec. Download psexec, copy/paste this into a batch file and edit the variables where needed. I use a similar process on several nightly Control-M jobs.
#ECHO OFF
REM ***** Set path to PSEXEC.exe *****
SET PSEXEC="H:\Utilities\PsTools\psexec.exe"
REM ***** Set path to batch file on remote server (unc paths work)
SET BATCHFILE="C:\path\to\batch.bat"
REM ***** Set server to execute batch on
SET REMOTESERVER="\\testserver"
REM ***** PRODUCTION SERVERS *****
ECHO Executing %BATCHFILE% on %REMOTESERVER%
%PSEXEC% %REMOTESERVER% %BATCHFILE%

I have implemented this solution by scheduling the batch files using windows scheduler and i triggered the windows scheduler to run the batch file using the below code
string job = #"""\JobLocation\JobName""";
string server = #"XXXXXXXXXXX";
string user = #"Domian\XXXXXX";
string pwd = #"XXXXXXXXXXXXXXX";
string line = #" /run /tn " + job + " /s " + server + " /u " + user + " /p " + pwd;
var process = new Process();
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = #"C:\WINDOWS\SYSTEM32\schtasks.exe",
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = line,
//WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
string output = process.StandardOutput.ReadLine();
string errors = process.StandardError.ReadLine();

Related

Automate WinSCP to get listing of files in remote directory

I've read a lot about automating WinSCP, but some of it I had trouble understanding because it presumed knowledge of other things, like .NET assembly, PowerShell, etc.
I'm wondering if, speaking strictly in VBScript and batch file file type of lingo, once I've downloaded the portable winscp.exe, how to simply open a remote site, give a user name and password, and download a list of the files in a particular directory. FTP protocol only.
There's an example for using the Session.ListDirectory from VBScript:
<job>
<reference object="WinSCP.Session"/>
<script language="VBScript">
Option Explicit
' Setup session options
Dim sessionOptions
Set sessionOptions = WScript.CreateObject("WinSCP.SessionOptions")
With sessionOptions
.Protocol = Protocol_Ftp
.HostName = "ftp.example.com"
.UserName = "user"
.Password = "mypassword"
End With
Dim session
Set session = WScript.CreateObject("WinSCP.Session")
' Connect
session.Open sessionOptions
Dim directoryInfo
Set directoryInfo = session.ListDirectory("/remote/path")
Dim fileInfo
For Each fileInfo In directoryInfo.Files
WScript.Echo fileInfo.Name & " with size " & fileInfo.Length & _
", permissions " & fileInfo.FilePermissions & _
" and last modification at " & fileInfo.LastWriteTime
Next
' Disconnect, clean up
session.Dispose
</script>
</job>
Other than that:
download the WinSCP .NET assembly package and extract it along with the script.
register the assembly for COM. Typically like:
%WINDIR%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe WinSCPnet.dll /codebase /tlb:WinSCPnet32.tlb
%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe WinSCPnet.dll /codebase /tlb:WinSCPnet64.tlb
Run the script (list.wsf) like:
cscript list.wsf
You can of course also just run winscp.com scripting like:
Set shell = CreateObject("WScript.Shell")
Set exec = shell.Exec("winscp.com /command ""open ftp://username:password#ftp.example.com/"" ""ls /remote/path"" ""exit""")
WScript.Echo(exec.StdOut.ReadAll())
For more details on this approach see guide to advanced FTP scripting from VB script.

Calling SVN post-lock only once

I've been trying to write a post-lock hook for my VisualSVN server on Windows, using batch files and VBS scripts. The end goal is to have the hook email a list of all the locked files to a collection of email addresses. However, the hook is called for every file. I'm hoping there's a way around this, or a clever way of waiting for all the information before sending the email. Also, I want a list of all the files, but currently only the repo path is passed in. I know the file paths are passed via stdin, but I haven't found a way to get that into a string to be passed to my VBS file. Any help would be great.
Batch File:
#echo off
pushd %~dp0
cscript email-bat.vbs %2 LOCKED %1
#pause 5
VBS:
Set emailObj = CreateObject("CDO.Message")
Set args = WScript.Arguments
emailObj.From = "mymail#gmail.com"
emailObj.To = "tomail#gmail.com"
emailObj.Subject = "SVN " + args.Item(1)
emailObj.TextBody = args.Item(0) + " has " + args.Item(1) + " the file(s) " + args.Item(2) + "."
Set emailConfig = emailObj.Configuration
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mymail#gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
emailConfig.Fields.Update
emailObj.Send

How do I execute SQL commands using a batch (.bat) file without accessing external SQL?

Is it possible to execute SQL commands written in a batch (.bat) file without accessing an external SQL script file. How can I do that? I don't want to call an external sql because i want to require as input a month, then execute the sql command that contains that month in some queries.
Asuume you have 3 files in your folder.
file 1 => .sql file
file 2 => mybatchfile1.bat(which has sqlcmds or cmd to execute the above .sql file)
file 3 => one other batch file(myexecute.bat) to call the above batch file(which has content "start mybatchfile1.bat")
All you need to create is myexecute.bat with the below content:
start mybatchfile1.bat
or
call mybatchfile1.bat
You can use either start or call.
Recomend on using powershell script:
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "SERVER\Instance" -Password "Password"
the output will be orginized as a Table and it's far more easy then bat file
Yes, you can run a query from a single DOS batch script, getting input from command line parameters and/or user prompts, rather easily. SQLCMD allows for passing in a query on the command line. By the very nature of passing something into a program from the command line, you can just place the DOS variable wherever you want it to go.
Place the following into a script with an extension of .cmd (you should not be using the .bat extension unless you have a specific need for something to run in a 16-bit process):
#ECHO OFF
ECHO.
SET /P Month="Please enter in a month: "
ECHO.
ECHO.
ECHO Month = %Month%
ECHO.
SET Month=%Month:'=%
ECHO Month with single-quotes removed = %Month%
ECHO.
SQLCMD.EXE -E -Q "IF (COALESCE(TRY_CONVERT(TINYINT, REPLACE('%Month%', '''', '''''')), 0) NOT BETWEEN 1 AND 12) BEGIN RAISERROR('Please enter a value 1 - 12.', 16, 1); RETURN; END; SELECT DATENAME(MONTH, '2014-%Month%-01') AS [MonthName];"
Run it without passing in any parameters. It will prompt for the month. It will then substitute that value in the query, which does its own data validation on the input.
NOTE: be sure to validate input to protect against SQL Injection. The above example replaces single-quotes with escaped-single-quotes for this reason. It also removes all single-quotes before the variable is even used in the query so the REPLACE() is just a redundant safety.
C:\>.\SingleScriptToAcceptParamForQuery.cmd
Please enter in a month: '5
Month = '5
Month with single-quotes removed = 5
MonthName
------------------------------
May
(1 rows affected)

Launch PL/SQL script from batch file (with arguments)

I'm strugling at passing arguments to a PL/SQL script from a Windows .bat file.
Here is the content of the batch file :
#echo off
set mName = "test"
exit | sqlplus <connection_string> #test.sql %mName%
pause
And here is the content of test.sql :
set verify off
set serveroutput on size unlimited
BEGIN
DBMS_OUTPUT.PUT_LINE('&&1');
END;
/
I would expect to see "test" appearing in the shell but instead, I get the following message :
Enter value for 1:
SP2-0546: User requested Interrupt or EOF detected.
Does anyone have a solution to this problem ?
Remove the spaces around your = sign. Here's my working batch file:
#echo off
set mName="test"
exit | sqlplus <connection_string> #test.sql %mName%
pause
Also note that you can use the -L option on sqlplus for batch jobs:
-L Attempts to log on just once, instead of reprompting on error.

Creating a shortcut for a exe using a batch file

I know a topic already exists like that but I do not want to use a VB script.
I would hope you can create a shortcut using a command line in DOS.
Please post some example that would be great.
Thanks!
AA
You can't create a shortcut in a .bat file without invoking an external program.
However, every version of Windows since Win2k has a built in scripting language called Windows Script Host
Here is a small WSH script that I wrote a few years ago that can be called from a .bat file,
just save this text as shortcut.wsf, it contains useage information in the script.
<package>
<job id="MakeShortcut">
<runtime>
<description>Create a shortcut (.lnk) file.</description>
<named
name = "Target"
helpstring = "the target script"
type = "string"
required = "true"
/>
<named
name = "Args"
helpstring = "arguments to pass to the script"
type = "string"
required = "false"
/>
<unnamed
name = "basename"
helpstring = "basename of the lnk file to create"
type = "string"
required = "false"
/>
</runtime>
<script language="JScript">
if ( ! WScript.Arguments.Named.Exists("Target"))
{
WScript.Arguments.ShowUsage();
WScript.Quit(2);
}
target = WScript.Arguments.Named.Item("Target");
WScript.Echo("target " + target);
args = WScript.Arguments.Named.Item("Args");
WScript.Echo("args " + args);
base = WScript.Arguments.Unnamed.Item(0);
WScript.Echo("base " + base);
fso = WScript.CreateObject("Scripting.FileSystemObject");
//path = fso.GetParentFolderName(WScript.ScriptFullName);
path = fso.GetAbsolutePathName(".");
WScript.Echo("path = " + path);
Shell = WScript.CreateObject("WScript.Shell");
short = fso.BuildPath(path,base);
if ( ! fso.GetExtensionName(base))
short = short + ".lnk";
link = Shell.CreateShortcut(short);
link.TargetPath = fso.BuildPath(path, target);
if (args != null && args != "")
link.Arguments = args;
else
link.Arguments = base;
//link.Description = "Sound Forge script link";
//link.HotKey = "ALT+CTRL+F";
//link.IconLocation = fso.BuildPath(path, target) + ", 2";
//link.WindowStyle = "1"
//link.WorkingDirectory = path;
link.Save();
</script>
</job>
</package>
run it without any arguments to get useage
c:\> shortcut.wsf
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Create a shortcut (.lnk) file.
Usage: shortcut.wsf /Target:value [/Args:value] [basename]
Options:
Target : the target script
Args : arguments to pass to the script
basename : basename of the lnk file to create
mklink /D c:\vim "C:\Program Files (x86)\Vim"
More Info Here
And Cygwin's ln - s
http://en.wikipedia.org/wiki/Symbolic_link#Cygwin_symbolic_links
Creating a shortcut in the .lnk format is basically impossible from a batch file without calling an external program of some kind. The file spec can be found here, and a quick glace will explain.
Creating a .url format shortcut is quite easy as the format is a simple text file. The spec can be found here. This format has a few disadvantages, but may accomplish your goal.
you can get shortcut.exe from the resource kit.
It can now be done with Powershell, which arguably sucks somewhat less than VBscript. And powershell can be called from a .bat / .cmd file:
powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Desktop\mylink.lnk'); $s.TargetPath='C:\Path\to\your.exe'; $s.Save()"
See also here for another example: https://ss64.com/nt/shortcut.html#e
See also

Resources