VBScript msgbox with NL [closed] - vbscript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the following code that displays a MsgBox using two env variables:
Set wshShell = CreateObject("WScript.Shell")
Title = wshShell.ExpandEnvironmentStrings("%Title%")
Text = wshShell.ExpandEnvironmentStrings("%Text%")
x = MsgBox(Text, 4144, Title)
Whilst the code works I wish t have a new line character in the message. I have read the following which discusses this scenario:
How to use \n new line in VB msgbox() ...?
However when I sen the env variable to the following it is displayed literally.
"This is the first line" & vbCrLf & "and this is the second line"
Just in case the code above is unclear...
The env variables %Title% and %Text% are set with values like in these batch statements:
set Title="This is a title"
set Text="This is the first line" & vbCrLf & "and this is the second line"
The code reads and displays these env variables in a message box.

The expanded environment string is still a string, so VBScript doesn't evaluate it as VBScript code without you telling it to do so.
x = MsgBox(Eval(Text), 4144, Eval(Title))
However, Eval is evil and should be avoided.
A better approach would be to define your environment variables using a placeholder for the newlines (e.g. \n) and then replace the placeholders with actual newlines:
x = MsgBox(Replace(Text, "\n", vbNewLine), 4144, Replace(Title, "\n", vbNewLine))

Related

How do I prevent zsh from replacing "%5D" with "]"?

[EDIT] Solved.
The actual issue was a typo in one of the handler variables, and not a zsh issue, as I initially thought.
I am trying to prevent zsh from replacing the code "%5D" for the ] right square bracket with the actual character "]".
For my purposes - calling the last.fm API via curl in shell script, to get info about a track from Apple Music - it needs to stay as "%5D", because otherwise the API doesn't recognise it.
I have tried escaping the "%5D" with backslashes or a second "%" but that doesn't work, it still gets replaced with "]"
Here's an example of what I'm trying to do and what is not working:
The original string of the track's name:
"YESTODAY (Extended Version) [Bonus Track]"
How it needs to be spelled for the API to work:
"YESTODAY+(Extended+Version)+%5BBonus+Track%5D"
The whitespaces get replaced with "+" by my AppleScript handler.
The left [ stays as "%5B" (I guess because it is immediately followed by more letters and therefore zsh cannot recognise it as code and replace it).
The right ] is generally the last character of the track string, not followed by anything and thus "%5D" is recognised by zsh and written as "]" .
How do I fix this?
Any help is greatly appreciated :)
For reference:
The part of the AppleScript that is supposed to replace the "[ ]" with code.
(This is obviously not the complete script). If you run this, it replaces the [ ] correctly. The issue only arises once the entire API call is made with do shell script curl_command because of zsh interpreting the code.
set trackreplace to "YESTODAY (Extended Version) [Bonus Track]"
if trackreplace contains "[" then
set trackreplace to replaceChars("[", "%5B", trackreplace)
end if
if trackreplace contains "]" then
set trackeplace to replaceChars("]", "%5D", trackreplace)
end if
on replaceChars(find, replace, subject)
set savedelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to find
set subject to text items of subject
set AppleScript's text item delimiters to replace
set subject to (subject as string)
set AppleScript's text item delimiters to savedelims
return subject
end replaceChars
It was not a zsh issue but actually just a typo in one of the handler variables (trackeplace instead of trackreplace), as pointed out by #GordonDavisson

How to pass double quoted arguments into vbscript?

I am a new bee for vbScript. I have a script that I am calling with an arguments which contains double quote. Following is the call
.vbs "a" 2 where variable a is JO"N
My VbScript:
If WScript.Arguments.Count > 0 Then
MsgBox "NAME:" + WScript.Arguments.Item(0)
MsgBox "NAME:" + WScript.Arguments.Item(1)
Else
MsgBox "Please pass a parameter to this script"
End if
*Note this works when a = JON but does not work when a= JO"N. I tried putting escape characters" (Example: "WScript.Arguments.Item(0)") but it does not work.
You can't.
At least, as the WScript argument parser handles and removes all quotes from the values in Arguments collection, you can not use the default argument handling for this task.
note: And we are leaving out of the problem if the final command you are running when calling your script (you have not included how/from where you make the call) will or not have problems because the additional quote interferes argument quoting rules.
You need to use some workaround to get the double quote to reach the script. Some approachs could be:
Replace the quote and any other problematic character (use some kind of escape sequence) before calling the script and revert the process inside your script.
Save the value you want to pass into an environment variable (how to make it depends on how you are callign the script) and then retrieve the value from your script (ex. here).
Use WMI to retrieve the full command line used to start the script, including all the quotes (ex. here) and write your own argument parser routine.
From my point of view, I would use the second option.
This will work: Chr(34) & Wscript.Arguments.Item(0) & Chr(34). Here Chr(34) function returns a double quote using its ASCII code 34.

How to prepend batch variable to filename on set of other variable? [duplicate]

This question already has answers here:
Why is no string output with 'echo %var%' after using 'set var = text' command in cmd? [duplicate]
(2 answers)
Closed 5 years ago.
Code first:
ECHO off
SET home = c:\Cygwin\home\ian
SET update_log = %home%\update.txt
^^^^^^
Is there a way to prepend the %home% variable in the initialization of update_log variable as in the example shown above?
Spaces on the left side of the equal sign are included in the variable name.
Spaces on the right side of the equal sign are included in the variable value.
If the spaces in these places are not a requirement, don't use them
SET "home=c:\Cygwin\home\ian"
SET "update_log=%home%\update.txt"
Also, it is recomended to quote the assignments to prevent problems with special characters and to avoid the inclusion of spaces at the end of the value.
Exactly as you have it, except batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"
The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".
So - remove the spaces

