How to VBScript find file path? - vbscript

ok so I was creating an HTML that opens without toolbars or anything just by itself but I can't make it work for other computers
this is what I got
set webbrowser = createobject("internetexplorer.application")
webbrowser.statusbar = false
webbrowser.menubar = false
webbrowser.toolbar = false
webbrowser.visible = true
webbrowser.navigate2 ("C:\Users\unknown\Desktop\Folder\myhtml.html")

You should handle that:
The user desktop folder location can be changed
The desktop a user sees is a virtual view of more than one folder in the filesystem. Directly searching for the folder inside the user desktop will leave out the desktop folder configured for all the users.
So, it is better to ask the OS to retrieve the required information
Option Explicit
' folder in desktop and file in folder
Const FOLDER_NAME = "Folder"
Const FILE_NAME = "myhtml.html"
Dim oFolder
Const ssfDESKTOP = &H00&
' Retrieve a reference to the virtual desktop view and try to retrieve a reference
' to the folder we are searching for
With WScript.CreateObject("Shell.Application").Namespace( ssfDESKTOP )
Set oFolder = .ParseName(FOLDER_NAME)
End With
' If we don't have a folder reference, leave with an error
If oFolder Is Nothing Then
WScript.Echo "ERROR - Folder not found in desktop"
WScript.Quit 1
End If
Dim strFolderPath, strFilePath
' Retrieve the file system path of the requested folder
strFolderPath = oFolder.Path
' Search the required file and leave with an error if it can not be found
With WScript.CreateObject("Scripting.FileSystemObject")
strFilePath = .BuildPath( strFolderPath, FILE_NAME )
If Not .FileExists( strFilePath ) Then
WScript.Echo "ERROR - File not found in desktop folder"
WScript.Quit 1
End If
End With
' We have a valid file reference, navigate to it
With WScript.CreateObject("InternetExplorer.Application")
.statusBar = False
.menubar = False
.toolbar = False
.visible = True
.navigate2 strFilePath
End With
You can find more information on shell scriptable objects here

Use the UserName property of the ActiveX-object "WScript.Network" to obtain the name of the current user on the other computers.
As in:
>> sUser = CreateObject("WScript.Network").UserName
>> WScript.Echo "Just for Demo:", sUser
>>
Just for Demo: eh
(That object is different from the WScript object provided by the C|WScript.exe host, so it's usable from other host. Not using the browser (.html), but the mshta.exe host (.hta) - as #omegastripes proposes - is sound advice.)

Related

Get Last Modified Time of a Shared Folder in Windows

I need to check a shared Path for Subfolder\File existence. If it exists need to check whether the LastModified Time of the shared path has exceeded more than 1 hour.
I am getting error "Path not found" for shared path, but the code works fine for Normal Directory.
Here is my code
Dim fso, folder
folder = "C:/test"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folder)
If folder.Files.Count + folder.SubFolders.Count = 0 Then
WScript.Echo "Folder is Empty"
ElseIf (folder.DateLastModified > 60) Then
WScript.Echo "Exceeded 1 hour"
Else
WScript.Echo "Not Exceeded 1 hour"
End If
This code works for the path mentioned in the script, but it throws error "Path not found" for the path \\server.com\subfolder\subfolder\subfolder.
When in doubt, read the documentation. Use the FolderExists method to verify the existence of folders. Use the FileExists method to verify the existence of files.
Don't try to get a folder object unless you have verified it exists. Also, avoid re-using variables for different things.
path = "\\server\share\sub\folder"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(path) Then
Set folder = fso.GetFolder(path)
...
End If
If your using a networked shared folder which requires user permissions to access, you should attempt to make a temporarily added network drive so vbscript can attempt to access it with credentials.
ServerShare = "\\192.168.3.56\d$"
UserName = "domain\username"
Password = "password"
Set NetworkObject = CreateObject("WScript.Network")
Set FSO = CreateObject("Scripting.FileSystemObject")
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
Set Directory = FSO.GetFolder(ServerShare)
For Each FileName In Directory.Files
WScript.Echo FileName.Name
Next
Set FileName = Nothing
Set Directory = Nothing
Set FSO = Nothing
NetworkObject.RemoveNetworkDrive ServerShare, True, False
Set ShellObject = Nothing
Set NetworkObject = Nothing
Stolen from here: Access network share from within VBScript eg FileSystemObject

get the target path from a nethood link

