Checking file accessibility
Hi there,
I have a script:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject ("WSCript.shell")
'Sets variables
if not objFSO.FileExists("%windir%") & "\system32\drivers\etc\Hosts" then
msgbox ("file not found")
end if
FilePath= oShell.ExpandEnvironmentStrings("%windir%") & "\system32\drivers\etc\Hosts"
SearchTerm="# 127.0.0.1 localhost"
NewText=" 127.0.0.1 localhost"
'Opens text file in read mode (Read=1, Write=2, Append=8)
Set objFile = objFSO.OpenTextFile(FilePath, 1)
'Adds all text in text file to "FileContent" string
FileContent = objFile.ReadAll
objFile.Close
'Instr searches "FileContent" looking for "SearchTerm", if not found returns 0
if Instr(FileContent,SearchTerm) = 0 then
'Not found code
'Opens text file in append mode so you can add text (Read=1, Write=2, Append=8)
Set objFile = objFSO.OpenTextFile(FilePath, 8)
'Writes new line to text fle vbCrLf inserts a returnto ensure new line
objFile.WriteLine (vbCrLf & NewText & vbCrLf)
objFile.Close
Else
'Found search term
ReplaceOldLine = Replace(FileContent, "# 127.0.0.1 localhost", NewText)
'Opens text file in write mode to replace old line (Read=1, Write=2, Append=8)
Set objFile = objFSO.OpenTextFile(FilePath, 2)
're-writes whole content of file with replaced values (if needed)
objFile.WriteLine ReplaceOldLine
objFile.Close
end If
WScript.Quit
works just fine but what I need is include in it error checking, for example when MSI installs it gives an error if file does not exist or is locked or other reasons, can some knowledge scripter could help in this because I have no idea how to do that.
Answers (3)
The hosts file is there by default, unless an admin deletes it.
beware of any additions / changes to the Hosts File can / will be removed using a System Restore point dated before the work was done with the file.
If the file is locked you may have to take ownership first before modding the file
Comments:
-
if you do not care about replacing the remark'd text you can push a bat via the k1000 and just add a line at the end with
echo 127.0.0.1 localhost >> c:\windows\system32\drivers\etc\hosts - SMal.tmcc 12 years ago