Active Setup - script to edit file not running/working - batch-file

Have the following batch file:
cscript Myvb.vbs "C:\Users\%username%\AppData\LocalLow\file.ini" "Things" "Stuff"
vb script file:
Const ForReading = 1
Const ForWriting = 2
strFileName = WScript.Arguments(0)
strFindText = WScript.Arguments(1)
strNewText = WScript.Arguments(1) & vbCrLf & WScript.Arguments(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strFindText, stfFindText&strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText
objFile.Close
Set objFile = Nothing
and batch file to set ActiveSetup:
#echo off
REM copy batch file
xcopy Mybat.bat* %SYSTEMROOT%\
xcopy Myvb.vbs* %SYSTEMROOT%\
REM create active setup component to run batch file
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Active Setup\Installed Components\MySetup" /v "Version" /t REG_SZ /d "1" /f
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Active Setup\Installed Components\MySetup" /v "StubPath" /t REG_SZ /d "%SYSTEMROOT%\Mybat.bat" /f
If mybat is executed manually, the file is edited fine. However, the file does not change after logging in. I undid the changes to the file and cleared the active setup registry entry in my profile between my tests.
Is there a permissions issue I am missing? Is %username% coming out to be not what I expect it to?

Got this working by indicating the full path to the vbs in the bat file
cscript "%~dp0Myvb.vbs" "C:\Users\%username%\AppData\LocalLow\file.ini" "Things" "Stuff"

Related

How can i run the window of the started program minimized

i want to run a .wav-file. This is with
start "" SoundFile.wav
totally practical. But how can i run the window of the standard-windows-soundplayer minimized? So that nothing of my view changes?
start "" SoundFile.wav /MIN
start "" SoundFile.wav /min
start "" SoundFile.wav -MIN
start "" SoundFile.wav -min
didn't work sadly.
Can you help me?
Greets.
Sorry but i am not familiar with stackoverflow, so i can't make it that understandable, but i hope that this is enough.
In a simple way, you could just use a VBS like this:
s = createobject("WScript.Shell")
s.run "music.mp3", 2
Or create an automatic and CLI program to do this:
runmusic.bat
#echo off
set music=%1
set music=%music:"=%
if ":" neq "%music:~1,1%" set music=%cd%\%music%
if "%music:~-4%" neq ".mp3" set music=%music%.mp3
set katorn=%random%
echo >>"%temp%\%katorn%.vbs" set s = createobject("WScript.Shell")
echo >>"%temp%\%katorn%.vbs" s.run "%music%", 2
cscript "%temp%\%katorn%.vbs"
:: Uncomment the next line to autodelete the vbs file.
:: del /q /f "%temp%\%katorn%.vbs"
Usage:
runmusic (name or full path with quotation marks)
In a "professional way" you could do a shortcut file that starts the file minimized.
It could be useful if you needs the musics to have the "artist logo" or something like that, also if you don't want to use an CMD all the time...
Delete all comments to execute.
Set WshShell = CreateObject ("Wscript.Shell")
strDesktop = "X:\Shortcutlocation\yoo"
Set Shortcut = WshShell.CreateShortcut(strDesktop + "\MusicNameMaybe.lnk")
Shortcut.WindowStyle = "7"
Shortcut.IconLocation = "X:\IconPath\youricon.ico" // You can delete this and the file will be the same ever and forever.
Shortcut.TargetPath = "X:\yourpath\music.mp3"
Shortcut.Save
And you don't have to keep the shortcuts on the desktop if you don't want to, you don't even have to keep them fixed. Example:
runmusic.bat
#echo off
set music=%1
set music=%music:"=%
if ":" neq "%music:~1,1%" set music=%cd%\%music%
set music=%music%.mp3
set katorn=%random%
echo >>"%temp%\%katorn%.vbs" Set WshShell = CreateObject ("Wscript.Shell")
echo >>"%temp%\%katorn%.vbs" strDesktop = "%temp%"
echo >>"%temp%\%katorn%.vbs" Set Shortcut = WshShell.CreateShortcut(strDesktop + "\%katorn%.lnk")
echo >>"%temp%\%katorn%.vbs" Shortcut.WindowStyle = "7"
echo >>"%temp%\%katorn%.vbs" Shortcut.TargetPath = "%music%"
echo >>"%temp%\%katorn%.vbs" Shortcut.Save
cscript "%temp%\%katorn%.vbs"
:: Uncomment the next two lines to delete the temporary files.
:: del /q /f "%temp%\%katorn%.vbs"
:: del /q /f "%temp%\%katorn%.lnk"
echo Enjoy!
Usage:
runmusic (name or full path with quotation marks)
Now that you understand, you can even leave a folder with the songs and the other with just the customized shortcuts, which can come in handy.
Hope this helps,
K.

How to pass a variable in a batch script during execution

I have a text file that has the record of all the services in a server. I want to keep '#' for the few entries at the beginning of the line. I have created one vbscript file that contains the following code:
Const Readpurpose = 1
Const Writepurpose = 2
strServiceMonFile = WScript.Arguments(0)
strOldText = WScript.Arguments(1)
strNewText = WScript.Arguments(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strServiceMonFile, Readpurpose)
strText = objFile.ReadAll
objFile.Close
Set objFile = objFSO.OpenTextFile(strServiceMonFile, Writepurpose)
strNewText = Replace(strText, strOldText, strNewText)
objFile.Write strNewText
objFile.Close
In order to execute the code, I am using a batch file and the code used is as follows:
cscript D:\Users\krkarthi\Desktop\replace.vbs "D:\Users\krkarthi\Desktop\test.txt" "Windows Update" "#Windows Update"
In the above mentioned batch code, I need to manually enter each and every entry which I need to keep # comment and for a plenty of services it is very difficult to proceed. I am thinking another way to have a separate text file lets say test1.txt that contains all the unwanted entries. A variable will define in a for loop to run on test1.txt and will run the above mentioned cscript code after do. The imaginative code is as follows:
FOR /f %%G in (D:\Users\krkarthi\Desktop\test1.txt)
DO
cscript D:\Users\krkarthi\Desktop\replace.vbs "D:\Users\krkarthi\Desktop\test.txt" "%%G" "#%%G"
Unfortunately, the above code didn't work at all. I don't understand where the error exists.
Try removing one % from the parameters in your code. It should work. Also you will not need double quotes while passing values to your code.
Corrected:
FOR /F %%G IN (D:\Users\krkarthi\Desktop\test1.txt) DO cscript D:\Users\krkarthi\Desktop\replace.vbs "D:\Users\krkarthi\Desktop\test.txt" "%%G" "#%%G"

How to change a drive letter dynamically on a .bat script

I'm currently working with an old script for a process that was in place before I took a look at it, the premise is to automatically create a folder and copy the contents of a flash drive into a C: drive. Below is the portion of the script I am concerned with:
xcopy "E:\directory" "c:\directory" /s /y
This is the script as I have it now, currently I need to change the first directory entry almost every time I plug into a new device as the drive letter as it appears in the script is sometimes different then what is on the local device. For example, the UBS drive would be D: on a laptop, but E: on most desktops, or some other letter in the case of a device with multiple peripherals.
Previously the script looked something like:
xcopy "...\directory" "c:\directory" /s /y
This doesn't function as the .bat file would come back with an inability to locate said directory on the UBS drive. When I manually change the .bat file to hard set the USB drive letter everything flows fine, all directories copy and the subsequent scripts run fine.
My question, any ideas on how to set the xcopy script to recognize the dynamic USB drive letter and allow for copying without having to change the script on each device?
Thanks!
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set evtDevice = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_VolumeChangeEvent")
Wscript.Echo "Waiting for events ..."
Do
Set objReceivedEvent = evtDevice.NextEvent
'report an event
Wscript.Echo " Win32_Device Changed event occurred" & VBNewLine
If objReceivedEvent.EventType = 1 Then
Wscript.Echo "Type = Config Changed"
ElseIf objReceivedEvent.EventType = 2 Then
Wscript.Echo "Type = Device Arrived"
Set colItems = objWMIService.ExecQuery("Select * From Win32_Volume")
For Each objItem in colItems
If objitem.DriveType = 2 then
Wscript.Echo objItem.DriveType & " " & objItem.Name & " " & objItem.driveletter
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(objitem.driveletter)
Set DestFldr=objShell.NameSpace("c:\test\")
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Wscript.Echo "Finished Copying"
Wscript.sleep 2000
End If
Next
ElseIf objReceivedEvent.EventType = 3 Then
Wscript.Echo "Type = Device Left"
ElseIf objReceivedEvent.EventType = 4 Then
Wscript.Echo "Type = Computer Docked"
End If
Loop
This vbs script waits for a USB to be inserted then copies it to a folder.
Remove all the debugging wscript.echo lines. Change the destination folder.
It copies all attached USB drives.
despite the previous answer from Noodles
#echo off
set "destDrive="
for /F "usebackq tokens=1,2 delims==" %i in (`"wmic logicaldisk get caption, drivetype"`) do (
if %%j EQU 2 set "destDrive=%%i"
)
if "%destDrive%" EQU "" (
echo No pendrive found
) else (
echo copying
xcopy "%destDrive%\directory\*.*" "c:\directory\*.*" /s /y
echo done...
)
Why not modify the batch file to ask for the drive letter before the copy begins?
SET /P USB=Enter USB Drive Letter (C:, D:, E: etc):
XCOPY "%USB%\directory" "C:\directory" /s /y

Pin shortcut (.lnk) to start menu

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

Use Batch File Processing To Remove Last Character

I have a process where an incoming file is csv and has trailing commas after the last entry.
I need to process this and send it out sans that final comma as it causes a verification error with the phantom "empty column"
Currently I've got this piece of code to write each line into a new file:
for /f "tokens=* delims=" %%x in (file.csv) do echo %%i >> test.txt
And I've been trying to use something like echo %string:~0,-1% to remove the trailing comma in conjunction but I'm not having much luck. I don't think %%i can be used the same as a string would be referenced with the above. I've tried writing %%i into a string but seems I've got that syntax wrong too.
[edit]
I do run the file through a vbs script to replace the commas with pipes (, = |) so if there's an easier way to do it as part of that process, in my searching of stackoverflow to try and resolve this prior to asking I found this line which I thought may help:
strNewText = strNewText.Substring(0,strNewText.Length-1)
strNewText being the variable holding the updated data, doesn't work though, now the find and replace text section doesn't actually run when I add that in:
rem CREATE Find And Replace Text VBS SCRIPT
echo Const ForReading = 1 > "%tmp%\fart.vbs"
echo Const ForWriting = 2 >> "%tmp%\fart.vbs"
echo strFileName = Wscript.Arguments(0) >> "%tmp%\fart.vbs"
echo strOldText = Wscript.Arguments(1) >> "%tmp%\fart.vbs"
echo strNewText = Wscript.Arguments(2) >> "%tmp%\fart.vbs"
echo Set objFSO = CreateObject("Scripting.FileSystemObject") >> "%tmp%\fart.vbs"
echo Set objFile = objFSO.OpenTextFile(strFileName, ForReading) >> "%tmp%\fart.vbs"
echo strText = objFile.ReadAll >> "%tmp%\fart.vbs"
echo objFile.Close >> "%tmp%\fart.vbs"
echo strNewText = Replace(strText, strOldText, strNewText) >> "%tmp%\fart.vbs"
echo strNewText = strNewText.Substring(0,strNewText.Length-1) >> "%tmp%\fart.vbs"
echo Set objFile = objFSO.OpenTextFile(strFileName, ForWriting) >> "%tmp%\fart.vbs"
echo objFile.WriteLine strNewText >> "%tmp%\fart.vbs"
echo objFile.Close >> "%tmp%\fart.vbs"
(all the echo's are because I generate the vbs during the batch runtime, I tend to find things easier when everything's done in the one file, this vbs file is then deleted later in the process).
#if (#This==#IsBatch) #then
#echo off
rem **** batch zone *********************************************************
type inputfile.csv | cscript //nologo //e:javascript "%~f0" > outputfile.csv
exit /b
#end
// **** Javascript zone *****************************************************
while (!WScript.StdIn.AtEndOfStream) WScript.StdOut.WriteLine(WScript.StdIn.ReadLine().replace(/,[\s,]+$/,''));
This is an hybrid batch/javascript file. Save as batch file, execute and the inputfile.csv file will be piped into cscript.exe that will execute the javascript code included in the same batch file, iterating over the piped data and deleting all commas and final spaces from last comma to end of line. Output from pipe is sent to outputfile.csv
EDITED - As stated in comments, maybe i missunderstood the question, and it is not necessary to remove commaS at the end of the lines, but only the final comma. In this case, the replace expression should be
... .replace(/,$/,''));
Probably the simplest solution for your problem would be sed for Windows:
C:\>sed "s/,$//" <in.csv >out.csv
You could also write a simple VBScript that does the same thing:
Set re = New RegExp
re.Pattern = ",$"
Do Until WScript.StdIn.AtEndOfStream
WScript.Echo re.Replace(WScript.StdIn.ReadLine, "")
Loop
Usage:
C:\>cscript //NoLogo script.vbs <in.csv >out.csv
PowerShell would be an even better option:
PS C:\> (Get-Content 'in.csv') -replace ',$' | Out-File 'out.csv'
I would not recommend using batch for this.
I'm not sure this will work, but since you only want the code to apply for the last line, I've tried implementing the code differently from your average for loop.
#echo off
setlocal enabledelayedexpansion
set previous=
set current=
ren file.csv file.tmp
3<file.tmp (
:loop
set previous=!current!
set /p current=<&3
if "!current!" == "!previous!" (
Echo !current:~0,-1! >> file.csv
) Else (
Echo !current! >> file.csv
goto :loop
)
)
type file.csv
Echo. &Echo Only delete if file.csv is not corrupt
del /p file.tmp
Endlocal
And that should about do what you want.
Mona.

Resources