Enable Logs in script - vbscript

I am new in scripting, I wrote below script to create folders on multiple computers and I need to create log file which show success and failure status of task.
Can some one help me.
Script :
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\CL_Repair\Computers.txt")
Do Until objFile.AtEndOfStream
strComputer = objFile.ReadLine
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
errReturn = objWMIService.Create _
("cmd.exe /c md c:\CL_Repair", Null, Null, intProcessID)
Loop
MsgBox("Folder = CL_Repair Created on Computers")

I think this is what you are looking for.. I have worked with Bill Stewart many years ago on some scripting items and he is a reliable resource..
http://social.technet.microsoft.com/Forums/windows/en-US/52873f35-5d55-498c-949e-da8ceb1df980/vbscript-write-error-to-log-file
Two items of notice:
On Error Resume Next
Is a line you would need to add to your VBScript.
Setup a batch file to run:
#echo off
ECHO %COMPUTERNAME% >> C:\Scripts\errors.txt
cscript C:\Scripts\myScript.vbs 2>> C:\Scripts\errors.txt
Now, this should trap issues seen and should log for you.
Ok.. You asked to have a list (text) list of servers.. Try something like this.. You really don't need the VBScript to do this..
:: http://www.robvanderwoude.com/files/servers_nt.txt
:: Check all servers in the list
FOR /F "tokens=*" %%A IN ('TYPE servers.txt') DO (
ECHO %%A >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\. ECHO CREATING FOLDER \\%%A\c$\CL_Repair >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\. MD \\%%A\c$\CL_Repair
IF NOT EXIST \\%%A\c$\CL_Repair\somefile.exe ECHO copying somefile.exe \\%%A\c$\CL_Repair >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\somefile.exe copy c:\CL_Repair\somefile.exe \\%%A\c$\CL_Repair
IF NOT EXIST \\%%A\c$\CL_Repair\anotherfile.bat ECHO copying anotherfile.bat \\%%A\c$\CL_Repair >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\anotherfile.bat copy c:\CL_Repair\anotherfile.bat \\%%A\c$\CL_Repair)
GOTO End
:END
EXIT

Related

How can I write a config file from batch script using vbscript variables in output redirect

