Get Last Modified Time of a Shared Folder in Windows - vbscript

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

Related

How to VBScript find file path?

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.)

VBScript - relative path not working

I'm trying to use a relative path to reference a cab file named wsusscn2.cab from a VBscript. For some reason, it's not working. The wsusscn2.cab is located in the same directory as the script. Based on the documentation I've read, this SHOULD work, but doesn't:
Set UpdateSession = CreateObject("Microsoft.Update.Session")
Set UpdateServiceManager = CreateObject("Microsoft.Update.ServiceManager")
Set UpdateService = UpdateServiceManager.AddScanPackageService("Offline Sync Service", "..\wsusscn2.cab")
Set UpdateSearcher = UpdateSession.CreateUpdateSearcher()
WScript.Echo "Searching for updates..." & vbCRLF
UpdateSearcher.ServerSelection = 3 ' ssOthers
UpdateSearcher.ServiceID = UpdateService.ServiceID
Set SearchResult = UpdateSearcher.Search("IsInstalled=0")
Set Updates = SearchResult.Updates
If searchResult.Updates.Count = 0 Then
WScript.Echo "There are no applicable updates."
WScript.Quit
End If
WScript.Echo "List of applicable items on the machine when using wssuscan.cab:" & vbCRLF
For I = 0 to searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
WScript.Echo I + 1 & "> " & update.Title
Next
WScript.Quit
Generates this error: The system cannot find the path specified.
try this:
Set UpdateService = UpdateServiceManager.AddScanPackageService("Offline Sync Service", "../wsusscn2.cab")
but be sure that this cab is in the folder one level above the page you calling for it, that is what you have there.
or if cab in the same folder do it like this:
Set UpdateService = UpdateServiceManager.AddScanPackageService("Offline Sync Service", "wsusscn2.cab")
It appears that the .AddScanPackageService() method does not allow relative paths within it's methods. To repair this, while still maintaining flexible code. You can make the path of the script location via Wscript.ScriptFullName and append it infront of wsussc2.cab. This will maintain the path of the script. So it should work as long as the script and .cab file are together.
Set UpdateService = UpdateServiceManager.AddScanPackageService("Offline Sync Service", Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) & "wsusscn2.cab")
When I hit this, I wondered if it might've been service permissions vs file location, but nope, just absolute file paths needed.
I used the FileSystemObject's GetAbsolutePathName function to determine the full path, which allows you to throw random relative paths in (like "..\reports\something\blah.cab" or just "local.cab" if you so desire.)
Set fso = CreateObject("Scripting.FileSystemObject")
CabFileArg = Wscript.Arguments(0) ' (cscript updatecheck.vbs wsusscn2.cab)
CabFileAbs = fso.GetAbsolutePathname(CabFileArg)
Then the usual stuff, just using CabFileAbs instead.
Set UpdateSession = CreateObject("Microsoft.Update.Session")
Set UpdateServiceManager = CreateObject("Microsoft.Update.ServiceManager")
Set UpdateService = UpdateServiceManager.AddScanPackageService("Offline CAB", CabFileAbs , 1)
Set UpdateSearcher = UpdateSession.CreateUpdateSearcher()
… etc

Bad filename or number : vbs error

sry guys m new to programming. I was trying to make a vbscript to cope a vbs file from current location to system startup folder. But m getting the error bad file name or number. but when i give path manually it works like a charm. The path my code is self picking is also correct. Cant understand what is the problem. Please help me. Here is my code.
Set objShell = Wscript.CreateObject("Wscript.Shell")
strMyPath = objShell.SpecialFolders("Startup")
wscript.echo strPath
wscript.echo strMyPath
'Const strMyPath = "C:\Users\Bilal\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"
Const SourceFile = "abc.vbs"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
If fso.FileExists(strMyPath) Then
'Check to see if the file is read-only
If Not fso.GetFile(strMyPath).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile SourceFile, strMyPath, True
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(strMyPath).Attributes = fso.GetFile(strMyPath).Attributes - 1
'Replace the file
fso.CopyFile SourceFile, strMyPath, True
'Reapply the read-only attribute
fso.GetFile(strMyPath).Attributes = fso.GetFile(strMyPath).Attributes + 1
End If
Else
'The file does not exist in the destination folder. Safe to copy file to this folder.
fso.CopyFile SourceFile, myStrPath, True
End If
Set fso = Nothing
Ok. So it should look like this:
Set objShell = Wscript.CreateObject("Wscript.Shell")
strPath = objShell.SpecialFolders("Startup")
strMyPath = strPath&"\"
Const SourceFile = "abc.vbs"
strMyPath = strMyPath & SourceFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
If fso.FileExists(strMyPath) Then
'Check to see if the file is read-only
If Not fso.GetFile(strMyPath).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile SourceFile, strMyPath, True
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(strMyPath).Attributes = fso.GetFile(strMyPath).Attributes - 1
'Replace the file
fso.CopyFile SourceFile, strMyPath, True
'Reapply the read-only attribute
fso.GetFile(strMyPath).Attributes = fso.GetFile(strMyPath).Attributes + 1
End If
Else
'The file does not exist in the destination folder. Safe to copy file to this folder.
fso.CopyFile SourceFile, strMyPath, True
End If
Set fso = Nothing
To make
If fso.FileExists(strMyPath) Then
'work', strMyPath must contain a valid file specification. As far as I can see, in your code it contains the path to the (destination?) folder.
Use properly named variable (names)s that make clear whether they hold folder or file specs.

