I am unable to delete a file on the Desktop (All Users) but I could delete without the script - windows

It crashes on wshShell.Run.
You can see that I run a WScript.Echo and it does print the location of the file name. When I run it, it says the "The system could not find the file specified"
I tried objFile.delete but it says Permission denied. If i perform "del " in the command prompt, it works.
For Each objFile In colFiles
bMatch = objRE.Test(objFile.Name)
If bMatch Then
WScript.Echo objFile.Name
WScript.Echo objFile.Path
Set wshShell = WScript.CreateObject ("WSCript.shell")
wshShell.Run "del " & objFile.Path, 1, True
Set wshShell = Nothing
End If
Next
Output
Lotus Notes 8.5.lnk
C:\Users\Public\Desktop\Lotus Notes 8.5.lnk
(null) (79, 3) : (null)
------------------ UPDATE ------------------
The following works perfectly if it's on the Users Desktop (not the AllUsersDesktop). I'm trying to delete it from the AllUsersDesktop
For Each objFile In colFiles
bMatch = objRE.Test(objFile.Name)
If bMatch Then
objFile.Delete
End If
Next
After applying the following code, I get this error
Lotus Notes 8.5.lnk
C:\Users\Public\Desktop\Lotus Notes 8.5.lnk
(null) (81, 3) : (null)
Code: (updated as of 5/23)
Set objShell = CreateObject("WScript.Shell")
strCurrentDirectory = objShell.SpecialFolders("AllUsersDesktop")
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(strCurrentDirectory)
Set objFolderItem = objFolder.Self
Set objFolder = objFS.GetFolder(strCurrentDirectory)
Set colFiles = objFolder.Files
Set objRE = New RegExp
objRE.Global = True
objRE.IgnoreCase = True
objRE.Pattern = "notes"
For Each objFile In colFiles
bMatch = objRE.Test(objFile.Name)
If bMatch Then
WScript.Echo objFile.Name
WScript.Echo objFile.Path
Set wshShell = WScript.CreateObject ("WSCript.shell")
wshShell.Run "del """ & objFile.Path & """", 1, True
Set wshShell = Nothing
End If
Next

This should do it:
wshShell.Run "del """ & objFile.Path & """", 1, True

The path has a space in it, so it should be enclosed in double quotes, something like "del \"" & objFile.Path & "\"", or whatever VB syntax for escaping is.

Related

Replace a specific string with the filename?

How to replace a specific string with the filename? Example: I have several files with different names (like: Test.asp, Constant.asp, Letter.asp, etc.) within a subfolder that contain the text "ABC123". I would like to replace the "ABC123" in each file with the filename.
Below is the code I have that finds string and replaces it with a specific string but it doesn't do the job that I listed above.
Option Explicit
Dim objFilesystem, objFolder, objFiles, objFile, tFile, objShell, objLogFile,objFSO, objStartFolder, colFiles
Dim SubFolder, FileText, bolWriteLog, strLogName, strLogPath, strCount, strCount2, strOldText, strNewText, strEXT
bolWriteLog = True
Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2
Set objFilesystem = WScript.CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
strLogName = "log.txt"
strLogPath = "C:\" & strLogName
strCount = 0
strCount2 = 0
strOldText = "ABC123"
strNewText = ""
strEXT = "asp"
'Initialize log file
If bolWriteLog Then
On Error Resume Next
Set objLogFile = objFileSystem.OpenTextFile(strLogPath, 2, True)
WriteLog "############### Start Log ##################"
If Not Err.Number = 0 Then
MsgBox "There was a problem opening the log file for writing." & Chr(10) & _
"Please check whether """ & strLogPath & """ is a valid file and can be openend for writing." & _
Chr(10) & Chr(10) & "If you're not sure what to do, please contact your support person.", vbCritical, "Script Error"
WScript.Quit
End If
On Error Goto 0
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "D:\MyFolder"
Set objFolder = objFSO.GetFolder(objStartFolder)
WScript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each objFile In colFiles
'WScript.Echo objFile.Name
' Now we have an exception for all files that can not be opened in text modus: all extensions such as "exe" should be listed upfront.
ReplaceText(objFile)
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ReplaceText(objFile)
If InStr(1, strEXT, Right(LCase(objFile.Name), 3)) = 0 Or objFile.Size = 0 Then
Else
strCount = strCount + 1
WriteLog("Opening " & objFile.Name)
Set tFile = objFile.OpenAsTextStream(ForReading, TriStateUseDefault)
FileText = tFile.ReadAll
tFile.Close
If InStr(FileText, strOldText) Then
WriteLog("Replacing " & strOldText & " with " & strNewText & ".")
FileText = Replace(FileText, strOldText, strNewText)
WriteLog("Text replaced")
Else
WriteLog(strOldText & " was not found in the file.")
strCount2 = strCount2 + 1
End If
Set tFile = objFile.OpenAsTextStream(ForWriting, TriStateUseDefault)
tFile.Write FileText
tFile.Close
FileText = ""
strCount = 0
strCount2 = 0
End If
End Sub
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
'WScript.Echo Subfolder.Path
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
'WScript.Echo objFile.Name
ReplaceText(objFile)
Next
ShowSubFolders Subfolder
Next
End Sub
WriteLog "############### EndLog ##################"
WScript.Echo "Script Complete"
objShell.Run "C:\" & strLogName
'Clear environment and exit
On Error Resume Next
Set tFile = Nothing
Set objFile = Nothing
Set objFiles = Nothing
Set objFolder = Nothing
Set objLogFile = Nothing
Set objFilesystem = Nothing
Set objShell = Nothing
WScript.Quit
'Subs and functions ********** DO NOT EDIT ***************
Sub WriteLog(sEntry)
If bolWriteLog Then objLogFile.WriteLine(Now() & ": Log: " & sEntry)
End Sub
I can give you a one line Ruby solution, should be not too difficult to translate that in Python but somewhat more extensive in VbScript I am afraid. First a generic search and replace version.
ARGV[0..-3].each{|f| File.write(f, File.read(f).gsub(ARGV[-2],ARGV[-1]))}
Save it in a script, eg replace.rb
You start in on the command line (here cmd.exe) with
replace.rb *.txt <string_to_replace> <replacement>
broken down so that I can explain what's happening but still executable
# ARGV is an array of the arguments passed to the script.
ARGV[0..-3].each do |f| # enumerate the arguments of this script from the first to the last (-1) minus 2
File.write(f, # open the argument (= filename) for writing
File.read(f) # open the argument (= filename) for reading
.gsub(ARGV[-2],ARGV[-1])) # and replace all occurances of the beforelast with the last argument (string)
end
And finally your request to replace ABC123 with the filename.
Of course tested and working
ARGV[0..-1].each{|f| File.write(f, File.read(f).gsub('ABC123', f))}
Contents of one of my testfiles (1.txt) after executing
test phrase
1.txt
EDIT
I see you want subfolder recursion on a fixed folder, no problem
Dir['**/*'].each{|f| File.write(f, File.read(f).gsub('ABC123', f)) unless File.directory?(f) }

The process cannot access the file because it is being used by another process. Code: 80070020, VBScript

When I run my vbscript, it says(In Windows Script Host):
C:\Users\admin\Desktop\Test.vbs
Line: 34
Char:1
Error: The process cannot access the file because it is being used by another process.
Code: 80070020
Source: (null)
How would I be able to fix this? Also here's the script...
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFSO, objFolder, objShell, objFile
Dim strDirectory, strFile
strDirectory = "c:\Folder"
strFile = "\Hidden.bat"
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
End If
set objFolder = nothing
set objFile = nothing
Const fsoForAppend = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTextStream
Set objTextStream = objFSO.OpenTextFile("C:\Folder\Hidden.bat", fsoForAppend)
objTextStream.WriteLine "attrib ""Folder"" +s +h"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run """C:\Folder\Hidden.bat"""
Set objShell = Nothing
Without creating any batch file to hide your folder :
Option Explicit
Dim objFSO,objFolder,strDirectory,Command,Result,objShell
Set objFSO = CreateObject("Scripting.FileSystemObject")
strDirectory = "C:\Folder"
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
End If
set objFolder = nothing
Command = "Cmd /c Attrib +s +h "& DblQuote(strDirectory) &""
Set objShell = CreateObject("WScript.Shell")
Result = objShell.Run(Command,0,True)
Set objShell = Nothing
'****************************************************************
Function DblQuote(str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************************
Closes an open TextStream file.
object.Close
From Help.
You need to close it after writing to it before using it.

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

Vbscript loops when it shouldn't

I have this vbs script:
Set WshShell = WScript.CreateObject("WScript.Shell")
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" &_
" RunAsAdministrator", , "runas", 1
Const Destination = "c:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"
Const Virus = "virus.bat"
Const YesNo = "yesnovbs.vbs"
Const CDRom = "cd-rom.vbs"
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile Virus, Destination, True
fso.CopyFile YesNo, Destination, True
fso.CopyFile CDRom, Destination, True
Basically, it copies some files from my USB to startup directory in any pc. The problem is, that the script keeps executing itself. I wanted this script to copy files and exit, how do I do that?
You need to do the restart just once, depending on a condition (e.g. a parameter). Demo:
If 0 = WScript.Arguments.Count Then
WScript.Echo "first run, starting script again"
CreateObject("WScript.Shell").Exec "wscript.exe " & WScript.ScriptName & " param"
Else
MsgBox "second run"
End If
output:
Function runas()
Set WshShell = WScript.CreateObject("WScript.Shell")
Set ObjShell = CreateObject("Shell.Application")
If WScript.Arguments.Length = 0 Then
ObjShell.ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" &_
" RunAsAdministrator", , "runas", 1
WScript.Quit
End If
End Function
Call runas()
Const Destination = "c:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"
Const Virus = "virus.bat"
Const YesNo = "yesnovbs.vbs"
Const CDRom = "cd-rom.vbs"
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile Virus, Destination, True
fso.CopyFile YesNo, Destination, True
fso.CopyFile CDRom, Destination, True
Set WshShell = Nothing
Set objShell = Nothing
Set fso = Nothing
If you did not add the wscript.Arguments.length = 0 condition statement it will keep continue work

I am trying to find specific links on users desktops and create a file logging the results

I have used similar before and I have local admin rights on every computer in our network. The following code generates an error on line 16 char 1.
line 16 For Each objsubfolder In objFSO.GetFolder("\" & strComputer & "%HOMEPATH%").subfolders
If the file exists it should write a line in the text file to indicate so for each user with a profile. If the file doesn't exist is should write a line in the same text file.
The error I get is Path not found 800A004C.
The computers.txt file contains a list of all the computers I want to check.
InputFile = "computers.txt"
Const DeleteReadOnly = True
Const ForAppending = 8
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim gsLog : gsLog = ".\logdemo.log"
WScript.Echo gsLog, "exists:", CStr(goFS.FileExists(gsLog))
' .OpenTextFile(filename[, iomode[, create[, format]]])
Dim goLog : Set goLog = goFS.OpenTextFile(gsLog, ForAppending, True)
goLog.WriteLine Now & " start"
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 & "%HOMEPATH%").subfolders
If objFSO.FileExists(objsubfolder.Path & "\desktop\program1.LNK") Then
golog.WriteLine Join(Array(Now, strComputer, objsubfolder, "This Computer has Program 1"))
Else
golog.WriteLine Join(Array(Now, strComputer, objsubfolder, "None"))
End If
Next
Loop
golog.WriteLine Now & " End"
golog.WriteLine "-----------------------------------------------------------"
golog.Close
MsgBox "Done"
To prove that the FSO does not expand environment strings automagically:
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim oWS : Set oWS = CreateObject("WScript.Shell")
Dim sPath
sPath = "%windir%\addins"
WScript.Echo qq(sPath), CStr(oFS.FolderExists(sPath))
sPath = oWS.ExpandEnvironmentStrings("%windir%\addins")
WScript.Echo qq(sPath), CStr(oFS.FolderExists(sPath))
output:
"%windir%\addins" False
"C:\WINDOWS\addins" True
So put some work into feeding a valid path to .GetFolder().

Resources