Visual Basic find and replace any " not followed or proceeded by a comma with ""

I want to write a vb or bat script that goes through a file and finds and replaces any quotation mark not followed or proceeded by a comma with a double quote.
Edit: solved
Ok so I got it I needed to use back references.
Incase anyone else needs something similar here is a little example script replacing " not followed or proceed by a comma with Doubleqoute
dim rp, file
set re = new RegExp
re.Pattern="([^,])("")([^,])"
re.Global=True
s="It is alive ""IT IS ALIVE"","
MsgBox re.Replace(s,"$1 DoubleQuote $3")
Ok so I got it I needed to use back references.
Incase anyone else needs something similar here is a little example script replacing " not followed or proceed by a comma with Doubleqoute
dim rp, file
set re = new RegExp
re.Pattern="([^,])("")([^,])"
re.Global=True
s="It is alive ""IT IS ALIVE"","
MsgBox re.Replace(s,"$1 DoubleQuote $3")
EDIT: Also the above does not work with one letter words in order to make it work with one letter you have to use look forward and look back functions.

Is there an equivalent to 'cut -c' in Windows cmd.exe?

I have some files of fixed line size, fixed field size that I need to extract information from. Nornmally, I'd use Cygwin (cut et al), but that's not an option in this case due to (boneheaded) management policies I can't change. It has to be done using standard XP toolset included with Windows.
I need to extract the 10 characters at offset 7 and 4 characters at offset 22 (zero-based), and output them to a file but with a slight twist:
The first field may have a negative, positive, or no sign (at the start or end). The sign should be moved to the front, or removed totally if it's positive.
The second field should have leading and trailing spaces removed.
For example:
1 2 3 <- ignore (these lines not in file,)
0123456789012345678901234567890123456789 <- ignore ( here only for info.)
xxxxxxx 15.22-yyyyyABCDzzzzzzzzzzz...
xxxxxxx 122.00+yyyyy XX zzzzzzzzzzz...
xxxxxxx 9yyyyyYYY zzzzzzzzzzz...
should produce (< indicates end of line):
-15.22,ABCD<
122.00,XX<
9,YYY<
If you working with modern windows, you are not restricted to cmd.exe commands natively, you can use vbscript. If your policy is not to use vbscript either, then I guess you should sack your management :)
Set objFS=CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
strFirstLine = objFile.ReadLine
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
var1 = Mid(strLine,10) ' do substring from position 10 onwards
' var2 = Mid (strLine,<pos>,<length>) ' get next offset and save to var2
WScript.Echo var1 & var2 ' print them out.
Loop
Basically, to "cut" characters of a string, you use Mid() function. please look at the vbscript documentation to find out more.
Save the above as test.vbs and, on the command line, do
c:\test> cscript /nologo test.vbs > newfile
Of course, "substring" can also be done with pure cmd.exe but I will leave it to some others to guide you.
Update by Pax: Based on this answer, I came up with the following which will be a good start:
option explicit
dim objFs, objFile, strLine, value1, value2
if wscript.arguments.count < 1 then
wscript.echo "Usage: process <input-file>"
wscript.quit
end if
set objFs=createObject("Scripting.FileSystemObject")
set objFile = objFs.openTextFile(wscript.arguments.item(0))
do until objFile.atEndOfStream
strLine= objFile.readLine
value1 = trim(mid(strLine, 8, 10))
value2 = trim(mid(strLine, 23, 4))
if right(value1,1) = "-" then value1 = "-" & left(value1,len(value1)-1)
if right(value1,1) = "+" then value1 = left(value1,len(value1)-1)
if left(value1,1) = "+" then value1 = mid(value1,2)
wscript.echo value1 & "," & value2
loop
This matches all the requirements we had. We can make the offsets and lengths into command-line arguments later.
End update.
This site has some pointers on how to extract substrings in cmd.exe: http://www.dostips.com/DtTipsStringManipulation.php
That site suggests that you can use
%varname:~2,3%
to subscript a variable. This seems to fill your needs, except you now have to get each line into a variable.
Next you want to look at the ghastly for loop syntax and if and branching (you can goto :labels in batch).
This stuff is all rather ugly, but if you really have to go there...
Here is a page in SO on looping through files and doing stuff to them: How do you loop through each line in a text file using a windows batch file?
Here's a small script (needs to be in a BAT/CMD file) expanding on what Daren Thomas suggested:
#echo off
setlocal
set key=HKCU\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{D27CDB6E-AE6D-11CF-96B8-444553540000}\iexplore\AllowedDomains
echo.
echo Liste der fuer Flash im IE zugelassenen Domaenen:
echo =================================================
for /f "usebackq tokens=11 delims=\" %%l in (`call reg query "%key%" /s`) do echo. %%l
echo.
endlocal
The FOR loop is the central part. Note the use of command modifiers in double quotes. I specify tokens=11 because I'm only interested in the subkeys of AllowedDomains, which is at position 10.
Be sure to read the help in for /?. Daren is right when he says this stuff is all rather ugly. And it easily breaks down on modification. There's a lot of non-intuitive subtleties with cmd.exe script syntax.
By the way, the GUID is the COM class ID for the Shockwave Flash Add-on. It's been around since at least 2001 so might well continue to be relevant for the foreseeable future. The purpose of the script is to list the domains where Flash, which I prefer to block by default, has been allowed.

Resources