Command to find Active Drive - vbscript

I am trying to build a VBScript to automatically run some .exe files. The problem is that the script and the .exe files are on a flashdrive, so it needs to find the current drive letter by itself. I can do it on a batch file using %~d0, but I like some of the functions of VBScript better, especially the ability to send keystrokes. Anyways, I found a whole list of VBScript commands, but I am no expert and I need help with the syntax. So far I have it set to open the task manager and press some keys to have it select the "performance tab" of the task manager:
Dim Act :Set Act = CreateObject("Wscript.Shell")
Act.Run("taskmgr.exe")
Success = Act.AppActivate("taskmgr")
Wscript.Sleep 250
Act.SendKeys "{TAB 5}" :WScript.Sleep 500
Act.SendKeys "{RIGHT 3}" :WScript.Sleep 500
I'd like to know what command I need to use to tell the script to use the drive letter where the script was executed from (USB drive).

Use the .ScriptFullName property to get the full file spec of the running script and apply .GetParentFolderName for the folder's path or .GetDriveName for just the drive letter.
>> Set oFS = CreateObject("Scripting.FileSystemObject")
>> s = WScript.ScriptFullName
>> WScript.Echo oFS.GetParentFolderName(s), oFS.GetDriveName(s)
>>
M:\bin M:
cf. here

Related

How to give script a name?

I have a script that I run to keep my computer from going to sleep. It's a simple script that presses the Num Lock key. How can I give my script a name so I can see it in Task Manager? I would like to end the process every now and then and not sure which application it is.
Here is the code (idle.vbs):
Dim objResult
Set objShell = WScript.CreateObject("WScript.Shell")
Do While True
objResult = objShell.sendkeys("{NUMLOCK}{NUMLOCK}")
Wscript.Sleep (60000)
Loop
Your script is being executed in an interpreter, and in Task Manager you will see the name of the executable : wscript.exe
You cannot change the process name, although you can identify the name of the running script using another script and the property of handles.
But the easiest way would be to make a copy of the executable wscript.exe, rename it with something suggestive for you, and use that executable in cmd to run the script. For example idleEx.exe and run it :
...\idleEx.exe idle.vbs
Or, the other method: create a shortcut for the vbs and change Properties / General / Opens with, browse and choose idleEx.exe.
After that, your process name will apear as idleEx.exe

Create shortcut which runs in minimized mode via script

