TargetPath is blank - on remote drives - vbscript

I can't seem to get the WShell to return a value for objShortcut.TargetPath, although it passes the full name fine.
I've been reading that the WShell can have issues with remote disks, and I had been using an external drive.
After testing it on shortcuts on my C: drive with files located on my C: drive, I am finding it still does not work. Instead of echoing the traget path, it echos a blank value.
Edited. Thanks for the tip.
getshorty.vbs
Dim objWSHShell
set objWSHShell = CreateObject("WScript.Shell")
Set wshShell = WScript.CreateObject("WScript.Shell")
strTargetPath=objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
Set objShortcut = wshShell.CreateShortcut(strTargetPath)
WScript.Echo objShortcut.TargetPath
Set objShortcut = Nothing
Set wshShell = Nothing

This a function to create a shortcut :
Call Shortcut("C:\The Absolute Path of your application goes here","Name of your Shortcut")
'*********************************************************************************
Sub Shortcut(PathApplication,Name)
Dim objShell,DesktopPath,objShortCut,MyTab
Set objShell = CreateObject("WScript.Shell")
MyTab = Split(PathApplication,"\")
If Name = "" Then
Name = MyTab(UBound(MyTab))
End if
DesktopPath = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(DesktopPath & "\" & Name & ".lnk")
objShortCut.TargetPath = Dblquote(PathApplication)
ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,-25"
objShortCut.Save
End Sub
'*********************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************************

Of course, TargetPath property results to "" (a string of zero length) if the .lnk or .url file does not exist.
The CreateShortcut method returns either a WshShortcut object or a WshURLShortcut object. Simply calling the CreateShortcut method opens an existing shortcut but does not result in the creation of a shortcut.
option explicit
On Error GoTo 0
Dim wshShell, strTargetPath, objShortcut
Set wshShell = WScript.CreateObject("WScript.Shell")
strTargetPath = wshShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
Set objShortcut = wshShell.CreateShortcut(strTargetPath)
WScript.Echo TypeName(objShortcut) & vbTab & VarType(objShortcut) _
& vbNewLine & "FullName" & vbTab & objShortcut.FullName _
& vbNewLine & "TargetPath" & vbTab & objShortcut.TargetPath
If TypeName(objShortcut) = "IWshShortcut" Then
WScript.Echo "Arguments" & vbTab & objShortcut.Arguments _
& vbNewLine & "Description" & vbTab & objShortcut.Description _
& vbNewLine & "WorkingDir" & vbTab & objShortcut.WorkingDirectory
End If
Output
==>dir /B d:\xxxx\*Shortcut.*
32421790 Shortcut.url
pisma - Shortcut.lnk
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\32421790 Shortcut.url"
IWshURLShortcut 8
FullName d:\xxxx\32421790 Shortcut.url
TargetPath http://stackoverflow.com/q/32421790/3439404
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\nonexistent Shortcut.url"
IWshURLShortcut 8
FullName d:\xxxx\nonexistent Shortcut.url
TargetPath
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\pisma - Shortcut.lnk"
IWshShortcut 8
FullName d:\xxxx\pisma - Shortcut.lnk
TargetPath D:\bat\SU\Files\ruzna pisma.png
Arguments
Description font samples
WorkingDir D:\bat\SU\Files
==>cscript D:\VB_scripts\SO\32421790.vbs "d:\xxxx\nonexistent Shortcut.lnk"
IWshShortcut 8
FullName d:\xxxx\nonexistent Shortcut.lnk
TargetPath
Arguments
Description
WorkingDir
==>

Related

Make all VBS files into one

I'm trying to compile all my many VBS files into one, but I can't figure out how to do it.
Set sapi = CreateObject("SAPI.SPvoice")
Set wshShell = WScript.CreateObject("WScript.Shell")
Set ChosenVBS = InputBox("Enter your message", "Choose What to run.")
Set WshShell = CreateObject("WScript.Shell")
Sub Speak
Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn, intWindowStyle
ProgramPath = "D:\Spam\Speak.vbs"
ProgramArgs = ""
intWindowStyle = 1
WaitOnReturn = True
WshShell.Run Chr(34) & ProgramPath & Chr(34) & Space(1) & ProgramArgs, _
intWindowStyle, WaitOnReturn
End Sub
Call ChosenVBS
How I'm trying to do it currently, the Set are for all the codes I'm going to put in.

subscript out of range in vbscript

I am working on a script to check on folder share where I will pass the folder location as variable to the script (example: Script.vbs D:\share)but when I run it I got an error "subscript out of range vbscript 800a0009"
Script given below,
Const EVENT_TYPE_ERROR = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4
Set oParameters = WScript.Arguments
Set WshShell = WScript.CreateObject("WScript.Shell")
ShareName = oParameters(6)
clog = "Windows Share"
Source = "ShareSecurity"
Dim WshShell
Set objShell = CreateObject("WScript.Shell")
set ObjExec = objShell.exec("icacls """"& ShareName & """"")
Set objStdOut = ObjExec.StdOut
While Not objStdOut.AtEndOfStream
strLine = objStdOut.ReadLine
If InStr(strLine,"Everyone") Then
set ObjExec1 = objShell.exec("icacls """"& ShareName & """"")
completeshare = ObjExec1.StdOut.ReadAll()
strCommand = "eventcreate /T Error /ID 422 /L " & Chr(34) & Clog & Chr(34) & " /SO " & source & " /D " & Chr(34) & completeshare & "Network share with Every one access is created and the information is given below" & Chr(34)
WshShell.Run strcommand
End If
Wend
wscript.quit
Read and follow docs: Arguments Property (WScript Object):
The Arguments property contains the WshArguments object (a
collection of arguments). Use a zero-based index to retrieve
individual arguments from this collection.
Hence, in case of expected Script.vbs D:\share (or Script.vbs "D:\share"), use next code snippet:
Set oParameters = WScript.Arguments
If oParameters.Count > 0 Then
ShareName = oParameters(0)
Else
' usage prompt and then `Wscript.Quit`, or
ShareName = "some default value"
End If
Const EVENT_TYPE_ERROR = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4
Dim WshShell, ShareName
Set oParameters = WScript.Arguments
Set WshShell = WScript.CreateObject("WScript.Shell")
ShareName = oParameters(6)
clog = "Application"
Source = "EventCreate"
Set objShell = CreateObject("WScript.Shell")
set ObjExec = objShell.exec("icacls """& ShareName &"""")
Set objStdOut = ObjExec.StdOut
While Not objStdOut.AtEndOfStream
strLine = objStdOut.ReadLine
If InStr(strLine,"Everyone") Then
set ObjExec1 = objShell.exec("icacls """& ShareName &"""")
completeshare = ObjExec1.StdOut.ReadAll()
strCommand = "eventcreate /T Error /ID 425 /L " & Chr(34) & Clog & Chr(34) & " /SO " & source & " /D " & Chr(34) & "Network share with Every one access is created and the information is given below " & Chr(13) & Chr(13) & completeshare & Chr(34)
'strCommand = "eventcreate /T Error /ID 1999 /L APPLICATION /D" & Chr(34) & "Network share with Every one access is created and the information is given below " & Chr(13) & Chr(13) & completeshare & Chr(34)
WshShell.Run strcommand
End If
Wend
wscript.quit
This one worked when I parsed the variable like below,
script.vbs 1 2 3 4 5 6 D:\share
Worked !!!!
Thanks all for your valuable inputs.
This:
ShareName = oParameters(6)
Should be this:
ShareName = oParameters(0)

create folder(trusted), copy of MDE and shortcut

I have put together a script that I think will work, but the only code I know is some VBA. Never tried to create a vbscript before, so my apologies if some errors are obvious, but pointers and corrections would be appreciated.
I am hoping I can give users in my company a link to this script and have them run it. It will create a folder on their C Drive, make it a trusted location, copy a database frontend from the server into it and create a shortcut on their desktop linking to the new file. (I'm hoping the file will auto-update when a new version is made - I think that bit works though).
The code comes from various sources, including my own addled mind but would I need to download Visual Studio to test this? Slightly concerned as it includes creating a registry key and I don't know how to stop the code if it all goes horribly wrong. I don't even know how to break a loop (although I think I read somewhere you need to hit Esc twice). Any tips on how to signify which sub is the main one to run on start would be good too.
EDIT : Code has been amended to my end result incase it is of use to others. Please use with caution. The 'update' vbs deletes the folder created on the local drive.
'FrontEnd Setup
call CreateTrustedFolder
'Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
'Const HKEY_LOCAL_MACHINE = &H80000002
'Const HKEY_USERS = &H80000003
'Const HKEY_CURRENT_CONFIG = &H80000005
Dim lclFolder
Dim blnUpdate
Sub CreateTrustedFolder()
On error resume next
Call RunAdmin
Call FolderFileShortcut
Call CreateReg
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
'Run as Administrator
Sub RunAdmin()
On error resume next
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
'Check if folder exists, add file and desktop shortcut
Sub FolderFileShortcut()
On error resume next
Dim oWS
Dim FSO
Dim svrFolder
Dim myShortcut
Dim strLocalDB
Dim strServerDB
Dim strUpdate
Dim strIcon
Dim objFile
Dim counter
Set oWS = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
svrFolder = "\\192.168.1.2\DeptFolder\DatabaseFolder\Auto-Update"
lclFolder = "C:\Program Files\Orrible Database"
If (FSO.FolderExists(lclFolder)) Then
oWS.run "icacls """ & lclFolder & """ /reset /grant:r Users:(W) /t" '/T required for existing folders
FSO.DeleteFolder lclFolder
blnUpdate = True
end if
If Not (FSO.FolderExists(svrFolder)) Then
msgbox "Unable to connect to Location Server", vbCritical, "Installation Failed"
WScript.Quit
End If
For Each objFile in FSO.Getfolder(svrFolder).Files
if LCase(FSO.GetExtensionName(objFile.name)) = LCase("mde") then
counter = counter + 1
strServerDB = FSO.GetFileName(objFile)
end if
Next
If strServerDB = "" or counter <> 1 then
msgbox "Unable to locate the Front End" & strServerDB & "-" & counter, vbCritical, "Installation Failed"
wScript.Quit
end if
strLocalDB = "Co Database.mde"
strUpdate = "DB_UpdateCheck.vbs"
strIcon = "Frontend Update.ico"
FSO.CreateFolder(lclFolder)
oWS.run "icacls """ & lclFolder & """ /grant Users:(OI)(CI)F /t" '/T required for existing folders
FSO.CopyFile svrFolder & "\" & strUpdate, lclFolder & "\" & strUpdate, True
FSO.CopyFile svrFolder & "\" & strServerDB, lclFolder & "\" & strLocalDB, True
FSO.CopyFile svrFolder & "\" & strIcon, lclFolder & "\" & strIcon, True
strDesktop = oWS.SpecialFolders("Desktop")
set myShortcut = oWS.CreateShortcut(strDesktop + "\New Database.lnk")
myShortcut.TargetPath = lclFolder & "\" & strUpdate
myShortcut.WindowStyle = 1
myShortcut.IconLocation = lclFolder & "\" & strIcon
myShortcut.WorkingDirectory = strDesktop
myShortcut.Save
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
Sub CreateReg()
On error resume next
Dim objRegistry 'registry object
Dim strDescription 'Description of the Trusted Location
Dim strParentKey 'Registry location of Application
Dim strNewKey 'strParentKey and myFolder
Dim oWS 'WSH shell object
strDescription = "DB Folder"
strParentKey = "Software\Microsoft\Office\15.0\Access\Security\Trusted Locations"
strNewKey = strParentKey & "\" & strDescription & "\"
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
'objRegistry.GetStringValue HKEY_CURRENT_USER, strParentKey & "\" & strDescription
If Not objRegistry.EnumKey(HKEY_CURRENT_USER, strNewKey) = 0 then '0=true
objRegistry.CreateKey HKEY_CURRENT_USER, strNewKey
objRegistry.SetStringValue HKEY_CURRENT_USER, strNewKey, "Path", lclFolder
objRegistry.SetStringValue HKEY_CURRENT_USER, strNewKey, "Description", strDescription
End if
If not blnUpdate = True then
msgbox "The Database is now available from your desktop", vbInformation, "Setup Complete"
Else
msgbox "The update is now complete."
End if
if err then
MsgBox "The following error has occurred " & Err & " " & Err.Description
exit Sub
end if
End Sub
There is also a separate Update vbs which is what runs when the link is clicked. This checks to see if the 'created date' of the database on the server is newer than that on the local drive. The new DB name MUST NOT be the same as the one it is replacing. It might run a little fast, but this is as far as I have taken this.
Call CheckForUpdate
Sub CheckForUpdate()
On Error Resume Next
Dim FSO
Dim oWS
Dim svrFolder
Dim lclFolder
Dim svrFail
Dim strLocalDB
Dim strServerDB
Dim lclDate
Dim svrDate
Dim strFileName
Dim intDBcount
Dim fCheck
Set oWS = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
svrFolder = "\\192.168.1.2\DeptFolder\DatabaseFolder\Auto-Update"
lclFolder = "C:\Program Files\Orrible Database"
strLocalDB = "Co Database.mde"
If Not (FSO.FolderExists(svrFolder)) Then
msgbox "Unable to connect to Location Server", vbCritical, "Update Check Failed"
svrFail = True
End If
If Not svrFail = True Then
For Each fCheck in FSO.GetFolder(svrFolder).Files
If Ucase(Right(fCheck.Name, 3)) = "MDE" Then
intDBcount = intDBcount + 1
strServerDB = fCheck.name
End If
Next
If Not intDBcount = 1 Then
MsgBox "Please inform the Administrator that there is a problem with the Automated Update System.", _
vbCritical, "Update Failed (" & intDBcount & ")"
svrFail = True 'not quit - need to see if old version available
End If
End If
If Not (FSO.FolderExists(lclFolder)) Then
If svrFail = True Then 'If no lcl folder or server
If Not intDBcount = 1 then WScript.Quit
msgbox "You are unable to use the Database." & vbcrlf & _
"Please try again when you have access to the Location Server.", _
vbcritical, "Database Not Installed"
WScript.Quit
Else 'If no lclfolder, get it from svr
'Do normal initial install
oWS.Run svrFolder & "\" & "DB_Install.vbs", 1, True
WScript.Quit
End If
Else
If svrFail = True Then 'If lcl folder, but no svr
'open db
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
Else 'If lcl folder and svr access, check for update.
lclDate = fso.getfile(lclFolder & "\" & strLocalDB).DateCreated
svrDate = fso.getfile(svrFolder & "\" & strServerDB).DateCreated
If lclDate < svrDate Then 'Update available
intMsg = MsgBox("An update is available - Do you wish to update now?", vbQuestion + vbYesNo, "Update Found")
If intMsg = vbYes Then
oWS.Run svrFolder & "\" & "DB_Install.vbs", 1, True ',1,true should pause the code until install closes
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
Else
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
End If
Else
oWS.Run CHR(34) & lclFolder & "\" & strLocalDB & CHR(34)
WScript.Quit
End If
End If
End If
If err Then
MsgBox "The following error has occurred " & Err & " " & Err.Description
Exit Sub
End If
End Sub

Get a VBS file to scan computer for a file

This is my first post, but I have been programming for a long time now
I just want to ask a quick question and the title explains it all. I want my VBS to run a file, but I dont want it to search just for a specific directory, I want it to just find the file if you know what I mean, because if I gave the script to anyone else, this file could be ANYWHERE on their computer.
This is the current couple of important lines that I am using for running files:
set wshshell = wscript.CreateObject("wscript.shell")
and
wshshell.run <program directory here>
You need a recursive function like this one searching for shortcuts.
Sub GenerateHotkeyInFolder(Fldr)
on error resume next
set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set FldrItems=Fldr.Items
For Each oFile in FldrItems
With oFile
If .IsFileSystem = true And .IsLink = true And .Type <> "Shortcut to MS-DOS Program" then
set lnk = WshShell.CreateShortcut(oFile.Path)
If lnk.hotkey <> "" then
Set fsop = fso.GetFile(.Path)
LnkName = "<b>" & fso.GetBaseName(fso.GetFile(.Path)) & "</b><br>" & fsop.ParentFolder.path & "\" & fso.GetBaseName(fso.GetFile(.Path)) & "." & fso.GetExtensionName(fso.GetFile(.Path))
TableVar = TableVar & "<tr><td><b>" & lnk.hotkey & "</b></td><td><a class=TblURL onmouseover='MakeRed()' onmouseout='MakeBlack()' onclick='FindShortcut(" & Chr(34) & lnk.fullname & Chr(34) & ")'>" & lnkname & "</a>" & "</td><td><a class=TblURL onmouseover='MakeRed()' onmouseout='MakeBlack()' onclick='FindShortcut(" & Chr(34) & lnk.targetpath & Chr(34) & ")'>" & lnk.targetpath & "</a></td></tr>" & vbcrlf
End If
ElseIf .IsFileSystem = true And .IsFolder = true then
GenerateHotkeyInFolder(.GetFolder)
End If
End With
Next
End Sub

Convert A Robocopy Command to VB Script

I used to use a line in Robocopy that would allow me to copy all folders in a folder INCLUDING the parent folder, I.E all files/folders in the Blackberry folder INCLUDING the Blackberry folder itself, else without it it would just copy the files within and dump them in the backup location...
The code used was;
for %%a in ("%source%") do SET destination="Backups\%date%\%%~nxa"
Now in VB Script I've got;
sSource = Chr(34) & objFolder.self.Path & Chr(34) & " "
So how would I go about having VB Script (which still calls Robocopy) use the above so that when it backs up it will include the PARENT folder as well?
This was the code I had; Converting Robocopy Batch To VB Script
Thanks in advance!
EDIT: The current content of my script file;
Dim BrowseBackupSource
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Please browse to the folder you would like to backup.", 1, "C:\")
If objFolder Is Nothing Then
Wscript.Quit
End If
wscript.Echo "folder: " & objFolder.title & " Path: " & objFolder.self.path
Dim BrowseBackupLocation
Set objShell = CreateObject("Shell.Application")
Set objDest = objShell.BrowseForFolder(0, "Please browse to the folder you would like to save the backup to.", 1, "C:\")
If objDest Is Nothing Then
Wscript.Quit
End If
wscript.Echo "folder: " & objDest.title & " Path: " & objDest.self.path
sCmd = "%windir%\System32\Robocopy.exe "
sDate = Day(Now) & "-" & Month(Now) & "-" & Year(Now)
sTime = Hour(Now) & "-" & Minute(Now) & "-" & Second(Now)
sSource = Chr(34) & objFolder.self.Path & Chr(34) & " "
sDestination = Chr(34) & objDest.self.Path & Chr(34) & " "
sSwitches = "/E /Log:"& sTime &".txt"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(sCmd & sSource & sDestination & sSwitches)
Well, if you need the path to the parent folder to set as root of copy:
dim parentFolderPath
parentFolderPath = WScript.CreateObject("Scripting.FileSystemObject").GetFolder(objFolder.self.Path).ParentFolder.Path
EDIT
You need the name of the selected source directory added to the path of the selected destination so
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
sSourceFolderName = fso.GetFolder(objFolder.self.Path).Name
sDestination = Chr(34) & objDest.self.Path & "\" & sSourceFolderName & Chr(34)
Robocopy will handle the target directory creation
If you want to create a copy of a particular folder for backup, why don't you simply copy that folder to the backup destination and be done with it?
Set fso = CreateObject("Scripting.FileSystemObject")
Set app = CreateObject("Shell.Application")
dst = "C:\backups\" & Year(Now) & "\" & Month(Now) & "\" & Day(Now)
CreatePath dst
Set fldr = app.BrowseForFolder(0, "Example", 1, "c:\Programs")
fso.CopyFolder fldr.Self.Path, dst & "\", True
Sub CreatePath(p)
If Not fso.FolderExists(p) Then
CreatePath fso.GetParentFolderName(p)
fso.CreateFolder p
End If
End Sub

Resources