vbscript : fso.opentextfile permission denied - vbscript

In my code segment, when I script the file name, it gives me a permission denied
on the following line:
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
Here is the script
'output log info
Function OutputToLog (strToAdd)
Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
strDirectory = "c:\eNet"
strFile = "\weeklydel.bat"
'strText = "Book Another Holiday"
strText = strToAdd
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check that the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
'WScript.Echo "Just created " & strDirectory
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
'Wscript.Echo "Just created " & strDirectory & strFile
End If
set objFile = nothing
set objFolder = nothing
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 2
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
' Writes strText every time you run this VBScript
objTextFile.WriteLine(strText)
objTextFile.Close
End Function
I have assigned the vbscript domain administrator permissions. Any ideas?
thanks in advance

I don't think this has to do with File Permissions per se. It has to do with the fact that you've created the file using:
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
That creates the file...and carries a reference to that file (objFile)
Then you don't close the file before you destroy the reference
...
'Missing objFile.Close here
Set objFile = nothing
Set objFolder = nothing
...
Consequently you're destroying the reference but leaving the textstream open in memory thus locking your file.
You are then proceeding to attempt to re-open the file while the file is already "open". This is a little long winded, you've already got a reference after you've created the file - it would be easier just to write straight to that rather than destroy the reference before creating another one.

for what its worth...
I was convinced I had a permission error because of this line:
Set LogFile = LogFSO.OpenTextFile(LogFileName, ForWriting, True)
Because that's the line that the 'permission denied' error pointed to. But in fact, my permission error was a few lines further down:
WshShell.AppActivate(ScreensToRemove(i))
WshShell.SendKeys ("~")
WScript.Sleep(1000)
There was no screen with such a caption, so the SendKeys is what did not have permission.
The solution, of course, was:
If WshShell.AppActivate(ScreensToRemove(i)) = True Then
WshShell.SendKeys ("~")
WScript.Sleep(1000)
End if
Hope that might help.

Also, make sure that you don't have the file open in Excel (I had this problem with a .csv file)...

In my particular case the file which existed before and all I had to do was give permission to the Everyone user

balabaster is exactly right. You either need to close the file before reopening it a second time for writing, or using the existing open handle.

Related

How do I add to a to VBS file command

I have the following VBScript to which I'm trying to add to, but I need help in how to do it.
At present I have the script below that asks for the file name I want it to be called and then creates a folder and moves of which ok.
What I'm trying to add is after the folder is created I need a command box with the YES/NO option and if I click YES I need the file moved to C:\DOCUMENTS\A and if NO I need it moved to C:\DOCUMENTS\B.
Once I've clicked YES or NO and it has moved the folder I need to open Folder A or B to view.
Any Ideas?
Option Explicit
Const strDLFolder = "C:\Downloads"
Dim objFSO, objWShell, objDLFolder, strNewFolder, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWShell = CreateObject("WScript.Shell")
If Not objFSO.FolderExists(strDLFolder) Then objFSO.CreateFolder(strDLFolder)
objWShell.CurrentDirectory = strDLFolder
Set objDLFolder = objFSO.GetFolder(strDLFolder)
If objDLFolder.Files.Count = 0 Then WScript.Quit
Do
Err.Clear
strNewFolder = InputBox("Folder Name", vbLf & "Enter the name of the folder to be created:")
If strNewFolder = False Then WScript.Quit
On Error Resume Next
objFSO.CreateFolder strNewFolder
Loop While Err.Number <> 0 Or Not objFSO.FolderExists(strNewFolder)
On Error Goto 0
For Each objFile In objDLFolder.Files
objFSO.MoveFile objFile.Name, strNewFolder & "\"
Next
objWShell.Popup "All files moved.", 0, "Done", vbInformation Or vbSystemModal Or &h00040000&

VBScript Using Computername to Name a File