In a bash script I write for creating a config file for dosbox, I can define the Current Resolution:
#!/bin/bash
#
if [ "$Resolucion" = "1152x864" ]; then
windowresolution=$(echo windowresolution=1024x768)
scaler=$(echo scaler=2xsai)
fi
Full script is available here.
In bash I can make
echo '
Line 1
Line 2
Line with Varible 1 fullResolution='"$Resolucion"'
Line with Varible 2 '"$windowresolution"'
Line with Varible 3 '"$output"'
Line with Varible 4 '"$scaler"'
Lines :
#echo off
mount c '"$Ruta_Actual/.$Titulo"'
c:
'"$Ejecutable"'
exit' | tee "$PWD/dosbox.conf" &> /dev/null
Now I need to do the same in a batch script, but I don't know how make batch + VBScript working.
I wrote the following for testing purposes:
#echo off
setlocal enabledelayedexpansion
color A
title BattleChess
set DIR="%CD%"
set PWD=%CD%\Juegos\Inukaze\BattleChess
set TITULO="BattleChess"
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo strComputer = "." >> %SCRIPT%
echo Set objWMIService = GetObject("winmgmts:" _ >> %SCRIPT%
echo & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") >> %SCRIPT%
echo Set colItems = objWMIService.ExecQuery("Select * from Win32_DesktopMonitor") >> %SCRIPT%
cscript /nologo %SCRIPT%
for /F %%* in (%SCRIPT%) do set RES=%%A
echo %RES% >> %CD%\RES.TXT
The RES.TXT just have a %A in it, but I can get the current resolution with this VBScript:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_DesktopMonitor")
For Each objItem in colItems
msgbox( "Current Resolution : " & objItem.ScreenWidth & "x" & objItem.ScreenHeight)
Next
However, I don't know how to make a file %CD%\dosbox.conf with multiples lines and using the "Current Resolution" from VBScript.
The lines of VBScript show me an error.
The Error :
""{impersonationLevel=impersonate}\\"" is not recognized as an internal or external command, program or batch file.
"strComputer" is not recognized as an internal or external command,
program or batch file.
The system can not find the path specified.
Well i dont know how to export the script .
But the answer :
for /F %%A in (
'wmic desktopmonitor get ScreenHeight^,ScreenWidth /value ^| find "="'
) do set "%%A"
set "RES=%ScreenWidth%x%ScreenHeight%"
echo %RES%
That solves that for me.
OK, this almost ready, I just need to know how I can make the following from bash script:
# Resolutions 4:3
if [ "$Resolucion" = "640x480" ]; then
windowresolution=$(echo windowresolution=512x384)
scaler=$(echo scaler=2xsai)
fi
if [ "$Resolucion" = "800x600" ]; then
windowresolution=$(echo windowresolution=640x480)
scaler=$(echo scaler=2xsai)
fi
if [ "$Resolucion" = "1024x768" ]; then
windowresolution=$(echo windowresolution=800x600)
scaler=$(echo scaler=2xsai)
fi
if [ "$Resolucion" = "1152x864" ]; then
windowresolution=$(echo windowresolution=1024x768)
scaler=$(echo scaler=2xsai)
fi
into batch script. I really don't know if the next are right:
REM "Resolutions 4:3"
if %RES% = 800x600
set windowresolution=640x480
set scale=2xsai
I need specify multiple resolutions and windowresolutions in the script
for better config file.
echo "lines" >> %CONFIG%
echo "%variable%" >> %CONFIG%
which I need use for each
"if %RES%=Numbers X Numbers"
windowresolution=%WINRES%
scale=something
to export to the config file the follow
Resolution=800x600
windowresolution=640x480
scale=2xsai
I can't help you with the vbs-parts, but:
for /F %%* in (%SCRIPT%) do set RES=%%A
seems quite wrong. first, you have to use then same for-variable : EITHER %%* OR %%A:
for /F %%A in (%SCRIPT%) do set RES=%%A
Second: with this syntax you read the file %script%, assingning every line to RES, resulting in %RES% being the last line of your file.
To use the result of the executed script, use:
for /F %%A in ('%SCRIPT%') do set RES=%%A
Note the single qoutes ('), which tell forto execute the script.
Note: you can also get your screen-parameters with batch:
for /f %%i in ('wmic desktopmonitor get screenheight^,screenwidth /value^|find "="') do set %%i
echo %Screenheight%x%ScreenWidht%
First and foremost: always post the actual error information (error message, error number, the actual line raising the error, …). Since we're not sitting in front of your computer screen you need to tell us what's on it.
With that said, you're probably getting an error, because the & operator has a special meaning in batch files. It separates two commands from each other, so you need to escape it if you want to print a literal &:
C:\>echo foo & echo bar
foo
bar
C:\>echo foo ^& echo bar
foo & echo bar
You're getting %A in the output file, because the syntax of your for loop is entirely wrong. The loop variable must be defined as %%A, not %%*, and the statement you want to run must be put between single quotes (or backticks, if you set the usebackq option). Also, you must run the script with cscript.exe, because the default interpreter (wscript.exe) doesn't write to StdOut, so you'd have no output to process. Change this:
for /F %%* in (%SCRIPT%) do set RES=%%A
into this:
for /F %%A in ('cscript //NoLogo %SCRIPT%') do set RES=%%A
to make the loop work correctly.
Just fixing the loop won't help much, though, because the VBScript you generate doesn't produce any output in the first place. You can't pass VBScript variables back to the batch script, only printed output (WScript.Echo or WScript.StdOut.WriteLine), or perhaps variables in the volatile environment.
However, as #Stephan already pointed out, you don't need the VBScript in the first place, because you can run WMI queries from batch files with the wmic command-line utility:
for /F %%A in (
'wmic desktopmonitor get ScreenHeight^,ScreenWidth /value ^| find "="'
) do set "%%A"
set "RES=%ScreenHeight%x%ScreenWidth%"
Note that you need to escape both , and | in the subexpression (escape character in batch is ^).
To create an output file with multiple lines you have to either echo one line at a time:
set "CONFIG=%CD%\dosbox.conf"
type nul >"%CONFIG%"
echo foo >>"%CONFIG%"
echo windowresolution=%RES% >>"%CONFIG%"
echo bar >>"%CONFIG%"
or escape line breaks like this:
set "CONFIG=%CD%\dosbox.conf"
echo foo ^
windowresolution=%RES% ^
bar >"%CONFIG%"
Writing several lines depending on the value of %RES% can be handled like this:
REM "Resolutions 4:3"
if "%RES%" = "800x600" (
echo Resolution=%RES% >>"%CONFIG%"
echo windowresolution=640x480 >>"%CONFIG%"
echo scale=2xsai >>"%CONFIG%"
)

How to End a VBScript Called from a Batch File and loop through the Batch File

Currently I have a batch file that calls a VBScript and executes the script and exits from that script into the command prompt window that I called the batch file from. I am wanting to return to the batch file from the VBScript and loop back into the beginning of the batch file and ask for the information from the user again and then go back into the script and repeat. I would also like to query the user as to whether they would like to quit or repeat after the VBscript has been run.
Here is my batch file:
#echo off
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
Set /P datafile=Please enter data file to be analyzed:
Set /P filename=Please enter name for canvas file:
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
And here is my VBScript (Disregard the SendKeys method, I understand how unreliable it is and will modify this later to not use it):
Set wshShell = CreateObject("Wscript.Shell")
Set args = WScript.Arguments
arg1 = args.Item(0)
Dim filename
filename = ""&arg1&""
WshShell.AppActivate "Command Prompt"
WshShell.SendKeys "root -b"
WshShell.SendKeys "~"
WshShell.AppActivate "ROOT session"
WshShell.SendKeys ".x analysis.C"
WshShell.SendKeys "~"
WshShell.SendKeys ".x double_gaus.C"
WshShell.SendKeys "~"
WshShell.AppActivate "ROOT session"
WshShell.SendKeys "c1->SaveAs{(}"""&filename&"""{)}"
WshShell.SendKeys "~"
WshShell.SendKeys ".q"
WshShell.SendKeys "~"
WScript.Quit
I have tried various ways of using the IF ERRORLEVEL command and keeping in mind that it must be in descending order when checked, but nothing is working.
#echo off
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
:loop
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
set "datafile="
Set /P datafile=Please enter data file to be analyzed:
if not defined datafile echo all done - exiting&goto :eof
set "filename="
Set /P filename=Please enter name for canvas file:
if not defined filename echo all done - exiting&goto :eof
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
goto loop
This should get you going.
Can't see what errorlevels have to do with anything. You appear not to be setting the vbscript exit code (need WScript.Quit yourerrorlevel else it will exit with errorlevel 0, I am told)
If you clear the values before they are input, then you can take advantage of the set /p behaviour that the value will remain unchanged if you simply reply with Enter
You can also use this characteristic to establish a default value, if that suits.
OR you could define a specific exit codeword like quit or exit. Using this method, you'd code a line
if /i "%var%"=="exit" echo Bye-bye&goto :eof
where the quotes protect against an empty or space-containing entry by the user into var, the & is an inline statement-separator and :eof is a special label predefined and understood by cmd to mean end of file (the colon is required)
This has a loop and a method to exit from the loop.
#echo off
:loop
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
"set datafaile="
Set /P datafile=Please enter data file to be analyzed or press Enter to Quit:
if not defined datafile goto :EOF
Set /P filename=Please enter name for canvas file:
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
goto :loop
As #brianadams suggested, there's no need for a batch script here. You can do the entire prompting and looping in VBScript and shell out for external commands like mklink.
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
sh.CurrentDirectory = "C:\Users\Jared\Documents\Research\jared"
basicfile = "basic.dat"
Do
If fso.FileExists(basicfile) Then
On Error Resume Next
fso.DeleteFile basicfile, True
If Err Then fso.OpenTextFile("Report.txt", 8, True).WriteLine _
"[+] File failed to delete: " & qq(basicfile)
On Error Goto 0
End If
datafile = InputBox("Please enter data file to be analyzed:")
filename = InputBox("Please enter name for canvas file:")
sh.Run "cmd /c mklink " & qq(basicfile) & " " & qq(datafile)
sh.AppActivate "Command Prompt"
sh.SendKeys "root -b"
'...
Loop

Batch Command Line to Eject CD Tray?

I'm currently trying to move my CD's of backup to my Backup HDD.
To automate the task I'm trying to create a batch to copy the files with the label of the CD than eject the media.
The code looks like this so far:
#echo off
SET dest=F:\Backup\
d:
:: routine to retrieve volume label.
for /f "tokens=1-5*" %%1 in ('vol') do (
set vol=%%6 & goto done
)
:done
:: create destination folder
set dest=%dest%%vol%
mkdir "%dest%"
:: copy to destiny folder
xcopy "d:" "%dest%" /i /s /exclude:c:\excludes.txt
::eject CD
c:
I'm stuck at eject part. I'm trying to eject the CD because I want a clear line to draw my attention when the copy finished (I thought opening the tray to be a good one).
Any ideas how to do it using Batch? Or any other ways to "draw the attention" to the end of the copy event?
Thanks :)
if you have no installed media player or anti virus alarms check my other answer.
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul
'& cls
'& cscript /nologo /E:vbscript %~f0
'& pause
Set oWMP = CreateObject("WMPlayer.OCX.7" )
Set colCDROMs = oWMP.cdromCollection
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count - 1
colCDROMs.Item(i).Eject
Next ' cdrom
End If
This is a batch/vbscript hybrid (you need to save it as a batch) .I don't think is possible to do this with simple batch.On windows 8/8.1 might require download of windows media player (the most right column).Some anti-virus programs could warn you about this script.
I know this question is old, but I wanted to share this:
#echo off
echo Set oWMP = CreateObject("WMPlayer.OCX.7") >> %temp%\temp.vbs
echo Set colCDROMs = oWMP.cdromCollection >> %temp%\temp.vbs
echo For i = 0 to colCDROMs.Count-1 >> %temp%\temp.vbs
echo colCDROMs.Item(i).Eject >> %temp%\temp.vbs
echo next >> %temp%\temp.vbs
echo oWMP.close >> %temp%\temp.vbs
%temp%\temp.vbs
timeout /t 1
del %temp%\temp.vbs
just make sure you don't have a file called "temp.vbs" in your Temp folder. This can be executed directly through a cmd, you don't need a batch, but I don't know any command like "eject E:\". Remember that this will eject all CD trays in your system.
UPDATE:
A script that supports also ejection of a usb sticks - ejectjs.bat:
::to eject specific dive by letter
call ejectjs.bat G
::to eject all drives that can be ejected
call ejectjs.bat *
A much better way that does not require windows media player and is not recognized by anti-virus programs (yet) .Must be saves with .bat extension:
#cScript.EXE //noLogo "%~f0?.WSF" //job:info %~nx0 %*
#exit /b 0
<job id="info">
<script language="VBScript">
if WScript.Arguments.Count < 2 then
WScript.Echo "No drive letter passed"
WScript.Echo "Usage: "
WScript.Echo " " & WScript.Arguments.Item(0) & " {LETTER|*}"
WScript.Echo " * will eject all cd drives"
WScript.Quit 1
end if
driveletter = WScript.Arguments.Item(1):
driveletter = mid(driveletter,1,1):
Public Function ejectDrive (drvLtr)
Set objApp = CreateObject( "Shell.Application" ):
Set objF=objApp.NameSpace(&H11&):
'WScript.Echo(objF.Items().Count):
set MyComp = objF.Items():
for each item in objF.Items() :
iName = objF.GetDetailsOf (item,0):
iType = objF.GetDetailsOf (item,1):
iLabels = split (iName , "(" ) :
iLabel = iLabels(1):
if Ucase(drvLtr & ":)") = iLabel and iType = "CD Drive" then
set verbs=item.Verbs():
set verb=verbs.Item(verbs.Count-4):
verb.DoIt():
item.InvokeVerb replace(verb,"&","") :
ejectDrive = 1:
exit function:
end if
next
ejectDrive = 2:
End Function
Public Function ejectAll ()
Set objApp = CreateObject( "Shell.Application" ):
Set objF=objApp.NameSpace(&H11&):
'WScript.Echo(objF.Items().Count):
set MyComp = objF.Items():
for each item in objF.Items() :
iType = objF.GetDetailsOf (item,1):
if iType = "CD Drive" then
set verbs=item.Verbs():
set verb=verbs.Item(verbs.Count-4):
verb.DoIt():
item.InvokeVerb replace(verb,"&","") :
end if
next
End Function
if driveletter = "*" then
call ejectAll
WScript.Quit 0
end if
result = ejectDrive (driveletter):
if result = 2 then
WScript.Echo "no cd drive found with letter " & driveletter & ":"
WScript.Quit 2
end if
</script>
</job>
Requiring administrator's rights is too abusing :)
I am using wizmo:
https://www.grc.com/WIZMO/WIZMO.HTM

Why is my entire batch script running as a SETLOCAL command?

I don't understand what I'm doing wrong, the output is always the entire script, with an Invalid parameter to setlocal error! This is probably just a silly mistake, but it's making me crazy.
SETLOCAL ENABLEDELAYEDEXPANSION
REM Obtain username of logged in user
SET loggedinuser=%USERNAME%
REM Create temporary vbscript to obtain user OU
echo Const ADS_SCOPE_SUBTREE = 2 >temp.vbs
echo. >>temp.vbs
echo Set objConnection = CreateObject("ADODB.Connection") >>temp.vbs
echo Set objCommand = CreateObject("ADODB.Command") >>temp.vbs
echo objConnection.Provider = "ADsDSOObject" >>temp.vbs
echo objConnection.Open "Active Directory Provider" >>temp.vbs
echo Set objCommand.ActiveConnection = objConnection >>temp.vbs
echo. >>temp.vbs
echo objCommand.Properties("Page Size") = 1000 >>temp.vbs
echo objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE >>temp.vbs
echo. >>temp.vbs
echo objCommand.CommandText = _ >>temp.vbs
echo ^"SELECT distinguishedName FROM ^'LDAP://dc=test,dc=com^' ^" ^& _ >>temp.vbs
echo "WHERE objectCategory='user' " ^& _ >>temp.vbs
echo "AND sAMAccountName='!loggedinuser!'" >>temp.vbs
echo Set objRecordSet = objCommand.Execute >>temp.vbs
echo. >>temp.vbs
echo objRecordSet.MoveFirst >>temp.vbs
echo Do Until objRecordSet.EOF >>temp.vbs
echo strDN = objRecordSet.Fields("distinguishedName").Value >>temp.vbs
echo arrPath = Split(strDN, ",") >>temp.vbs
echo intLength = Len(arrPath(1)) >>temp.vbs
echo intNameLength = intLength - 3 >>temp.vbs
echo Wscript.Echo Right(arrPath(1), intNameLength) >>temp.vbs
echo objRecordSet.MoveNext >>temp.vbs
echo Loop >>temp.vbs
REM Save backup of old printer list, just in case
echo Creating a backup list of current printers, please wait...
wmic printer list brief /format:csv > \\networkshare\userfiles\!loggedinuser!\oldprinterlist.txt
echo Backup list completed.
REM Set the OU variable by running the vbscript
echo Discovering your department...
FOR /F "delims=" %%a in ('cscript.exe /nologo temp.vbs') do #set OU=%%a
echo Adding printers for %OU%
REM Perform new printer install based on OU
if %OU%==MIS (
set printer1=Printer_1_Yo
set printer2=Printer_2_Yo
set printer3=Printer_3_Yo
echo Adding %printer1%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer1%
echo %printer1% added. Adding %printer2%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer2%
echo %printer2% added. Adding %printer3%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer3%
echo %printer3% added. All printers are ready to use!
)
REM Delete printers that were on job
echo Deleting old printers from testserver, please wait...
wmic printer where servername=\\\\testserver delete
echo Deletion complete.
echo. If you would like to add more printers, please visit the Printers page on the intranet.
echo. Press any key to close this window.
pause>temp.txt
del temp.txt
del temp.vbs
After further testing, it seems that the wmic printer where line doesn't work properly, and I will fix that soon (suggestions welcome)... but is that the cause of the entire script falling apart? I'm aware that the vbscript portion is a little odd, but I don't think that's the issue either. Please correct me if I'm wrong!
If your script does NOT start with #ECHO OFF command, then you will see in the screen the fully script contents when it runs.
I want to make good use of this post, so I modified your script in order to make the creation of the temp.vbs file much cleaner, although this point is not directly related to your problem. However, when I tested the Batch file below with a GOTO :EOF command inserted after the creation of the temp.vbs file, it correctly runs with no "setlocal" error!
EDIT: I realized that original script uses loggedinuser variable to hardcode its value in the creation of the temp.vbs program, that is the reason because the file is created and deleted each time. My original translation does not account for this detail.
I modified the Batch file below to pass the value of loggedinuser from Batch to VBS section in the parameter. This way, the .vbs program could be created just once with a more appropriate name.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM Obtain username of logged in user
SET loggedinuser=%USERNAME%
REM Create temporary vbscript to obtain user OU, if not exists
if not exist getUserOU.vbs (
for /F "delims=:" %%a in ('findstr /N "^:VBS_Section" "%~F0"') do set n=%%a
more +!n! < "%~F0" > getUserOU.vbs
)
REM Save backup of old printer list, just in case
echo Creating a backup list of current printers, please wait...
wmic printer list brief /format:csv >
\\networkshare\userfiles\!loggedinuser!\oldprinterlist.txt
echo Backup list completed.
REM Set the OU variable by running the vbscript
echo Discovering your department...
FOR /F "delims=" %%a in ('cscript.exe //nologo getUserOU.vbs "%loggedinuser%"') do #set OU=%%a
echo Adding printers for %OU%
REM Perform new printer install based on OU
if %OU%==MIS (
set printer1=Printer_1_Yo
set printer2=Printer_2_Yo
set printer3=Printer_3_Yo
echo Adding %printer1%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer1%
echo %printer1% added. Adding %printer2%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer2%
echo %printer2% added. Adding %printer3%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer3%
echo %printer3% added. All printers are ready to use!
)
REM Delete printers that were on job
echo Deleting old printers from testserver, please wait...
wmic printer where servername=\\\\testserver delete
echo Deletion complete.
echo. If you would like to add more printers, please visit the Printers page on the intranet.
echo. Press any key to close this window.
pause>temp.txt
del temp.txt
goto :EOF
:VBS_Section
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.CommandText = _
"SELECT distinguishedName FROM 'LDAP://dc=test,dc=com' " & _
"WHERE objectCategory='user' " & _
"AND sAMAccountName='" & WScript.Arguments(0) & "'"
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
strDN = objRecordSet.Fields("distinguishedName").Value
arrPath = Split(strDN, ",")
intLength = Len(arrPath(1))
intNameLength = intLength - 3
Wscript.Echo Right(arrPath(1), intNameLength)
objRecordSet.MoveNext
Loop
For your wmic printer command use:
wmic printer where 'servername="\\\\testserver"'
If that doesn't work, swap the single and double quotes. I'm not at a computer atm, so I'm going from memory. Also, you don't have to go through all that creating vbscript to get a ou. Wmic can query ldap.
WMIC /NAMESPACE:\\root\directory\ldap PATH ds_user GET ds_distinguishedname
Here is my version of your script.
#echo off
setlocal enabledelayedexpansion
set q=wmic /NAMESPACE:\\root\directory\ldap PATH ds_user Where "ds_samaccountname^='!username!'" get ds_distinguishedname
for /f "skip=1 tokens=3 delims==" %%a in ('%q%') do (
for /f "tokens=1 delims=," %%b in ("%%a") do set ou=%%b
)
:: Save backup of old printer list, just in case
set share=\\networkshare\userfiles
if not exist "%share%\!username!" md "%share%\!username!"
set printlist="%share%\!username!\oldprinterlist.txt"
echo Creating a backup list of current printers, please wait...
wmic printer list brief /format:csv > %printlist%
echo Backup list completed.
::Perform new printer install based on OU
IF %ou%==MIS (
call :addprinter Printer_1_Yo Testserver
call :addprinter Printer_2_Yo Testserver
call :addprinter Printer_3_Yo Testserver
)
::Delete printers that were on job
echo.
echo Deleting old printers from testserver, please wait...
wmic printer where "servername='\\\\testserver'" delete
echo Deletion complete.
echo.
echo. If you would like to add more printers, please visit the Printers page on the intranet.
echo. Press any key to close this window.
pause>nul
goto :eof
:addprinter prn server
echo.
echo Adding %1, please wait...
wmic printer call addprinterconnection \\%2\%1

How to set environment variables in vbs that can be read in calling batch script

I have a batch file that calls a vbscript file. I am trying to have the vbscript file change an environment variable that is later used in the batch file that calls the vbscript file.
Here are snippetes from the files.
Parent.bat
Set Value="Initial Value"
cscript Child.vbs
ECHO Value = %VALUE%
Child.vbs
Set wshShell = CreateObject( "WScript.Shell" )
Set wshSystemEnv = wshShell.Environment( "Process" )
wshSystemEnv("VALUE") = "New Value"
You can't. A process can pass environment variables to child processes, but not to its parent - and in this case the parent is cmd.exe, which is running your Parent.bat file.
There are of course other ways to communicate information back to the parent batch file - outputting to stdout or a file is an obvious way, e.g.
== Child.vbs ===
WScript.echo "New Value"
== Parent.cmd ===
for /f "tokens=*" %%i in ('cscript //nologo child.vbs') do set Value=%%i
echo %Value%
yes, you can.... however, you'll have to resetvars in your session. see the following link:
Is there a command to refresh environment variables from the command prompt in Windows?
'RESETVARS.vbs
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("System")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")
set oEnv=oShell.Environment("User")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close
This is how I did it:
SET oShell = CREATEOBJECT("Wscript.Shell")
dim varSet
SET varSet = NOTHING
SET varSet = oShell.Environment("SYSTEM")
varSet("WinVer") = "6.0.2008"
Then in a separate VB script (resetvars.vbs) I called from CMD script:
cscript //nologo \\%APPSERVER%\apps\IE9.0\restartvars.vbs
call %TEMP%\resetvars.bat
I don't think you can do this. At least, you would need to mess with the environment block in the calling process, and there's no guarantee that it will respect this...
Ho about this:
#echo off
set vbsFile=%temp%\createguid.vbs
call :CreateVbs
call :GetGuid NewGuid
echo.%NewGuid%
del %vbsFile%>nul
GOTO:EOF
:CreateVbs
echo.set obj = CreateObject("Scriptlet.TypeLib")>%vbsFile%
echo.WScript.StdOut.WriteLine obj.GUID>>%vbsFile%
GOTO:EOF
:GetGuid
for /f "tokens=*" %%i in ('cscript //nologo %vbsFile%') do set %1=%%i
GOTO:EOF
It is not pure batch script but works ok.
#echo off&color 4a&title %~n0&AT>NUL
IF %ERRORLEVEL% EQU 0 (
goto 2
) ELSE (
echo.
)
if not "%minimized%"=="" goto 1
set minimized=true & start /min cmd /C "%~dpnx0"&cls&exit
:1
wmic process where name="cmd.exe" CALL setpriority "realtime">nul&echo set shell=CreateObject("Shell.Application") > %~n0.vbs&echo shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1 >> %~n0.vbs&echo set shell=nothing >> %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit
:2
echo %~dpnx0 admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"&timeout 3 /NOBREAK>nul
:3
echo x=msgbox("end of line" ,48, "%~n0") > %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit

Resources