I am trying to share values between my batch file and embedded script within it and I can't find a way to make it work. I am relatively new to embedded scripting...
I have tried to find an answer on the web and I can't find an answer to my question. It would need to be (all the scripts) in the same .bat file...
<!-- : Begin batch script
#echo off
cls
set "Shared_UserName=VelocityDK"
goto ShareValue
:ShareValue
cls
cscript //nologo "%~f0?.wsf" //job:UserName
pause >nul
cls & exit /force
----- Begin wsf script --->
<package>
<job id="UserName">
<script language="VBScript">
Dim Shared_UserName As String = %Shared_UserName%
WScript.Echo "Your username is: " & Shared_UserName
</script>
</job>
</package>
I am expecting the embedded VBScript to write the following output: Your username is VelocityDK. but instead, I get a message saying:
Microsoft VBScript compilation error: Expected end of statement
If you plan to use shell methods inside VBScript then use Windows Scripting Host (WSH) automation object. Please find the code:
Set wshShell = CreateObject( "WScript.Shell" )
userName = wshShell.ExpandEnvironmentStrings("%Shared_UserName%")
WScript.Echo "Your username is: " & userName
See refs :devguru.com or ss64.com
Related
This thread outlines how to code batch hybrids that may include a combination of several scripting languages, such as batch, VBS, JScript, PowerShell, etc. The question is, whether a batch hybrid treats "foreign" language blocks as "functions", meaning calls to these blocks may include arguments like regular and delayed expansion batch variables, that are referenced as usual arguments like %1, %2, etc?
Example below shows the approach in the task of unzipping a file, while using this file unzip code, but it gives an error in Win10 64-bit - why? Note, the linked file unzip code gives an error as well when run in Win 10, but a different one.
<!-- : Begin batch script
#echo off
set "dir=C:\Temp\" & set "file=%USERPROFILE%\Downloads\archive.zip\"
cscript //nologo "%~f0?.wsf" "%dir%" "%file%"
exit /b
----- Begin wsf script --->
<job><script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(%1) Then
fso.CreateFolder(%1)
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip = objShell.NameSpace(%2).items
objShell.NameSpace(%1).CopyHere(FilesInZip)
set fso = Nothing
set objShell = Nothing
</script></job>
:: Error
..\test.bat?.wsf(9, 8) Microsoft VBScript compilation error: Invalid character
In vbscript the first argument is : wscript.Arguments(0)
the second argument is : wscript.Arguments(1)
So,you should write it like that :
`
----- Begin wsf script --->
<job><script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
If NOT fso.FolderExists(wscript.Arguments(0)) Then
fso.CreateFolder(wscript.Arguments(0))
End If
set objShell = CreateObject("Shell.Application")
set FilesInZip = objShell.NameSpace(wscript.Arguments(1)).items
objShell.NameSpace(wscript.Arguments(0)).CopyHere(FilesInZip)
set fso = Nothing
set objShell = Nothing
</script></job>
I'm currently making an installation script by using a .cmd file.
Here is my code:
IF EXIST "%USERPROFILE%\Desktop\Opslag\Opslag.hta" (
START "" "%USERPROFILE%\Desktop\Opslag\Opslag.lnk" /secondary /minimized
MSG "%USERNAME%" The program is already installed.
EXIT
) ELSE (
XCOPY %SOURCE% %DESTINATION% /D /E /C /R /I /K /Y
START "" "%USERPROFILE%\Desktop\Opslag\Opslag.lnk" /secondary /minimized
MSG "%USERNAME%" Setup is complete!
EXIT
)
The %SOURCE% and %DESTINATION% are set earlier in the script.
When the folder has been copied I want the file %USERPROFILE%\Desktop\Opslag\Opslag.lnk to be added to the Start Menu.
I have seen earlier posts like:
How to pin to start menu using PowerShell, but I cannot make it work.
I'm currently testing it on my home laptop which runs Windows 7 with danish language. The machine where I need to do this runs Windows 7 with english language. Therefore I think the $verb is different from the scripts I've found, but I haven't tested on my work station.
Furthermore my work station has a very limited UAC,
and therefore I do not have Administrator rights. And please do not comment on how this should not be done by users, but only Administrators/IT, as I know what I'm doing.
I hope someone can help me pin the Opslag.lnk to the Start Menu, preferably on both languages (danish and english).
Find the location of the Start Menu folder:
For /f "tokens=3*" %%G in ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Start Menu" ^|Find "REG_"') do Call Set _startmenu=%%H
echo %_startmenu%
pause
In another search I stumbled across a very usefull VBScript: http://blogs.technet.com/b/deploymentguys/archive/2009/04/08/pin-items-to-the-start-menu-or-windows-7-taskbar-via-script.aspx:
Const CSIDL_COMMON_PROGRAMS = &H17
Const CSIDL_PROGRAMS = &H2
Set objShell = CreateObject("Shell.Application")
Set objAllUsersProgramsFolder = objShell.NameSpace(CSIDL_COMMON_PROGRAMS)
strAllUsersProgramsPath = objAllUsersProgramsFolder.Self.Path
Set objFolder = objShell.Namespace(strAllUsersProgramsPath & "\Accessories")
Set objFolderItem = objFolder.ParseName("Calculator.lnk")
Set colVerbs = objFolderItem.Verbs
For Each objVerb in colVerbs
Wscript.Echo objVerb
Next
The script lists alle the verbs for the specifik program, in this case the Calculator. Unfortunately the verb "Pin to Start Menu" in my Opslag.lnk is not listed, and therefore I do not think this can be done with verbs. Hope some one else has other ideas.
I used a .vbs to do this in the current profile (and used the registry, runonce to launch the .vbs on all (new)userprofiles). We are working with both Dutch and English devices in our company so you will see that it will try both languages. The problem is that it did not work on a .lnk but you can always create an exe referring to your desired destination.
Dim strFolder, strExecutable
Set objShell = CreateObject("Shell.Application")
strFolder = "C:\Tools"
strExecutable = "Tool.exe"
Set objFolder = objShell.Namespace(strFolder)
Set objFolderItem = objFolder.ParseName(strExecutable)
Set colVerbs = objFolderItem.Verbs
'Loop through the verbs and if PIN is found then 'DoIt' (execute)
blnOptionFound = False
For Each objVerb In colVerbs
If Replace(objVerb.name, "&", "") = "Aan het menu Start vastmaken" Then
objVerb.DoIt
blnOptionFound = True
End If
Next
For Each objVerb In colVerbs
If Replace(objVerb.name, "&", "") = "Pin to Start Menu" Then
objVerb.DoIt
blnOptionFound = True
End If
Next
Have seen - Assigning newline character to a variable in a batch script
I am wanting to take a REG_MULTI_SZ and split to multiple lines..
For example, we have:
if %PROCESSOR_ARCHITECTURE% == AMD64 SET ApacheKey="HKLM\SOFTWARE\Wow6432Node\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters\Java"
if NOT %PROCESSOR_ARCHITECTURE% == AMD64 SET ApacheKey="HKLM\SOFTWARE\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters\Java"
POWERSHELL "Get-ItemProperty 'HKLM:%ApacheKey%' |select -ExpandProperty Options" >> somelog.txt
Thanks to the response below and the post found at - How to read multi line multi string registry entries in PowerShell?
as this is now working!
Please note: I cannot use vbs (well I could) but would rather not as I have to codesign my scripts.
Can break out the "\0" delimiters. The issue that I have right now is that I type in echo %SETTINGS% from the command-line and I can see the new lines.. Probably going to have to PIPE the original variable to a text file. Read in (type) the file and if the "\0" is found to echo. which should write the file properly.
The original log shows:
-Dcatalina.base=C:\tomcat\0-Dcatalina.home=C:\tomcat\0-Djava.endorsed.dirs=C:\tomcat\endorsed\0-Djava.io.tmpdir=C:\tomcat\temp\0-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\0-Djava.util.logging.config.file=C:\tomcat\conf\logging.properties\0-Dcom.sun.management.jmxremote\0-Dcom.sun.management.jmxremote.port=1092\0-Dcom.sun.management.jmxremote.ssl=false\0-Dcom.sun.management.jmxremote.authenticate=false\0-XX:MaxPermSize=256m\0-Xmx1024m\0-Xms1024m\0-Xverify:none\0-XX:+UseConcMarkSweepGC\0-XX:+UseParNewGC\0-XX:MinHeapFreeRatio=40\0-XX:MaxHeapFreeRatio=60\0-XX:MaxGCPauseMillis=200
What I want it to show is:
-Dcatalina.base=C:\tomcat
-Dcatalina.home=C:\tomcat
-Djava.endorsed.dirs=C:\tomcat\endorsed
-Djava.io.tmpdir=C:\tomcat\temp
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
-Djava.util.logging.config.file=C:\tomcat\conf\logging.properties
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=1092
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
-XX:MaxPermSize=256m
-Xmx1024m
-Xms1024m
-Xverify:none
-XX:+UseConcMarkSweepGC
-XX:+UseParNewGC
-XX:MinHeapFreeRatio=40
-XX:MaxHeapFreeRatio=60
-XX:MaxGCPauseMillis=200
It can be simple using Vbscript working with your batch script:
:: Create readMulti.vbs
(
echo/Const HKEY_LOCAL_MACHINE = ^&H80000002
echo/strComputer = "."
echo/Set oReg=GetObject^("winmgmts:{impersonationLevel=impersonate}!\\" ^& _
echo/ strComputer ^& "\root\default:StdRegProv"^)
echo/strKeyPath = "SOFTWARE\Apache Software Foundation\Procrun 2.0\tomcat6\Parameters\Java"
echo/strValueName = "Options"
echo/oReg.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath, _
echo/ strValueName,arrValues
echo/For Each strValue In arrValues
echo/ Wscript.Echo strValue
echo/Next)>readMulti.vbs
for /f "tokens=*" %%a in ('cscript //nologo readMulti.vbs') do (echo/%%a>>log.txt)
del readMulti.vbs
I created a batch file to lookup my external ip.
and it works well .
This is the code.
#echo off
>"%temp%\ip.vbs" echo Set objHTTP = CreateObject("MSXML2.XMLHTTP")
>>"%temp%\ip.vbs" echo Call objHTTP.Open("GET", "http://checkip.dyndns.org", False)
>>"%temp%\ip.vbs" echo objHTTP.Send()
>>"%temp%\ip.vbs" echo strHTML = objHTTP.ResponseText
>>"%temp%\ip.vbs" echo wscript.echo strHTML
for /f "tokens=7 delims=:<" %%a in ('cscript /nologo "%temp%\ip.vbs"') do set ip=%%a
echo %ip:~1%
pause
What i want is to Print the results to a text file named "IPlog.txt"
and every time i run the bat file it has to do the same thing and print the new results to the next line in the text file. So please can anyone help me with this.
... or change your
echo %ip:~1%
to
echo %ip:~1% >>IPlog.txt
to run your batch without the additional " >>IPlog.txt "
Please remove the pause command from your code and run the batch-file like this
mybatch.bat >> IPlog.txt
This will append the resulting ip address on to the log file IPLog.txt every time you run this batch file.
VB scripting is completely alien to me but today landed in a situation to write a small one. I need Admin rights to run my .bat file. So I am trying to elevate to Admin rights if not have them. With the help of SO and Google I reached upto:
Function Length()
Set WshShell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.length = 0 Then
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """" & " RunAsAdministrator", , "runas", 1
Else
Dim shell
set shell=createobject("wscript.shell")
shell.run "ExtractFiles.bat"
End If
End Function
Length
Here, this .vbs and ExtractFiles.bat are saved in same folder. I opened 2 command prompts. One in Admin mode and other normal. When running this script thorugh command prompt in Admin mode, I am getting success. But in normal mode, first I get a window to switch to Admin mode and I press Yes on it. Then I get below error:
Can anyone point me to correct code. I am getting error in line shell.run "ExtractFiles.bat". Please help!
As I have also mentioned the requirement, a different approach is also welcome. In this problem, I am not sure how I am able to run the bat file in admin mode and failing in normal mode.
Add the Admin VBS code into your bat file. Here is my routine for the job.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:Admin <Return> [Needed] [Success]
:: Check for Administrator privileges and request privileges if Needed 'true'.
:::: Usage: call :Admin xReturn true
:: Return success value, if user is Admin. Default `true` if Success not set.
setlocal
set "xVBUAC=%Temp%\AdminUAC.vbs"
set "xSuccess=true"
set "xAdmin=false"
if not "%~3"=="" set "xSuccess=%~3"
:: Check for Access
::net session >nul 2>&1
>nul 2>&1 "%SystemRoot%\system32\cacls.exe" "%SystemRoot%\system32\config\system"
if %ErrorLevel% EQU 0 set "xAdmin=%xSuccess%"
:: Execute UAC
if /i not "%xAdmin%"=="%xSuccess%" if not "%~2"=="" if /i "%~2"=="true" (
echo Set UAC = CreateObject^("Shell.Application"^) > "%xVBUAC%"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%xVBUAC%"
if exist "%xVBUAC%" (
"%xVBUAC%"
rem if %ErrorLevel% EQU 5 echo Access Denied. Launching UAC.
del "%xVBUAC%"
)
)
endlocal & if not "%~1"=="" set "%~1=%xAdmin%"
goto :eof
How to Use it
:: Example Admin check
#echo off
setlocal EnableExtensions
call :Admin xReturn true 1
if not "%xReturn%"=="1" goto End
:: Do my .bat stuff here.
goto End
:: TODO Place the admin function here.
:End
Depending on how you launch the VBScript the directory in which the scripts reside isn't necessarily the working directory. Try this:
Set fso = CreateObject("Scripting.FileSystemObject")
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
shell.run "%COMSPEC% /c """ & fso.BuildPath(scriptDir, "ExtractFiles.bat") & """"
What you enter in the command prompt? Is it...
InstallACS.vbs ExtractFiles.bat
Your script works just fine on XP x64 (if that important) never mind how I'll run it - from the sell or from the console, and also work with and without argument.