New to VBScript and having a problem grasping this concept.
This is the code:
Set WshNetwork = WScript.CreateObject("WScript.Network")
strCompName = WshNetwork.Computername
Wscript.Echo WshNetwork.Username >j:\strCompName.txt
WScript.Quit()
Basically I want to the username dumped to a text file and the text file should be named with the name of the computer. I've tried putting the strCompName in quotes, single quotes, parenthesis with no success.
Here is the code that you can use. You need to use FileSystemObject. The FileSystemObject is used to gain access to a computer's file system. It can create new files and access existing ones.
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strCompName = WshNetwork.Computername
'writing to file
outFile="c:\TEMP\" & strCompName & ".txt"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write WshNetwork.Username & vbCrLf
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Set WshNetwork = Nothing
WScript.Quit()
Save this in .vbs file and run and you will get a text file with computer name in TEMP folder (Change the path if you like).
This code should work. This code opens the file and appends it if the file exists or creates a file and writed to it if it does not exist.
'constants
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
'Load domain, username, & computer variables
Set oShell = CreateObject( "WScript.Shell" )
sDomain = oShell.ExpandEnvironmentStrings( "%USERDOMAIN%" )
sUserName = oShell.ExpandEnvironmentStrings( "%USERNAME%" )
sComputer = oShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
'Setup filesystemobject
Set oFSO=CreateObject("Scripting.FileSystemObject")
'Check to see if file exists. If exists open it forAppending
'else create file and write to it.
outFile="c:\export\" & sComputer & ".txt"
If oFSO.FileExists(outFile) Then
Set objFile = oFSO.OpenTextFile(outFile, ForAppending, True, TristateTrue)
Else
Set objFile = oFSO.CreateTextFile(outFile,True)
End If
'write to file
objFile.WriteLine sDomain & "\" & sUsername & " - " & Now
'clean up objects
objFile.Close
Set objFile = Nothing
Set oFSO = Nothing
Set oShell = Nothing

How to Copy a file that was read from a list

Hello guys I have an issue or issues with my code above
I'm trying to get "sExtension" to be search in a different folder other that the one I'm using to save my script since this script will be use as a Startup Script on many computers
(It works only if I run the script in the same folder "sExtension", "ExtAssign.txt" and sComputername are otherwise it wont find the path)
This is what it should do
Read a file called "ExtAssign.txt" (There is a full list of computer names in that file) and if it find the computer name on that file then it should copy a file with the with the extension number assigned to that computer name from a file server to "C:\" Drive
For this example I'm trying to do this locally, If I can make it then I'll try it from my File Server
Set objFSO = CreateObject("Scripting.FileSystemObject")
set oFso = CreateObject("Scripting.FileSystemObject")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
set oShell = WScript.CreateObject("WScript.Shell")
set oShellEnv = oShell.Environment("Process")
Set folder = Fso.GetFolder("C:\Users\XXXXX\Desktop\Test\Extensions\")
Set wshshell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set ObjEnv = WshShell.Environment("Process")
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Scomputername = ObjEnv("COMPUTERNAME")
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objWShell = wScript.createObject("WScript.Shell")
Dim strFile
'File to scan
strFile = "C:\Users\XXXXX\Desktop\Test\Extensions\Extassign\ExtAssign.txt"
Dim strPattern
'Look for computer name in file
strPattern = scomputername
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
Dim strLine
'Read each line and store it in strLine
strLine = objFile.ReadLine
'If the line matches the computer name, save the line to ExtArray
If InStr(strLine,strPattern)>0 Then
Dim ExtArray
'Split the line and separate the extension
ExtArray = Split(strLine,"|", -1, 1)
Dim sExtension
'Save the extension to sExtension
sExtension=ExtArray(1)
End If
Loop
'If the sExtension is empty, computer was not found, send message and terminate script.
If sExtension="" Then
WScript.Echo "ERROR: Computer "& scomputername &" not found in Extension Assignment List, so no extension has been set. Avaya will not be launched. Please contact your IT department for assistance."
Else
'If the sExtension contains a number, Copy that file to C:\ and rename it to Config.xml
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
End If
at the end it if it finds the file sExtension it will rename it to Config.xml but it wont do it unless I run the script in the same folder sExtension and sComputername.
I get File not found error
Thank you in advance and Happy new year!
The culprit is most likely this line:
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
There is a trailing space after the last backslash in the path, so you're creating a path
C:\Users\XXXXX\Desktop\Test\Extensions\ 12345
^
when you actually want a path
C:\Users\XXXXX\Desktop\Test\Extensions\12345
On a more general note: why are you creating 7(!) FileSystemObject instances (replacing one of them three times on top of that)? And 3(!) WScript.Shell instances? You don't even use most of them, not to mention that you don't need the Shell object in the first place. You only use it for determining the computer name, which could be done just fine using the WScript.Network object (that you don't use at all).
Also, please don't ever use comments like this:
'Read each line and store it in strLine
strLine = objFile.ReadLine
It's quite obvious that you read each line and assign it to the variable strLine. Comments shouldn't rephrase what you're doing (the code already does that, at least when you're using speaking variable and function names), but why you're doing it, i.e. what the purpose of a particular code section is.
Your code could be reduced to something as simple as this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set net = CreateObject("WScript.Network")
computername = net.ComputerName
foldername = "C:\Users\XXXXX\Desktop\Test\Extensions"
filename = fso.BuildPath(foldername, "Extassign\ExtAssign.txt")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If InStr(line, computername) > 0 Then
arr = Split(line, "|", -1, 1)
If UBound(arr) >= 1 Then extension = arr(1)
End If
Loop
f.Close
If IsEmpty(extension) Then
WScript.Echo "ERROR: Computer "& computername &" not found in ..."
Else
fso.CopyFile fso.BuildPath(foldername, extension), "C:\Config.xml", True
End If

vbscript to delete files & folders of remote computer

First thing I am not an expert in writing VBScripts.
I have a requirement of deleting files & folders of remote systems with just 1 click. I was trying to build below VBScript but somehow it’s not working. I request any of your help to correct the same or with a new script that help me to fulfill the requirement. Any help in this regard is greatly appreciated, Thanks in Advance.
With the below:
C:\Test - is the directory from where I would like to delete the files & subfolders
C:\computerList.txt – is the text file contains all remote systems IP Address.
Const strPath = "C:\Test"
Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1)
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Call Search (strPath)
WScript.Echo"Done."
Sub Search(str)
Do While Not computerList.AtEndOfStream
strComputer = computerList.ReadLine
Dim objFolder, objSubFolder, objFile
Set objFolder = objFSO.GetFolder("\\" & strComputer & "\" & str)
For Each objFile In objFolder.Files
If objFile.DateLastModified < (Now() - 0) Then
objFile.Delete(True)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Search(objSubFolder.Path)
' Files have been deleted, now see if
' the folder is empty.
If (objSubFolder.Files.Count = 0) Then
objSubFolder.Delete True
End If
Next
loop
End Sub
Regards,
Balaram Reddy
Your first problem is that you have the line order incorrect:
Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1)
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Should be
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set computerList = objfso.OpenTextFile ("C:\computerList.txt", 1)
You are using objfso before declaring it
When using a UNC path, you will need to use the folder's remote share name. If you have admin privileges on the remote pc use:
Const strPath = "c$\Test"