How do I create a shortcut of a batch file and configure if to run in minimized mode? When I create a shortcut to a batch file I have to manually configure it to run in minimized mode manually. Any idea how do I write a script to change it to run as "minimized" mode
#npocmaka's shortcutjs.bat is a complete solution but it has about 200 lines. So, I have created a small VBScript for the purpose. You need to modify it according to your purpose.
'======PART 1: elivate to admin. required to save the batch file from part 2 in C drive
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
'======PART 2: create the test batch file on the fly
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile = "c:\test.cmd"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "pause" & vbCrLf
objFile.Close
'=======PART 3: create the shortcut of the batch file
set WshShell = CreateObject("Wscript.shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oMyShortcut = WshShell.CreateShortcut(strDesktop + "\test.lnk")
oMyShortcut.WindowStyle = 7
OMyShortcut.TargetPath = "c:\test.cmd"
oMyShortCut.Save
Part 1 and 2 are optional and they are just to give an idea about what to do if you also want to create the batch file on the fly. Part 3 is the required code to create a shortcut using VBS.
You can run VBS script from cmd: cscript shortcut.vbs after you save the code above as shortcut.vbs
If you want to pass some argument about your batch file location, see this question, Can I pass an argument to a VBScript (vbs file launched with cscript)?
Then you can also use your code like cscript shortcut.vbs "C:\test.cmd" and reuse the same VBScript to create different shortcuts.
For other available options like adding an icon to your shortcut, adding hotkey support, setting Working Directory etc. please see this link
If I understand you correctly. You will need to use VB script to create shortcut. I don't believe batch script can create shortcut
https://support.microsoft.com/en-us/help/244677/how-to-create-a-desktop-shortcut-with-the-windows-script-host
see example 2: the WindowsStyle parameter define the windows size.
oMyShortCut.WindowStyle = 7 <-- 7= minimized.
Good luck
Binh
Try with shortcutjs.bat:
shortcutjs.bat -linkfile tst6.lnk -target "%cd%\myscript.bat" -windowstyle 7 -adminpermissions yes
-adminpermissions yes is optional if you want to run the bat as administrator. You'll need the full path to your script. possible modes are 1 for normal, 3 for maximized and 7 for minimized.

how to make my scripts portable vbs

this would be a noob question..but I want to make my scripts more portable.
lets say, I have coded all my .vbs(or any script in any code of nature) in a USB.
so I want to run that vbs on that current machine. the USB is assigned to be in F: drive
however when i unplugged that usb and sticked to another machine..it is going to be no longer F:..but it could be E: G: or whatever
I just wanted to know how do i overcome that without changing it directly on the scripts but the script is capable of reading which directory its pointing toward.
Im not sure how that property/functionality is called.
but would appreciate any hints/tips
There are two main ways you can make your script more portable.
The first, and probably the most appropriate for your use case, is to check what drive your executable is running on by using WScript.ScriptFullName and getting the first three characters to find the drive letter. You could alternatively chop the script name (WScript.ScriptName) off the end to find the current working directory. Assign this to a variable, and use it everywhere in your code where you specify a path.
Dim fullname : fullname = WScript.ScriptFullName
Dim drive : drive = Mid(fullname, 1, 3)
Dim path : path = Mid(fullname, 1, Len(fullname) - Len(WScript.ScriptName))
WScript.Echo "Drive = " & drive & vbcrlf & "Path = " & path
Another way is to make your script expect run-time arguments from the user, so you can specify exactly where you want to do things.
' Make a shortcut to your script and add a parameter,
' Or run from the command prompt with an additional parameter.
If WScript.Arguments.Length = 0 Then
WScript.Echo "No arguments supplied!"
WScript.Quit
End If
WScript.Echo WScript.Arguments(0)
I hope that helps!

Run a vbscript as an admin from itself (Nagios / NSclient)

I'll detail as much as I can so you can understand in which environment I'm working on and what I am trying to do.
I am using Nagios at work to monitor our servers. Each one of our Windows servers has NSclient++ installed on it. One of the many scripts Nagios' calling is check_updates.vbs; here 's how it goes if someone need to know:
On the Nagios' server side, we execute the following command:
/usr/lib/nagios/plugins/check_nrpe -H WindowsServerIpAddress -p 5666 -t 120 -c check_updates
When we execute that command, here is what's happening on the Windows Server:
By using the nscp service, it calls the following command, defined in the nsclient.ini file (into NSclient++ folder):
check_updates=cscript.exe //T:120 //NoLogo scripts\\check_updates.vbs
Then, it calls the check_updates.vbs script.
The local account on the Windows Server is the administrator one. We have changed nscp service's properties so that this service is called with another account, created especially for monitoring.
So, when we call the check_updates.vbs script directly on the Windows server (i.e locally), everything goes well, the script is working perfectly. But if we call it remotely, on the Nagios server, we have a simple (but deadly) error that says Permission denied.
That is why we are focusing on giving enough permissions to the monitoring-user.
After searching more and more and trying everything we could, I must say we're kinda lost right now.
The last solution I tried was to add these lines at the beginning of the script, to give the monitoring-user enough permissions to execute the script properly:
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
End if
(I found this here)
When I use this, locally I get an [error notice*] but the script is working anyway. However, when I call the script remotely, I just have a timeout after 120s.
More info: UAC is disabled on the Windows server, and the monitoring-user has full access control on the NSclient++\scripts folder. Using the nscp service with the admin account is not the solution we are seeking for this matter.
So, am I missing something here ? Do you have any idea about this ?
Thanks for the help ! :)
[*error notice]: Invalid arguments, check help with cscript.exe check_available_updates.vbs -h
If UAC is off then it's not a UAC permission error therefore don't worry about runas.
It's also unlikely to be a file permissions problem (all admins are equal unless someone made it different).
What is likely is the different environments. You have an assumption that is true for the interactive user only. You need to log what is happening in your script (see wshshell.LogEvent(intType, strMessage [,strTarget])). If your script has
on error remove next
remove it.
Mapped drives are a problem. As are environmental variables and special folders.
Try using Runas command line command with various options (eg /env) to see if you can duplicate the behaviour.
Also run
cmd /c set > c:\set.log
and compare the output from the two ways of running it (ie with your client and direct).
Thanks for your answer Tony, I've tried your suggestions, but eventually we ended up getting around the problem.
Despite we gave the monitoring-user all permissions needed to execute this script, it was not working. So here's what we've done:
We created a bat file which contains the command-line to call check_update.vbs and to write its output into a new file:
cscript.exe //T:120 //NoLogo "C:\Program Files\NSClient++\scripts\check_updates.vbs" > "C:\Program Files\NSClient++\check_update.log"
Then, we've created a scheduled task (using the TaskScheduler) which calls the bat file every day to check for new updates.
To have the correct output in Nagios, we created another vbscript which only has to read the check_update.log file and return the appropriate value to Nagios:
Const ForReading = 1
Const rOK = 0
Const rWarning = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Program Files\NSClient++\check_update.log", ForReading)
FirstChar = objFile.Read(1)
Content = objFile.ReadAll
If FirstChar = "O" Then
Wscript.Echo FirstChar + Content
Wscript.Quit(rOK)
Else
WScript.Echo FirstChar + Content
End If
Wscript.Quit(rWarning)
This vbscript is really basic, since it only reads the first letter of the file to decide which value to return. Indeed, if there are no updates available, the message will always be "OK - No patches missing".
So, by calling the bat file using the SchedulerTask, we get around the fact that the monitoring-user has not enough permissions to execute the script.

Double Click and Open an undefined file from within VBscript

I want to open .mp3 files with mpg123.exe silently when a .mp3 file is double clicked from within Windows Explorer. For this I wrote a VBScript as bellow and changed the default program for playing .mp3 files by assigning my VBScript to it via Open with → Choose default program. My script is working well from within command line (cmd.exe) but when a .mp3 file is double clicked I get an error message that double clicked .mp3 file is not an executable file in Windows. Here is my VBScript, please let me know where I am doing wrong.
if Wscript.arguments.count = 0 then
WScript.quit
else
strSoundFile = WScript.Arguments.Item(0)
end if
Set objShell = CreateObject("Wscript.Shell")
strCommand = "mpg123.exe -q " & chr(34) & strSoundFile & chr(34)
objShell.Run strCommand, 0, True
Why don't you just associate mp3 files with mpg123.exe and set up the associated parameters (eg: -q "%1") instead?
Since I couldn't find a notable existing example, I've whipped up an example for you. (tested to work on Windows 7 with mpg123.exe). The response was too image heavy to post here. I hope it helps you.

Resources