Let's say I have a nethood link to a folder with the name "BLABLA" and the target path is "\\servername\temp"
how do I get the string for the target path?
I tried:
Set oShell = CreateObject("WScript.Shell")
Const NET_HOOD = &H13&
Set oShApp = CreateObject("Shell.Application")
sNetHood = oShApp.NameSpace(NET_HOOD).Self.Path
Set oShortCut = oShell.CreateShortcut(sNetHood & "\" & "BLABLA" & ".lnk")
MsgBox "> " & oShortCut.TargetPath
It does everything, even creates a oShortCut object without any errors.
But, it does not return
oShortCut.TargetPath
what am I doing wrong?
I'd like it to return this: "\\servername\temp\BLABLA"
Thanks in advance for any advice!
I've created the shortcut under win 7 with right click in Computer view of the explorer and then > Add a network location > Next ... etc. It creates a Folder representing a shortcut in NetHood to the path on the server ... it's like a mapped share but not really it.
thx for the input ... after years of reading myself into the matter and then checking google once more i found a c# code which i wrote into vbs and then simplified only to see that all i had to change in the end was to add this:
.GetLink
so the solution to my problem is:
Const NET_HOOD = &H13&
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.NameSpace(NET_HOOD)
For Each oFile In oFolder.Items
MsgBox oFile.GetLink.Path
Next

VBS script 'Path not found' error when setting file system folder object reference

I am writing a script to determine the combined size of all instances of a particular subfolder within the profile folder of each user who has logged onto a Windows 2003 server, e.g. all users' desktop folders or all users' local settings folders.
Option Explicit
Dim colSubfolders, intCount, intCombinedSize, objFolder2, objFSO1, objFSO2, objUserFolder, strOutput, objSearchFolder, objSubfolder, strSearchFolder, strSubfolderPath
intCount = 0
intCombinedSize = 0
strSearchFolder = "C:\Documents and Settings\"
Set objFSO1 = CreateObject("Scripting.FileSystemObject")
Set objSearchFolder = objFSO1.GetFolder(strSearchFolder)
Set colSubfolders = objSearchFolder.SubFolders
For Each objUserFolder in colSubfolders
strSubfolderPath = objUserFolder.Path & "\Desktop\"
Set objFSO2 = CreateObject("Scripting.FileSystemObject")
Set objSubfolder = objFSO2.GetFolder(strSubfolderPath)
intCount = intCount + 1
intCombinedSize = intCombinedSize + objSubfolder.Size
Next
MsgBox "Combined size of " & CStr(intCount) & " folders: " & CStr(intCombinedSize / 1048576) & " MB"
This code throws a 'Path not found' error (Code 800A004C) at line 15:
Set objSubfolder = objFSO2.GetFolder(strSubfolderPath)
If I print out strSubfolderPath, however, I find that all the strings returned are valid directory paths, so I don't understand why I'm getting this error.
I've tried with and without the trailing backslash at the end of the path and I've tried with 8.3 style paths to remove spaces but to no effect.
When I run your code I get the same error.
Upon further inspection, on my computer there is a folder named C:\Documents and Settings\machinename, where machinename is the name of my computer. This folder only contains one subfolder named ASPNet.
I'm guessing you have something similar.
To minimize multiple-backslash confusion, use the FileSystemObject methods consistently instead of relying on string concatenation:
strSubfolderPath = objFSO1.BuildPath(objUserFolder.Path,"Desktop")

Batch command for Browse Folder

I'm new to batch scripting. I want to programmatically browse for a folder and then copy the contents of current directory to the specified directory.
I have a VBScript script (below) that allows me to browse for a folder. How can I link the batch file with it? That is, after the script is run and a folder is selected, the files should be moved to the selected folder. Is it possible?
Here's my VBScript code for browsing for a folder:
Option Explicit
WScript.Echo BrowseFolder( "C:\Program Files", True )
WScript.Echo BrowseFolder( "My Computer", False )
WScript.Echo BrowseFolder( "", False )
Function BrowseFolder( myStartLocation, blnSimpleDialog )
' This function generates a Browse Folder dialog
' and returns the selected folder as a string.
'
' Arguments:
' blnSimpleDialog [boolean] if False, an additional text field will be
' displayed where the folder can be selected
' by typing the fully qualified path
'
' Returns: [string] the fully qualified path to the selected folder
'
' Based on the Hey Scripting Guys article
' "How Can I Show Users a Dialog Box That Only Lets Them Select Folders?"
' http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0617.mspx
'
' Function written by Rob van der Woude
' http://www.robvanderwoude.com
Const MY_COMPUTER = &H11&
Const WINDOW_HANDLE = 0 ' Must ALWAYS be 0
Dim numOptions, objFolder, objFolderItem
Dim objPath, objShell, strPath, strPrompt
' Set the options for the dialog window
strPrompt = "Select a folder:"
If blnSimpleDialog = True Then
numOptions = 0 ' Simple dialog
Else
numOptions = &H10& ' Additional text field to type folder path
End If
' Create a Windows Shell object
Set objShell = CreateObject( "Shell.Application" )
' If specified, convert "My Computer" to a valid
' path for the Windows Shell's BrowseFolder method
If UCase( myStartLocation ) = "MY COMPUTER" Then
Set objFolder = objShell.Namespace( MY_COMPUTER )
Set objFolderItem = objFolder.Self
strPath = objFolderItem.Path
Else
strPath = myStartLocation
End If
Set objFolder = objShell.BrowseForFolder( WINDOW_HANDLE, strPrompt, _
numOptions, strPath )
' Quit if no folder was selected
If objFolder Is Nothing Then
BrowseFolder = ""
Exit Function
End If
' Retrieve the path of the selected folder
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
' Return the path of the selected folder
BrowseFolder = objPath
End Function
Do you want to use the same function in batch as you do with your VBScript? If so I don't think you can use the OpenFileDialog with batch, very easy with Visual Studio and C# (worth looking at). If you want to do it in batch you could use this:
set /p path=Enter folder path:
xcopy /e %cd% %path%
If you realy want to use a batch you can pass the value to an environment variable or write it to io.out to pipe the value out but none of these is advisable. You could also write the value to a temporary textfile and have your batch use that as imput.
Best and most simplest solution is to do the copying in your script itself, plenty of samples for that, more possibilities to respond to erro conditions too.
Let me know if you can't find one, i have one in use but need to strip some data before publishing..

VBS Using createshortcut to get the name of a shortcut with spaces

I'm struggling... used google and have come up with no answers to this one!
I have a code that I'm intending to run at user logon which will find a shortcut and update the shortcut location to reflect some network changes - but the shortcut has spaces in it and VBS won't find the full target path... HELP!!!
The current target of the shortcut is:
\\LANG-APPS2\Mandata\Warehouse\Programs\StartApp.exe /sWH /ip192.168.73.124
But it will only return the bit up to .exe - it misses the last bit of /sWH /ip192.168.73.124
Here's my script:
On Error Resume Next
wscript.echo "Checking Warehouse Shortcut..."
Dim fso, folder, files, sFolder
Set fso = CreateObject("Scripting.FileSystemObject")
Set Shell = CreateObject("WScript.Shell")
sFolder = Shell.SpecialFolders("Desktop")
Set folder = fso.GetFolder(sFolder)
Set files = folder.Files
For each folderIdx In files
fullname = fso.GetAbsolutePathName(folderIdx)
Set shortcut = Shell.CreateShortcut(fullname)
shortTarget = LCase(shortcut.TargetPath)
shortWorkPath = shortcut.WorkingDirectory
lnkFind = ".lnk"
lnkSearch = instr(fullname, lnkfind)
if lnkSearch > 0 then
srvFind = "lang-apps2\mandata\warehouse\programs\startapp.exe"
srvSearch = instr(shortTarget, srvFind)
if srvSearch > 0 then
pracFind = "Practice"
pracSearch = instr(fullname, pracFind)
if pracSearch > 0 then
wscript.echo "Warehouse Practice Shortcut Needs Updating!"
wscript.echo "Please wait while I sort that out for you......"
shortcut.TargetPath = """\\Lang-man\Warehouse\Programs\StartApp.exe /sWHPRAC /ip192.168.73.134"""
shortcut.WorkingDirectory = "\\Lang-man\Warehouse\Programs"
shortcut.save
wscript.echo "Warehouse Practice Shortcut Updated!"
else
wscript.echo "Warehouse Live Shortcut Needs Updating!"
wscript.echo "Please wait while I sort that out for you......"
shortcut.TargetPath = """\\Lang-man\Warehouse\Programs\StartApp.exe /sWH /ip192.168.73.134"""
shortcut.WorkingDirectory = "\\Lang-man\Warehouse\Programs"
shortcut.save
wscript.echo "Warehouse Live Shortcut Updated!"
end if
end if
end if
set shortTarget=nothing
set shortWorkPath=nothing
set shortcut=nothing
next
wscript.echo "Finished"
From the description of the TargetPath property on MSDN (bold added by me):
This property is for the shortcut's target path only. Any arguments to the shortcut must be placed in the Argument's property.

Resources