Delete shortcut from remote computers with multiple users

Warning I have zero VB knoeledge
So I found this handy script this morning:
InputFile = "C:\MachineList.Txt"
Const DeleteReadOnly = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(InputFile)
Do While Not (objFile.AtEndOfStream)
strComputer = objFile.ReadLine
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile("\\" & strComputer & "\c$\Documents and Settings\all users\Desktop\Malwarebytes Anti-Malware.LNK")
Err.Clear
Loop
MsgBox "Done"
It did the job great. The problem I am facing is the shortcut is not always under all users or their name lets call it user1
So I would love for it to go through MachineList.txt and browse through all of the profiles searching for Malwarebytes Anti-Malware.LNK. I have seen a few scripts on this but I just cannot wrap my head around VB is a short amount of time. I appreciate any input.
I assume that what you provided results in valid paths... therefore this should work:
InputFile = "C:\MachineList.Txt"
Const DeleteReadOnly = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(InputFile)
Do While Not (objFile.AtEndOfStream)
strComputer = objFile.ReadLine
For Each objsubfolder In objFSO.GetFolder("\\" & strComputer & "\c$\Documents and Settings\").subfolders
If objFSO.FileExists(objsubfolder.Path & "\desktop\Malwarebytes Anti-Malware.LNK") Then
objFSO.DeleteFile (objsubfolder.Path & "\desktop\Malwarebytes Anti-Malware.LNK")
End If
'To check another file uncomment this
'Add as many of these as you like here
'If objFSO.FileExists(objsubfolder.Path & "\desktop\Otherfile.LNK") Then
' objFSO.DeleteFile (objsubfolder.Path & "\desktop\Otherfile.LNK")
'End If
Next
Loop
MsgBox "Done"

Resources