How to run command to set credentials from within vbs script using system account?

Salvete!
On my server I am running hMailServer, and that service uses the local system account.
I need to copy a file to another machine. So I have this a script that will use cmdkey.exe to save the credentials and then copy the file.
If I run this function myself (in a standalone vbs file) whilst logged into the server, it works, but I am admin.
However, if I let the hMailServer service run this function, the function runs, but it always says the destination does not exist.
Notice I have commented out the deletion of the credentials. If I go to the server and run cmdkey /list I see that the credentials were never set, which means the command failed. That means the first setting of the credentials probably failed too, which is why 'objFSO' cannot find the directory.
Again, if I put all this in a separate file and run it as test.vbs by double-clicking the file, it works. But if I use it from within hMailServer, it fails.
I suppose this means the hMailServer (local system account) doesn't have rights to set credentials? How do I get this to work?
option explicit
dim SPcopyMessage
SPcopyMessage = CopyFileToRemoteMachine("SERVER", "mydomain\username", "password", "c:\test2.txt", "\\SERVER\somefolder\otherfolder")
MsgBox SPcopyMessage
function CopyFileToRemoteMachine(whatMachine, whatUsername, whatPassword, whatSourceFile, whatDestination)
dim errormessage, CredentialCreate, CredentialDelete
errormessage = "Sharepoint Mail Delivered"
CredentialCreate = "cmd.exe /c cmdkey /add:" & whatMachine & " /user:" & whatUsername & " /pass:" & whatPassword
Dim objShell, objFSO
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
CALL objShell.Run(CredentialCreate, 0, True) 'add username to the credentials list
If objFSO.FileExists(whatSourceFile) Then
If objFSO.FolderExists(whatDestination) Then
If Right(whatDestination, 1) <> "\" Then
whatDestination = whatDestination & "\"
End If
objFSO.CopyFile whatSourceFile, whatDestination, True
Else
errormessage = "Destination does not exist: " & whatDestination
End If
Else
errormessage = "Source file does not exist: " & whatSourceFile
End If
'CredentialDelete = "cmd.exe /c cmdkey /delete:" & whatMachine
'CALL objShell.Run(CredentialDelete, 0, True)
set objFSO = nothing
set objShell = nothing
CopyFileToRemoteMachine = errormessage
end function
Figured out a way! First, I made sure the destination was shared to the right user account on machine2. Then made the script on machine1 to map the network drive and then copy the file. This will work as long as the N drive is never used for anything else on that machine.
Here is the code is if be helpful to anyone!
function CopyFileToRemoteMachine(whatMachine, whatUsername, whatPassword, whatSourceFile, whatDestination)
dim errormessage, mdrive
errormessage = "File successfully copied"
mdrive = "N:"
Dim objFSO, objNetwork
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("Wscript.Network")
If not objFSO.FileExists(mdrive) Then
objNetwork.MapNetworkDrive mdrive, whatDestination, False, whatUsername, whatPassword
End If
If Right(whatDestination, 1) <> "\" Then
whatDestination = whatDestination & "\"
End If
If objFSO.FileExists(whatSourceFile) Then
If objFSO.FolderExists(whatDestination) Then
objFSO.CopyFile whatSourceFile, whatDestination, True
Else
errormessage = "Destination does not exist: " & whatDestination
End If
Else
errormessage = "Source file does not exist: " & whatSourceFile
End If
objNetwork.RemoveNetworkDrive mdrive,TRUE,TRUE
set objFSO = nothing
set objNetwork = nothing
CopyFileToRemoteMachine = errormessage
end function

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")

Resources