Modifications of shortcut target path? - vbscript

I need to change the shortcut target path from "google.com" to "yahoo.com" using the following VBScript:
Set sh = CreateObject("WScript.Shell")
Set shortcut = sh.CreateShortcut("C:\Wherever\Shortcut.lnk")
shortcut.TargetPath = "C:\Program Files(x86)\Internet Explorer\iexplore.exe" http://www.google.com"
shortcut.Save
When I'm running this from CMD
cscript file.vbs
I'm getting the following error:
excepted end of statement
Do I need to add <script language=script> or anything else?

This works for me:
Set sh = CreateObject("WScript.Shell")
Set shortcut = sh.CreateShortcut("C:\temp\Shortcut.lnk")
shortcut.TargetPath = "c:\temp"
shortcut.Save
Also, your script worked perfectly as-is after I created c:\wherever\.
Please post your error if it still doesn't work after ensuring the folder exists.

The syntax of your target path string is incorrect. You need to put double quotes around the entire string, plus you need to put escaped double quotes around the Internet Explorer path inside the string, because that path contains spaces. In VBScript you escape double quotes inside a string by doubling them.
Change this line:
shortcut.TargetPath = "C:\Program Files(x86)\Internet Explorer\iexplore.exe" http://www.google.com"
into this:
shortcut.TargetPath = """C:\Program Files(x86)\Internet Explorer\iexplore.exe"" http://www.google.com"
and the error will disappear.

Related

Open Internet Explorer from Chrome using a protocol handler (ie:url)

I've followed these steps and it doesn't work correctly for me.
Custom protocol handler in chrome
Basically, I don't have a custom app. I just want to create an handler to open IE with a specific URL.
Here are my reg:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\ie]
"URL Protocol"="\"\""
#="\"URL:IE Protocol\""
[HKEY_CURRENT_USER\Software\Classes\ie\DefaultIcon]
#="\"explorer.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\ie\shell]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open\command]
#="\"C:\\Program Files\\Internet Explorer\\iexplore.exe\" \"%1\""
It's working but... when I'm opening ie:www.google.com from Chrome, it ask to open IE but it keeps the "ie:" in the opened URL... which generate a endless loop.
How can I fix that?
Thanks
Create a Protocol Handler
save this script as internet-explorer-protocol-handler.reg:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\ie]
"URL Protocol"="\"\""
#="\"URL:IE Protocol\""
[HKEY_CURRENT_USER\Software\Classes\ie\DefaultIcon]
#="\"explorer.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\ie\shell]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open\command]
#="cmd /k set myvar=%1 & call set myvar=%%myvar:ie:=%% & call \"C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe\" %%myvar%% & exit /B"
Then run the script to install the keys in your registry. It will look like this:
Now links that use the ie: protocol will open in Internet Explorer.
Google
Demo Page
Here is a solution that should solve the problem with extended url's that contain parameters and special characters (&, % etc.)
Like this:
https://www.google.com/search?q=open-internet-explorer-from-chrome-using-a-protocol-handler&oq=open-internet-explorer-from-chrome-using-a-protocol-handler&aqs=chrome..69i57j69i60l3.1754j0j4&sourceid=chrome&ie=UTF-8
Replace the command in reg file with this:
powershell -windowstyle hidden -command "& {$Url = '%1' ; $Url = $Url -replace 'ie:',''; $IE=new-object -com internetexplorer.application ; $IE.navigate2($Url) ; $IE.visible=$true }"
After few tests, I move to another strategy.
I'm targetin an intermediate batch script instead.
And the batch split the protocol and the url, and open IE.
Here is the batch:
echo %1%
set var=%1
set var=%var:~4,-1%
Start "" "%ProgramFiles%\Internet Explorer\iexplore.exe" %var%
Working registry:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\ie]
"URL Protocol"=""
#="URL:IE Protocol"
[HKEY_CURRENT_USER\Software\Classes\ie\shell]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open]
[HKEY_CURRENT_USER\Software\Classes\ie\shell\open\command]
#="cmd /c set url=\"%1\" & call set url=%%url:ie:=%% & call start iexplore -nosessionmerging -noframemerging %%url%%"
Some important notes:
You have to wrap %1 in double quotes. Otherwise url with multiple params like example.com?a=1&b=2 will be stripped to example.com?a=1, params after & will be ignored.
You have to remove the double quotes when calling iexplore. If you don't remove the double quotes and open multiple IE window from chrome, only the first IE window will get the correct URL. But removing quotes with command set url=%%url:\"=%% or set url=%%url:~1,-1%% doesn't work.
If you just can't make it to remove those quotes, add switches -nosessionmerging and -noframemerging to iexplore. These are command-line options to control "merging" behavior for IE.
The implementation of the registry will be more generic if you last line of the registry as
#="cmd /C set myvar=%1 & call set myvar=%%myvar:ie:=%% & call start /separate iexplore %%myvar%% & exit"
You wont need to create a custom script.
In case, the target URL can have more than 1 query params, you might face an issue that only the first param gets passed to IE (check the address bar on IE to validate).
In such a case, you can go for the following workaround ... simply create a new html file passing the target URL after encoding it and open this HTML on IE.
window.location = "ie:"+<URL to the above HTML>+"?path="+encodeURIComponent(<target URL>);
In the HTML file, just redirect to the decoded target URL
<html>
<head>
<title>
IE Redirect
</title>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
function openURL(){
window.location.href=decodeURIComponent(getUrlVars()["path"]);
}
</script>
</head>
<body onload="openURL()">
</body>
</html>
The above worked perfectly in my application.
the following command will work for all query params to be passed:
cmd /C set myvar="%1" & call set myvar=%%myvar:ie:=%% & call start /separate "iexplore.exe" %%myvar%% & exit
the following command will work for all query params to be passed:
cmd /C set myvar="%1" & call set myvar=%%myvar:ie:=%% & call start
/separate "iexplore.exe" %%myvar%% & exit
We need to use the double quotes when a link had an ampersand in it and would not open in IE11 as anything after the ampersand was trimmed off.

vbscript cannot find batch file stored in google drive

I am trying to run the following C:\users\jdoe\google drive\bin\script.vbs script on Windows 7:
CreateObject("Wscript.Shell").Run "C:\users\jdoe\google drive\bin\run.bat", 0, True
But I always get the error:
---------------------------
Windows Script Host
---------------------------
Script: C:\Users\jdoe\Google Drive\bin\script.vbs
Line:1
Char: 1
Error: The system cannot find the file specified.
Code: 80070002
Source: (null)
---------------------------
OK
---------------------------
When I change the path of my run.bat file to c:\run.bat and of course move the run.bat file to c:\, the script.vbs runs without problems.
Any way to get my scripts stored in google drive to run? I have the same issue when using the local group policy editor to select a shutdown or logon/logoff script that is stored in google drive...
Thanks a lot!
CreateObject("Wscript.Shell").Run "C:\users\jdoe\google drive\bin\run.bat", 0, True
^..................^ ^...............^
command to run arguments
You need to quote the the command to avoid problems with spaces
CreateObject("Wscript.Shell").Run """C:\users\jdoe\google drive\bin\run.bat""", 0, True
Remember that a double quote inside a string needs to be escaped, writting two double quotes where one must be included.
To avoid problems with spaces : you must try like this way to get rid of this error that comes from spaces in the path of your application:
Option Explicit
Dim Application
Application = "C:\users\jdoe\google drive\bin\run.bat"
Call RunThis(Application)
'*********************************************************************************
Sub RunThis(Application)
Dim Ws,Result
Set Ws = CreateObject("WScript.Shell")
Result = Ws.Run(DblQuote(Application),0,True)
End Sub
'*********************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************************

VBS WScript.Run fails after passing Exists test

In a couple of place in my code I check if the file exists (it does) then I try to Run the file as above, or get the DateLastModified, and get errors about file not found or invalid path. How can the script NOT see a file after confirming it exists?
I'm working up a .vbs script that tries to run an Access .mdb file. The WScript.Run command seems to choke on the filename, but putting a MsgBox() before that call to display the path allows Run to work properly. I don't want to display a popup.
Error is:
The directory name is invalid.
How is this possible and how can I get around it?
Here is code:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
SET ws = WScript.CreateObject("WScript.Shell")
path = Chr(34) & LocalPath & AccessFileName & Chr(34)
if (fso.FileExists(LocalPath & AccessFileName)) THEN
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run path 'This line errors
End If
Try to open your file with shell .InvokeVerb method:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
If CreateObject("Scripting.FileSystemObject").FileExists(LocalPath & AccessFileName) Then
CreateObject("Shell.Application").Namespace(LocalPath).ParseName(AccessFileName).InvokeVerb
End If
UPD: Both ActiveX WScript.Shell and Shell.Application uses native windows shell to perform a file execution.The first one launches new process via WSH core located in wscript.exe, cscript.exe, wshom.ocx, jscript.dll, vbscript.dll, ets, .Run and .Exec methods of WsShell object provides wide control on the launched process, and second one located in Shell32.dll, uses .InvokeVerb method of IShellDispatch object, called without name, runs default verb equals to the windows explorer "open" command.In case of any issues connected to WSH, explorer might still works without any proplems. If it does, that is just a work-around, I can't say what's wrong definetely without close look.
Hello the following code worked for me.
Basically this code gets a folder object and loops through all files in a folder and checks if its the one that you named. This it runs the application.
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = Wscript.CreateObject("Wscript.Shell")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set myFolder = fso.GetFolder(LocalPath)
For each myFile in myFolder.Files
If myFile.Name = AccessFileName Then
'Wscript.Echo myFile.Name
ws.Run myFolder.Path & "\" & myFile.Name
End If
Next
You can give this a shot. You probably do not need the quotes around the path, but I included it as a comment if you want to give it a shot. You just put quotes twice if you need to include a quote character in a string:
Set fso = CreateObject("Scripting.FileSystemObject")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set ws = WScript.CreateObject("WScript.Shell")
' path = """" & LocalPath & AccessFileName & """" <-- probably unnecessary
path = LocalPath & AccessFileName
If (fso.FileExists(path)) Then
Set file = fso.GetFile(path)
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run file.Path 'This line errors
End If
This does not make any sense. Having a MsgBox line is altering the behavior of the program!!!
I feel it is probably some weird invisible character somewhere which is getting activated when you comment the line.
Try retyping the If block without the MsgBox in between.

cant get local htm file to open with VB-script

Hi Im tryijng to open a local htm file ussing vb script. I have the following code which will work for standard online webpages however my target htm is found localy, and in that case senario i cant get it to work
WORKING:
strURL = "http://www.somesite.com"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(strURL)
NOT WORKING:
strURL = "file://J:\Project Phoenix\Tekenafspraak Tafelhandboek\COMPELATION WITHOUT IMAGES (MASTER)\Tekenafspraak Tafelhandboek.htm"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(strURL)
You need to put quotes around your full path name if there are spaces in it. In this case, it means adding two extra double-quotes at the beginning and end of your string.
And you shouldn't need the "file://" in the path. The Shell object will just open the htm file in your default browser automatically:
strURL = """J:\Project Phoenix\Tekenafspraak Tafelhandboek\COMPELATION WITHOUT IMAGES (MASTER)\Tekenafspraak Tafelhandboek.htm"""
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(strURL)
Quote your spaces. This is spaces 101. What will happen in your script will depend on the configuration of the computer it is run on.

How can I find path of file

In the end, I am trying to return the 'Product Version' of Robocopy.exe (in order to avoid using XP026; broken return code). I can use Shell.Application, NameSpace, ParseName to get the 'Product Version', but I would need to know the NameSpace (folder|directory|path) beforehand.
I can't write a NameSpace path into the script since it will run on different computers and Robocopy.exe could be in one or more directories listed in the system PATH environment variable. I am only interested in the ones found in PATH, and further, the instance that will execute as a result of the WScript.Shell Run method. WScript.Shell Run will execute the first instance found in the system search path when absolute path is not specified. That's the one I'm interested in finding.
My backup plan is to use the where.exe program to find the full path to Robocopy.exe, return it to my vbs script using WScript.Shell Exec oExec.StdOut and extract the path to use as NameSpace in the code above.
I have been searching for a vbs or com control implementation of the winapi searchpath function/method and have had no luck. I'm surprised it's not already implemented in FileSystemObject or Shell.Application. I appreciate any help, referrals, or ideas.
To search the PATH variable for a given file you would have to get value of the variable, split it by the ";" character into an array and then loop through the array of directory paths checking each directory if contains the file you search for. But you can also use a CMD one-liner to achieve that:
sFileName = "robocopy.exe"
Set oShell = WScript.CreateObject("WScript.Shell")
' this will find the file that will be actually run from command line when typed without qualified path
Set oExec = oShell.Exec("cmd /c for %G in (""" & sFileName & """) do #echo.%~$PATH:G")
' this will find all occurances of the file in directories listed in PATH
'Set oExec = oShell.Exec("cmd /c for %G in (""%path:;="" ""%"") do #if exist ""%~dpfxG\" & sFileName & """ echo %~dpfxG\" & sFileName)
Do
line = oExec.StdOut.ReadLine()
WScript.Echo line
' here you can examine the file
Loop While Not oExec.Stdout.atEndOfStream

Resources