Overcome Permissions Errors When Traversing the File System - recursion

I am building a VBScript to search for and record the locations of files that have been copied out of a home directory (duplicates).
I currently have a script that recursively searches the C drive and records all file locations to a log file. (This is not elegant, but I am still working on a proof of concept.)
As I iterate through the file system, however, I find that there are a great many folders the script cannot even view- Appdata, Local Settings, My Videos, My Pictures, etc.
So of these are obviously inaccessible to the user, but the user has ownership over the folders in My Documents, so I cannot determine why my script cannot even read their contents. The user is a local administrator.
I have tried running the script with elevated permissions by adding this snippet to the beginning with no change in behavior:
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
This is a salient Function in the script, with the line that errors out notated (please let me know if another portion would be of aid):
' Get list of ALL files recursively and record them in a text file
Function getAllFilesRecursively (specifiedFolder, logLocation)
If (Right(specifiedFolder,7)<>"AppData") And _
(Right(specifiedFolder,16)<>"Application Data") And _
(Right(specifiedFolder,7)<>"Cookies") And _
(Right(specifiedFolder,14)<>"Local Settings") Then
' Get list of files in current folder
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(specifiedFolder.Path)
Set colFiles = objFolder.Files
'This function writes to a specified log file, using the specified method
writeToFile specifiedFolder, logLocationTemp, "Append"
' For each file, perform a task
For Each objFile in colFiles '(<<<<<<<<<<<<<<<<<<<< permissions error)
' Compose the full path to the file
fullPath = specifiedFolder & "\" & objFile.name
'Save the path to a text file (a newline is automatically added)
writeToFile fullPath, logLocation, "Append"
Next
' For each folder, Recurse
For Each Subfolder in specifiedFolder.SubFolders
getAllFilesRecursively Subfolder, logLocation
Next
End If
End Function
Is there any way for me to allow this script access to these folders? The computer is on a domain but I can make whatever modifications necessary (even policies).

The folders that are giving you errors probably aren't actual folders, but symbolic links to folders. They exist for compatibility reasons and have an ACE "everyone deny list folder, this folder only" on them to prevent people from browsing. Don't tamper with them. Make an exclusion list to prevent your script from trying to traverse them.
Set exclude = CreateObject("Scripting.Dictionary")
exclude.CompareMode = vbTextCompare
exclude.Add "Application Data", True
exclude.Add "Local Settings", True
...
Function getAllFilesRecursively (specifiedFolder, logLocation)
...
For Each Subfolder in specifiedFolder.SubFolders
If Not exclude.Exists(Subfolder.Name) Then
getAllFilesRecursively Subfolder, logLocation
End If
Next
End Function

Related

VBScript FileExists fails consistantly

We're trying to read some log files for our application but FileExists is failing in every case. So I simplified the problem with this test code:
Dim filespec, msg
filespec = Chr(34) & "C:\Windows\explorer.exe" & Chr(34)
'filespec = "C:\Windows\explorer.exe"
'filespec = Chr(34) & "C:" & Chr(34)
'filespec = "C:"
'filespec = "default.asp"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
Response.Write(msg)
As you can see, we've tried testing with and without added Chr(32) (which is the double quote character). We're testing against the file C:\Windows\explorer.exe and the file C:\Windows\explorer.exe does exist on the computer hosting the asp files and the iis server. We even fail when simply checking to see if the C drive exist.
Additionally, it even fails if we try to see if the default.asp file exists and that file is in the same directory as our filetest.asp file.
Does anyone see why our FileExists is consistently failing? Thank you.
filespec = "C:\Windows\explorer.exe"
Without the additional quotes will work. To find a folder we need to use
fso.FolderExists
Instead of FileExists.
This still doesn't find the default.asp file in the same directory. But that problem is too far removed from our actual problem which is to look at log files on another drive. That problem is too far from this original question so I'll post that problem separately.
You may want to try to load the folder in to a folder object and loop through files in the folder object. Below is an example.
Set fso = CreateObject("Scripting.FileSystemObject")
FileToFind = "explorer.exe"
FolderToSearch = "C:\Windows\"
Set myFolder = fso.GetFolder(FolderToSearch)
For each myFile in myFolder.Files
If myFile.Name = FileToFind Then
Wscript.echo "Found " & myFolder.Path & "\" & myFile.Name
End If
Next
you do not need to insert additional quotes. removing your quotes will work just fine.
Dim filespec, msg
filespec = "C:\Windows\explorer.exe"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
Response.Write(msg)
In the past, I have only noticed that you need to insert additional quotes when using the wshshell.run since a space might be interpreted as additional arguments to the filename.
It appears that our problem is not in the VBScript at all. The app is running inside an ApplicationPool in iis. The Identity property of that Application Pool is the dynamically created applicationPoolIdentity user. This is a user with no permissions. So essentially, the application is running as a user which does not have access to any other drives. Therefore, it cannot find any file on any network drive. We will have to create an additional identity with the proper rights and set our applicationPool identity to use that custom account.
I found instructions on how to set this identity account here: http://technet.microsoft.com/en-us/library/cc771170%28v=ws.10%29.aspx

