Passing Caret to command line using VBScript - vbscript

Having a hard time figuring this one out. I have a vbscript that asks for username and password. Then the script runs PSExec.exe passing those to the command line like this.
strUser = Inputbox("Username:","Username")
strPassword = Inputbox("Password:","Password")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /K psexec.exe \\workstation -u " & struser _
& " -p " & strPassword & " -d calc.exe", 1, false
This works fine if the password doesn't have a caret in it. BUT if it does have one, for example if the password is "Pass)(*&^%$##!" I get the following error from psexec.
'%$##!' is not recognized as an internal or external command,
operable program or batch file.
The caret is being read by the command line as a space so it thinks it's trying to run this command.
psexec.exe \\workstation64 -u User -p Pass)(*& %$##! -d Calc.exe
As you can see there is a space instead of a caret so psexec see's %$##! as the command.
I've seen an example for passing it when using a batch file but it doesn't work in this case. It said adding an extra ^ like this ^^ works in a bat file.
How can I pass a caret to the command line????
UPDATE......
I worked on this for about 45 minutes today at work and couldn't get it to work. First thing I tried was to add quotes to the password and it still didn't work. I just tested it here at the house and it worked fine....... OS at work is Windows XP and at home I run Windows 7. I will try again in the morning to make sure I didn't mistype something. Here is what I did to make it work at home on Windows 7.
strUser = Inputbox("Username:","Username")
strPassword = Inputbox("Password:","Password")
strPassword = chr(34) & strPassword & chr(34)
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /K psexec.exe \\workstation -u " & struser _
& " -p " & strPassword & " -d calc.exe", 1, false

The problem lays in using of ampersand, not caret: single ampersand is used as a command separator, so rest of the line after &-sign considered to be a next command by cmd interpreter.
In next example I have used SET command instead of PSExec, as I will not experiment with PSExec.
All goes well with SET command, even if escaped all characters:), but I'm not sure about percentage sign, which is said "must be doubled to use literally".
Dim strPssw: strPssw = "/Pass"")=(*&^%$##!"
Dim ii, strChar, strEscape
Dim strPassword: strPassword = ""
For ii = 1 To Len( strPssw) 'cannot use Replace() function
strChar = Mid( strPssw, ii, 1)
Select Case strChar
Case "&", """", "^", "%", "=", _
"#", "(", ")", "!", "*", "?", _
".", "\", "|", ">", "<", "/"
strEscape = "^"
Case Else
strEscape = "" 'all goes well even if strEscape = "^" here
End Select
strPassword = strPassword & strEscape & strChar
Next
Dim objShell: Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /C set varia=" & strPassword & "&set varia&pause&set varia=", 1, false
' # - At Symbol: be less verbose
' & - Single Ampersand: used as a command separator
' ^ - Caret: general escape character in batch
' " - Double Quote: surrounding a string in double quotes escapes all of the characters contained within it
' () - Parentheses: used to make "code blocks" of grouped commands
' % - Percentage Sign: are used to mark some variables, must be doubled to use literally
' ! - Exclamation Mark: to mark delayed expansion environment variables !variable!
' * - Asterisk: wildcard matches any number or any characters
' ? - Question Mark: matches any single character
' . - Single dot: represents the current directory
' \ - Backslash: represent the root directory of a drive dir ^\
' | - Single Pipe: redirects the std.output of one command into the std.input of another
' > - Single Greater Than: redirects output to either a file or file like device
' < - Less Than: redirect the contents of a file to the std.input of a command
''
' && - Double Ampersand: conditional command separator (if errorlevel 0)
' .. - Double dot: represents the parent directory of the current directory
' || - Double Pipe: conditional command separator (if errorlevel > 0)
' :: - Double Colon: alternative to "rem" for comments outside of code blocks
' >> - Double Greater than: output will be added to the very end of the file
' thanks to http://judago.webs.com/batchoperators.htm
'

Related

WScript.Shell seems to be ignoring escaped quotes [duplicate]

This question already has an answer here:
Filename string space issue in VBScript
(1 answer)
Closed 5 years ago.
In the following script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%comspec% /k" & _
" ""C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TF.exe"" " & _
"move ""C:\Automation\Custom_UiPath_Activities\NuPackages\*.nupkg"" ""C:\Automation\Custom_UiPath_Activities\NuPackages\Old""", 1, True
it gives the error
'C:\Program' is not recognized as an internal or external command.
Seemingly because the escaped quotes around the first argument is ignored.
I've tried logging the string to a text file, and when copying the outputted string into CMD it works as intended.
I cannot see what I have done wrong.
If you want to daisy-chain commands in CMD you need to put an ampersand (&) between them as part of the commandline. Your code is using the ampersand just as the VBScript string concatenation operator. Also, for running multiple commands via cmd /k (or cmd /c) you need to put an additional set of double quotes around them. Also, using variables and a quoting function helps with keeping your code readable.
Function qq(s) : qq = """" & s & """" : End Function
tf = "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TF.exe"
src = "C:\Automation\Custom_UiPath_Activities\NuPackages"
dst = "C:\Automation\Custom_UiPath_Activities\NuPackages\Old"
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "%comspec% /k """ & qq(tf) & " & " & _
"move " & qq(src & "\*.nupkg") & " " & qq(dst) & """", 1, True

Run Rscript.exe with VBScript and spaces in path

I have the followaing run.vbs script
Rexe = "R-Portable\App\R-Portable\bin\Rscript.exe"
Ropts = "--no-save --no-environ --no-init-file --no-restore --no-Rconsole "
RScriptFile = "runShinyApp.R"
Outfile = "ShinyApp.log"
startChrome = "GoogleChromePortable\App\Chrome-bin\chrome.exe --app=http://127.0.0.1:9999"
strCommand = Rexe & " " & Ropts & " " & RScriptFile & " 1> " & Outfile & " 2>&1"
intWindowStyle = 0 ' Hide the window and activate another window.'
bWaitOnReturn = False ' continue running script after launching R '
' the following is a Sub call, so no parentheses around arguments'
CreateObject("Wscript.Shell").Run strCommand, intWindowStyle, bWaitOnReturn
WScript.Sleep 1000
CreateObject("Wscript.Shell").Run startChrome, intWindowStyle, bWaitOnReturn
It works pretty well in most cases except when the user puts the run.vbs script in a folder with spaces in its name: e.g. if run.vbs is in folder "foo bar", the user gets the error : "C:\Users\[user name]\Desktop\foo" not recognized as internal command...
I don't understand why Rscript.exe looks for the absolute path before running even if it's called from its parent directory using relative path.
I heard about the double quote solution using the absolute path but it doesn't seem to work with .exe scripts (it does though with .bat and .cmd)
Thanks for any help!
Below code will help you
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec("C:\Program Files\R\R-3.2.3\bin\Rscript.exe C:\subfolder\YourScript.R " & """" & var1 & """")
Set oOutput = oExec.StdOut
handle the results as they are written to and read from the StdOut object
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend

How to execute shell command without double Quotes

I need to execute the below command in command prompt using vb6,
quser /server:machinename
So my code is,
mycommand = "quser / server: & strString" 'where strstring will be my machine name..
Shell "cmd.exe" & mycommand
The problem is it is executing in command prompt with the double quotes. But if double quotes is there, I wont get the expected results. I need to execute the above without double quotes.
Please let me know your comments.
You can use double double quotes to encode a double quote in a vb6 string.
e.g.
Dim str as String
str = "This is some text with a " & """double quote""" & "in it."
MsgBox str
Will show a message: This is some text with a "double quote" in it.
This is what I think you want:
mycommand = """quser / server:" & strString & """"
Shell "cmd.exe " & mycommand
Note that you did not have a space after cmd.exe
The first problem I can see is that your last double quote is in the wrong place and so
mycommand is just the string "quser / server: & strString".
To append the value of a variable called strString to the end of the string you would use
mycommand = "quser / server:" & strString
The next problem is that there needs to be a space between cmd.exe and the parameters string.
Either replace "quser... with " quser... or replace "cmd.exe" with "cmd.exe "

VBScript Carriage Returns

I write the following VB script in order to run commands from WIN XP on Linux machine and redirect the output command to out.txt file ( under C:\ )
My VB script I print the /etc/hosts file from Linux machine in to out.txt file
Script works fine but I have one problem:
/etc/hosts file was printed in out.txt file with one long line , in place of three lines
Example: (out.txt)
127.0.0.1 localhost 19.20.183.99 MY_IP 10.10.10.10 LOOP
In place to print the following host file in out.txt
127.0.0.1 localhost
19.20.183.99 MY_IP
10.10.10.10 LOOP
MY VB script
Const TARGET_HOST = "19.20.183.99"
const PATH = "cat /etc/hosts"
const LOGIN = "root"
const PASS = " dgdgd "
Const PLINKPATH="""C:\dir1\plink.exe"""
Set Sh = CreateObject("WScript.Shell")
CMD = " echo y | " & PLINKPATH & " -ssh -pw " & PASS & LOGIN & "#" & TARGET_HOST & " " & PATH
Sh.Run "cmd /k" & CMD & " > ""C:\out.txt""" , 1, True
Please advice what I need to fix in my VB script in order to print the correct hosts file ( line by line ) and not as one long line ?
Try to do a replace of lf (line feed) for lf and cr (carriage return). Linux only has LFs, where windows also requires the carriage return to show the extra line.
Alternatively, open the file in Notepad++ and you'll notice that the lines are printed line by line. (http://notepad-plus-plus.org/download/v6.4.5.html)
EDIT:
Try the following after you outputted the file to replace the line feeds (reference: link):
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\out.txt", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, chr(10), chr(13) & chr(10))
Set objFile = objFSO.OpenTextFile("C:\out.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

VBscript Robocopy Syntax

I am having a problem with what I think is a syntax error in VBscript regarding running robocopy.
The following is a code snippet of what I now using to try to run robocopy:
Dim Command2
sLocalDestinationPath = "C:\Script\files\outzips\"
sFinalDestinationPath = "C:\CopyTestFolder\"
Command2 = "Robocopy.exe " & sLocalDestinationPath & " " & sFinalDestinationPath
The thing is that the command does not produce any errors, but it also does not copy any files from the local path to the final path. It runs perfectly fine when executed from the command line. Any help would be greatly appreciated because this simple command is keeping me from finishing the rest of this script.
I also have it echoing out the command and the command matches exactly what I put in the command line.
Thank you, if you need anymore explanation just let me know.
You don't say how you are trying to 'run' Robocopy, but I presume it is via WScript.Shell.Run().
I don't happen to have Robocopy handy, but I did work up an example using Windows XCopy. Perhaps you can adapt my simple XCopy example to gain more insight into your problem with Robocopy.
Option Explicit
' XCOPY doesn't Like trailing slashes in folder names
Const sLocalDestinationPath = "C:\Script\files\outzips"
Const sFinalDestinationPath = "C:\CopyTestFolder"
Dim Command2 : Command2 = _
"XCOPY" _
& " " & sLocalDestinationPath _
& " " & sFinalDestinationPath _
& " /E /I /Y" _
& ""
Dim oSh : Set oSh = CreateObject("WScript.Shell")
WScript.Echo "Cmd: [" & Command2 & "]"
On Error Resume Next
Dim nRetVal : nRetval = oSh.Run(Command2, 0, True)
If Err Then
WScript.Echo "An exception occurred:" _
& vbNewLine & "Number: [" & Hex(Err.Number) & "]" _
& vbNewLine & "Description: [" & Err.Description & "]" _
& ""
Else
If nRetVal Then
WScript.Echo "Copy error: [" & nRetVal & "]"
Else
WScript.Echo "Copy succeeded."
End If
End If
Set oSh = Nothing
' XCOPY options:
'
' /E Copies directories and subdirectories, including empty ones.
' Same as /S /E. May be used to modify /T.
'
' /I If destination does not exist and copying more than one file,
' assumes that destination must be a directory.
'
' /Y Suppresses prompting to confirm you want to overwrite an
' existing destination file.
' End

Resources