Web server ignores savepath and saves to wwwroot, while localhost works perfectly

When I try to use FileUpload1.SaveAs(savePath), it works very strangely.
When using localhost, it uses the savePath perfectly. I have used a variety of paths and syntaxes to confirm this. However, when I publish this to my website, and use the upload feature there, it saves the file to the wwwroot folder, and nowhere else.
In fact, no matter what the path is specified, it ALWAYS saves to wwwroot, even when I tell it otherwise.
Sub SaveFile(ByVal file As HttpPostedFile)
' Specify the path to save the uploaded file to.
Dim savePath As String = Server.MapPath("\uploads\")
' Get the name of the file to upload.
Dim fileName As String = FileUpload1.FileName
' Create the path and file name to check for duplicates.
Dim pathToCheck As String = savePath + fileName
' Create a temporary file name to use for checking duplicates.
Dim tempfileName As String
' Check to see if a file already exists with the
' same name as the file to upload.
If (System.IO.File.Exists(pathToCheck)) Then
Dim counter As Integer = 2
While (System.IO.File.Exists(pathToCheck))
' If a file with this name already exists,
' prefix the filename with a number.
tempfileName = counter.ToString() + fileName
pathToCheck = savePath + tempfileName
counter = counter + 1
End While
fileName = tempfileName
' Notify the user that the file name was changed.
UploadStatusLabel.Text = "A file with the same name already exists." + "<br />" + _
"Your file was saved as " + fileName
Else
' Notify the user that the file was saved successfully.
UploadStatusLabel.Text = "Your file was uploaded successfully."
End If
' Append the name of the file to upload to the path.
savePath += fileName
' Call the SaveAs method to save the uploaded
' file to the specified directory.
FileUpload1.SaveAs(savePath)
End Sub
Once I get through this problem, I would like the path to be going to a virtual directory, which I have already created through IIS, but because of this problem, I can not test it.
would it work like,
Dim savePath As String = Server.MapPath("~/uploads/")
just check by changing direction of slash to /
I figured out that the changes to the upload process were not being fully changed unless I deleted the files in root, and republished them. Publishing the changes without deleting the initial files did not fix the upload process. Still somewhat mysterious, but at least I found a hard fix to the problem. Likely a change is made in web.config, or another file, which causes the changes to not fully occur unless a fresh start was made.

check file existence in FreeASPUpload

I want to check file if i uploaded it before. If file exist, i want to upload with different name. How to do this?
on error resume next
Set Upload = New FreeASPUpload
<!-- Upload.OverwriteFiles = False-->
Upload.Save(UploadPathValue)
if err <> 0 then
Response.Write(err.description)
end if
You will need to use the filesystemobject to check if the file exists before saving it.
Here is an explanation of how to do this: ASP fileexists

Change all users attribute in a domain in Active Directory recursively

I've got a little script (VBS) to change website attribute of all users :
dim objOU, objUser
objOU="OU=Users,DC=mysociety,DC=local"
Set objOU = GetObject("LDAP://" & objOU)
on error resume next
For each objUser in objOU
If objUser.Class="user" Then
Set objUser = GetObject("LDAP://" & objUser.distinguishedName)
objUser.Put "wWWHomePage", "http://mysite.mysociety.local/Person.aspx?accountname=mysociety\" & objUser.mailNickname
objUser.setInfo
if err.number <> 0 then
wscript.echo "Error processing " & objUser.givenName & ":" & err.number & ", " & err.Description
err.clear
end if
End if
Next
So my problem is that if I precise my objOU up to deepest directories it works perfectly. But it is not a recursive script and with this code it doesn't work because of subdirectories.
I am a very beginner with VBS, could you help me to make this script recursive ?
Thank you by advance and excuse me for my poor English
This task can be accomplished very efficiently using threads. In one thread, execute a search
wherein the base object is that point in the directory information tree (DIT) below which all
the entries that must be modified are stored. Use whole subtree for the search scope and a
filter that narrows the search results to just the entries that require modification. Use the
OID 1.1 for the list of requested attributes (this will cause the directory server to return
only distinguished names). Assuming the directory administrator allows this search - it may be
denied for resource reasons or security reasons or other reasons - as the search results arrive,
use another thread to construct the modifications on the distinguished names that are being
returned in the search thread. For maximum efficiency, use multiple threads to make the
modifications and use the appropriate concurrence mechanisms for your API.
see also
LDAP: Programming practices
LDAP: Search Best practices

Trying to retrieve spreadsheet from asp site without any prompts

I have a company site that publishes large reports which I pull down and split up into what I need. I can get the webpage open and get the link to the spreadsheet I need opened, but then I get one IE pop-up for open/save/cancel and, when I click to open the spreadsheet, I get a second pop-up (this one from Excel) saying that the spreadsheet is in a different format than specified by the extension." I have no idea how, if possible, to get the first pop-up to away; the only way I know to normally prevent pop-ups with excel is with DisplayAlerts=False, but adding that doesn't seem to have any effect. The code for the start of this automation project follows:
[EDIT] I have edited and replaced the original coding to reflect the most recent attempt at this. I have managed to get past the first file download pop-up (though with the use of sendkeys) and am now working on getting the second pop-up taken care of (which I suppose is a matter of shifting focus back to excel). Any suggestions on replacing the sendkeys portion are definitely welcomed, as well as advice for returning focus to excel so that I can use excel to control the second pop-up (if that's the best way to do it). The updated code follows:
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Sub Automation()
Dim IeApp As Object
Dim IeDoc As Object
Dim URL, URL2 As String
Application.DisplayAlerts = False
URL = "https://companysite.com/directorypage/default.aspx"
URL2 = "https://companysite.com/directorypage/Reports/MyReport.aspx?Format=Excel"
Set IeApp = CreateObject("InternetExplorer.Application")
IeApp.Visible = True
IeApp.Navigate URL
While IeApp.Busy Or IeApp.ReadyState <> 4: DoEvents: Wend
IeApp.Document.All.Item("MainContent_btnAuthenticate").Click
While IeApp.Busy Or IeApp.ReadyState <> 4: DoEvents: Wend
Set IeApp = CreateObject("InternetExplorer.Application")
IeApp.Visible = False
IeApp.Navigate URL2
Do Until thewindow <> 0 'wait for the "File Download" popup window to appear
thewindow = FindWindow(vbNullString, "File Download")
Loop
SendKeys "{LEFT}"
Application.Wait Now + TimeValue("00:00:01")
SendKeys "{LEFT}"
Application.Wait Now + TimeValue("00:00:01")
SendKeys "{ENTER}"
End Sub
You're not going to be able to suppress that message in your code, it's a setting on the user's workstation to prevent harm from malicious files.
The user would have to either edit their Windows registry or have it controlled via a group policy setting. http://support.microsoft.com/kb/948615
I ran across this same issue with Excel documents generated on on the server. The only workaround I made was to create files using the Open XML SDK.
EDIT: I read your question again and noticed it's more focused on the first pop-up, and JMax linked answer (How to disable file download popup in Internet Explorer?) should fix that.
Jon, my two cents on this.
If you have administrative access to your pc then what JMax suggested will sort it out. I would discourage editing the registry if you are an administrator until and unless you know what you are doing.
If it is say an office pc then editing the registry is not even an option. You will have to contact the IT dept. They can either login to your pc as an administrator and then turn the option off for you or they can tweak the GP as zeroef suggested. My best guess is that if it is an office pc then they will login as an administrator and make the changes for you individually instead of making the change in the GP (unless you are the only member of that group). In a corporate environment it is really difficult to get that pulled off via GP as it affects lot of users. There is also a possibility that your request might not be agreed upon if it is an Office pc.
BTW, from what I see, your question has nothing to do with it being an Excel problem :)
HTH
Sid
You could just download the file directly...
Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
"URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal _
szFileName As String, ByVal dwReserved As Long, _
ByVal lpfnCB As Long) As Long
Sub DownloadFile(sURL, sSaveAs)
Dim rv As Long
rv = URLDownloadToFile(0, sURL, sSaveAs, 0, 0)
If rv <> 0 Then
MsgBox "Error with download!"
End If
End Sub
Don't know if the https will be an issue here.
Another thing to try is just:
Workbooks.Open "https://companysite.com/directorypage/Reports/MyReport.aspx?Format=Excel"

Resources