VBS remove printe -- on error resume next - vbscript

When I run the script below I get an error that the first printer does not exist. This is true, the first printer is not connected, so the output gives me this:
"c:\temp\rmprintlong.vbs(4, 1) WSHNetwork.RemoveNetworkDrive: This network connection does not exist." and then the script dies...this is the issue: the script dies!!!
I still need it to remove the second printer in this script! If it doesn't find one of the printers in the script, I still need it to resume with the next remove printer command!
Here is the code I am using:
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\p1\(SW)_HP_LaserJet_8150_Series_PCL"
WshNetwork.RemovePrinterConnection PrinterPath, true, true
PrinterPath = "\\p1\(NE)_HP_LaserJet_5M"
WshNetwork.RemovePrinterConnection PrinterPath, true, true
Wscript.Quit(1)
Do I simply add "On Error Resume Next" under the first line of the code..?

That depends on the quality requirements of your script. If it doesn't matter whether it succeeds or fails, put the OERN in the first line (and meet the standards of the Scripting Guys).
A compromise/minimal impact/pythonic variation of your script:
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\p1\(SW)_HP_LaserJet_8150_Series_PCL"
On Error Resume Next ' don't care if this fails
WshNetwork.RemovePrinterConnection PrinterPath, true, true
On Error GoTo 0 ' open eyes again
PrinterPath = "\\p1\(NE)_HP_LaserJet_5M"
WshNetwork.RemovePrinterConnection PrinterPath, true, true
Wscript.Quit 1 ' no parameter list () when calling a sub
This would restrict the "I don't care" section to one single operation.

Related

VBScript Error 52 Bad file name or number

I have a VBScript which is used in Avaya CMS to generate a CSV every 3 seconds. This CSV is then read on each change by a node server.
Every now and then it will throw an error (Error 52) and it then requires someone to manually click OK on the prompt and then it continues.
I didn't write the initial script, but I have been trying to fix it so it doesn't throw this error.
As far as I understand, the issue is being caused when the script tries to write to the file when the node server is trying to read the file.
So far I have tried to fix this by making the file read only, then, in the script it makes it writeable, writes to it and makes it read only again.
I thought this had fixed the issue, but I have received Error 52 pop up again and now I am unsure.
Does anyone know if there is a way to get VB/Avaya to ignore the error? I was thinking something like putting On Error Resume Next before the line that writes the file?
I know ignoring errors is not good practice, but in this case, if it does ignore it, it just means the file wont be updated on this loop, but 3 seconds later it will loop again so it should be fine.
Script:
On Error Resume Next
cvsSrv.Reports.ACD = 1
Set Info = cvsSrv.Reports.Reports("Real-Time\Designer\Skill Status")
If Info Is Nothing Then
Else
b = cvsSrv.Reports.CreateReport(Info,Rep)
If b Then
Rep.RefreshInterval = 3
Rep.SetProperty "Split/Skill","5"
Set WshShell = CreateObject("WScript.Shell")
theHTMLLocation = "C:\wamp\www\wallboards\agent_status.csv"
theSleepFile = "C:\wamp\www\wallboards\sleep.vbs"
theTemplateLocation = ""
Set fso = CreateObject("Scripting.FileSystemObject")
Set gfile = fso.GetFile("C:\wamp\www\wallboards\agent_status.csv")
Do While Rep.Window.Caption <> ""
gfile.Attributes = 0
d = Rep.ExportData("C:\wamp\www\wallboards\agent_status.csv", 44, 0, False, True, True)
gfile.Attributes = 1
WshShell.Run "wscript.exe """ & theSleepFile & """", , True
Loop
If Not cvsSrv.Interactive Then cvsSrv.ActiveTasks.Remove Rep.TaskID
Set Rep = Nothing
End If
End If
Set Info = Nothing
P.S - I left out some Parameters at that start of the file which I don't think are relevant, if someone thinks they are I will add them.

How to disable SmartScreen for a specific .cmd file?

I recent made a group of .cmd files.
Called, 'Node.1.cmd' and 'Node.2.cmd', the files' purpose was supposed to open each other (in a chain-like process).
However, whenever I open one of the 2, it gives me a seriously annoying message:
Windows Protected your PC.
Windows SmartScreen prevented an unrecognized app from starting. Running this app may put your PC at risk.
I agree that this is a bit risky, but it was made for fun, not for destruction. It was just my way of showing people not to mess with my stuff. Not even did I set any LNK at my desktop to the file.
Now, to get to the point, can I exclude this file from SmartScreen while keeping it on?
Because of this, I have problems opening it with a .vbs file
To be more specific, it opens but then automatically closes with a message:
The system cannot find the path specified.
Does windows SmartScreen encrypt the file or something like that?
I scripted the following:
Titre = "What would you like to do ? RookieTEC9©"
message = "What would you like to do ?"&vbcr&vbcr&_
"1 - Launch Project Node "&vbcr&_
"2 - Launch Golden Chrome"&vbcr&_
"3 - Launch An Application"&vbcr&_
"4 - Start Windows Update"&vbcr&_
"5 - Slide2Kill"
Default ="1"
Question = InputBox(message,Titre,Default)
Select Case Question
Case 1 Run(1)
Case 2 Run(2)
Case 3 Run(3)
Case 4 Run(4)
Case 5 Run(5)
end Select
Sub Run(var)
Set WS = CreateObject("WScript.shell")
Select Case var
Case 1 WS.run("explorer.exe /e,C:\Users\Jeremi\OneDrive\Happy_files\Unsorted_Files\Project_Node.zip\Node.1.cmd")
Case 2 ProcessNotNeeded()
Case 3 LaunchApplication()
Case 4 WindowsUpdate()
Case 5 WS.run("SlideToShutDown.exe")
End select
End Sub
Sub Kill(Process)
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
Sub ProcessNotNeeded()
Titre = "Killing Process Not Needed RookieTEC9© "
message = "Type the Name of the process to be killed by this script"&vbcr&_
"Example To Kill The Internet Explorer Process You should type"&vbcr&_
"iexplore.exe"
Default ="iexplore.exe"
Question = InputBox(message,Titre,Default)
Kill(Question)
End Sub
Function CmdPrompt(sCmd)
Dim sCmdLine,oWS,nRes
set oWS = CreateObject("Wscript.Shell")
sCmdLine = "cmd /c Start " & sCmd & ""
nRes = oWS.Run(sCmdLine,0,False)
CmdPrompt = nRes
End Function
Sub LaunchApplication()
Titre = "Launching an Application"
message = "Type the Name of the process to be Lanuched by this script"&vbcr&_
"Example To Launch The Word Application You should type"&vbcr&_
"Winword.exe"
Default ="Winword.exe"
Question = InputBox(message,Titre,Default)
CmdPrompt(Question)
End Sub
Sub WindowsUpdate()
Title = "Checking for Windows updates"
Msg = "Looking for a list of updates, So be Patient Thank you !"
Wait = "70" 'waiting 70 secondes to close the popup
Set Ws = CreateObject("Wscript.Shell")
ws.Popup Msg,wait,Title,64
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
If searchResult.Updates.Count <> 0 Then 'If updates were found
'so with this loop shows how you can list the title of each update that was found.
For i = 0 To searchResult.Updates.Count - 1
Set update = searchResult.Updates.Item(i)
ws.Popup update.Title,wait,Title,64
Next
End If
Ws.Run "wuauclt.exe /reportnow /detectnow",1,False
End Sub
Sorry for the long code!
To be 100% honest, I didn't create this from scratch, I just edited it.
I am new to VBS
However, if you have any questions on HTML or CSS, I may be able to answer it.
Please keep in mind that I am a 5th grader and only started coding this school year.
THX for your time and answer.
P.S.
Also, the file was in a zip. Does that effect it?
You can unblock these CMD files, it is explained here
Once unblocked you should be able to run it from the console and from your script.
I myself scripted a very long time in vbscript but now it is obsolete. Since you have
just started to learn, I advise you to learn another scripting language like Ruby which is fun to learn or if you want to go the 'only windows' way Powershell (shiver..)

VBS If file is open

I've got a simple program than scans data into a spreadsheet along with a timestamp, then you can either update the data by saving, or quit and exit and save.
The only issue I've been stuck on for a day or so is to work around the error handling of the case of the spreadsheet being already open. Id like to have something like this;
if file is open THEn msgbox("File is open, close file and start again")
WScript.Quit
Option Explicit
DIM oFs: Set oFs = CreateObject("Scripting.FileSystemObject")
DIM objExcel, strExcelPath, objSheet
DIM ib
DIM msg1
DIM msg2
strExcelPath = "c:\temp\Example.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.WorkBooks.Open strExcelPath
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
DO
ib=inputbox("SCAN NAME, SCAN LOTS"&vbCrLf&"TO UPDATE,SCAN ""UPDATE."""&vbCrLf&"TO EXIT, SCAN ""QUIT.""","Picklot Passout Database")
IF ib="" THEN
msg1=MsgBox("You must scan either a NAME or LOT NUMBER."&vbCrLf&"If you want to exit, scan QUIT."&vbCrLf&"Click OK to continue.",vbokonly,"Cannot Insert Blank Data")
ELSEIF ib= "QUIT" OR ib= "quit" THEN
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
set objExcel = Nothing
Set oFs = Nothing
ELSEIF ib="update" OR ib="UPDATE" THEN
objExcel.ActiveWorkbook.Save
msg2=MsgBox("Update Complete.",vbokonly,"Database Updated")
ELSE
objSheet.Range("A2").EntireRow.Insert
objSheet.Cells(2, 1).Value = ib
objSheet.Cells(2, 2).Value=(now)
END IF
LOOP WHILE NOT ib="quit" AND NOT ib="QUIT"
This may help point you in the right direction. Sorry for the rushed, lowercase syntax and unconventional indentations (do not follow my bad practice - keep yours! :D), I wrote it in notepad you see - but it has been tested successfully.
Anyhow, with reference to your code, I have restructured it in a bad manner, familiar to me, adding the functionality you specify. Essentially the task manager application list is checked for a running instance of the "example" Excel file (depending on what version of excel you're using the syntax will differ).
If found it will make it the active window (thereby preventing a read only duplicate instance initiating). If no instance is found it will open "example.xlsx", in this case using a relative path to the script itself. A subroutine is then called to do the business with the cells...
I have written it in such a way to try keep your specs as well as maintain the "OK" and "Cancel" buttons explicitly functional. Please feel free to tinker with this, you may need to address the path and instr lines differently. I hope it helps! All the best.
path=createobject("scripting.filesystemobject").getparentfoldername(wscript.scriptfullname)
excelpath=path&"\example.xlsx"
set objword=createobject("word.application")
set coltasks=objword.tasks
i=0
for each objtask in coltasks
name=lcase(objtask.name)
if instr(name, "microsoft excel - example") then
i=1
end if
next
if i=1 then
wscript.echo "An active instance of ""example.xlsx"" has been found"
set objexcel=getobject(excelpath)
call UPDATER
else
set objexcel=createobject("excel.application")
objexcel.workbooks.open(excelpath)
set objsheet=objexcel.activeworkbook.worksheets(1)
objexcel.visible=true
call UPDATER
end if
sub UPDATER
do
data=inputbox("Please enter data" &vbcrlf&vbcrlf& "To save data & continue, type ""update""" &vbcrlf& "To save data & exit, type ""quit""","Excel DB Updater")
if isempty(data) then
objexcel.activeworkbook.close
objexcel.application.quit
wscript.quit()
elseif lcase(data)="quit" then
objexcel.activeworkbook.save
objexcel.activeworkbook.close
objexcel.application.quit
quit=msgbox("DB Updating complete",vbokonly,"Excel DB Updater")
wscript.quit
elseif lcase(data)="update" then
objexcel.activeworkbook.save
update=msgbox("Data save complete, press OK to continue",vbokonly,"Excel DB Updater")
elseif len(data)<>0 then
objsheet.range("A1").entirerow.insert
objsheet.cells(1, 1).value=data
objsheet.cells(1, 2).value=(now)
add=msgbox("Data added, press OK to continue",vbokonly,"Excel DB Updater")
end if
loop while len(data)>=0 and not lcase(data)="quit"
end sub

VBScript/Classic ASP permission denied with fso.OpenTextFile after several uses

I have a process that loops through a moderate amount of data (1MB) storing it in an array and then periodically writes it to the disk. After several iterations, the script fails at fso.OpenTextFile() in my else section as though the file has not been closed or finished closing from the previous time the function was called. The iteration # doesn't seem to be specific as it's happened anywhere between the 2nd and 10th iteration that I can tell. The file is actually created and being appended to so it doesn't appear to be a permissions issue. I considering adding a time delay to the process but don't want to necessarily add overhead to an already long process.
OS: Windows 2012 R2
Any thoughts or suggestions appreciated.
'Write array to disk
sub writeFile()
'on error resumenext
set fso = Server.CreateObject("Scripting.FileSystemObject")
if needToCreateFile then
set objTextFile = fso.CreateTextFile(server.mappath("google/linklist.html"),true)
objTextFile.writeLine("<!DOCTYPE html>")
objTextFile.writeLine("<html>")
objTextFile.writeLine("<title>")
objTextFile.writeLine("Content Listing")
objTextFile.writeLine("</title>")
needToCreateFile = false
else
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Set objTextFile = fso.OpenTextFile (filename, ForAppending, True)
end if
'Write contents of array to file
for each link in linkList
if link <>"" and not isNull(link) then
objTextFile.writeLine(link & "<br>")
end if
next
objTextFile.writeLine("</html>")
objTextFile.Close
set fso = nothing
set objTextFile = nothing
'on error goto 0
end sub
Follow Up - Solved
Adding a 3 second delay solved the problem, but significantly delayed the processing time. So, rather than opening and closing the file each time I wanted to write to it, I simply left it open until the entire script was done and thus I didn't need the delay.
sub writeFile()
if needToCreateFile then
set objTextFile = fs.CreateTextFile(server.mappath("google/linklist.html"),true)
objTextFile.writeLine("<!DOCTYPE html>")
objTextFile.writeLine("<html>")
objTextFile.writeLine("<title>")
objTextFile.writeLine("Content Listing")
objTextFile.writeLine("</title>")
needToCreateFile = false
end if
'Write contents of array to file
for each link in linkList
if link <>"" and not isNull(link) then
objTextFile.writeLine(link & "<br>")
end if
next
objTextFile.writeLine("</html>")
' objTextFile.Close
' set fso = nothing
' set objTextFile = nothing
end sub
Adding a 3 second delay solved the problem, but significantly delayed the processing time. So, rather than opening and closing the file each time I wanted to write to it, I simply left it open until the entire script was done and thus I didn't need the delay. See modified script above.

VBScript mysterium - Why isn't network drives connected at logon?

This is one of the strangest things I've ever seen. I've got this logon script that basically disconnects a set of Network drives and then reconnects them. Previously, all users had a batch file set in their AD profile to run. After I wrote the vbscript, I just run that via the batch script. And it's been working just fine.
Now however, I tried to create a GPO and set the vbscript directly in there. And strangely enough, no network drives are connected. So I began poking around, puttinga msgbox right before the drives are connected. And one right after. Immediatly after login I can see the first textbox appear. After I click OK, the drives are supposed to be connected. But they don't. And right after, I can see the second text box.
What's really weird is that if I run the script manually directly after, everything works just fine! I even tried to put a sleep command on the top of the script now, just in case there's some mismatch in the replication of the domain controllers. But that didn't do anything either.
Here's the script as it is right now:
'Run the script
mapNetworkdrives
Public Sub mapNetworkdrives()
' Lag WScript.Network-objekt
Set objNetwork = CreateObject("WScript.Network")
Set objFso = CreateObject("Scripting.FileSystemObject")
'On Error Resume Next
' Fjern eksisterende nettverksdrev først
removeNetworkDrives objFSO, objnetwork
Dim userName
userName = objNetwork.UserName
Dim computerName
computerName = objNetwork.ComputerName
' Sjekk om det er Citrix som blir logget på
If computerName = "JBC" Then
If Not isDriveConnected("S", objFso, objNetwork) = True Then
objNetwork.MapNetworkDrive "S:", "\\sharepoint.ourcompany.no\prosj"
End if
End if
' Sjekk om nettverksdrev er allerede koblet opp
'objNetwork.MapNetworkDrive "Z:", "\\ourcompany.local\files\Brukere\" & username
objNetwork.MapNetworkDrive "P:", "\\ourcompany.local\files\felles"
objNetwork.MapNetworkDrive "Q:", "\\ourcompany.local\files\maler"
objNetwork.MapNetworkDrive "R:", "\\ourcompany\DIY"
objNetwork.MapNetworkDrive "N:", "\\ourcompany\felles\navn"
Set objNetwork = Nothing
Set objFSO = Nothing
End Sub
Public Sub removeNetworkDrives(ByVal objFSO, ByVal objNetwork)
'On Error Resume Next
If isDriveConnected("Z", objFSO) Then
objNetwork.RemoveNetworkDrive "Z:", True, True
End if
If isDriveConnected("P", objFSO) = True Then
objNetwork.RemoveNetworkDrive "P:", True, True
End if
If isDriveConnected("Q", objFSO) = True Then
objNetwork.RemoveNetworkDrive "Q:", True, True
End if
If isDriveConnected("R", objFSO) = True Then
objNetwork.RemoveNetworkDrive "R:", True, True
End if
If isDriveConnected("N", objFSO) = True Then
objNetwork.RemoveNetworkDrive "N:", True, True
End if
Set objNetwork = Nothing
End Sub
Can anybody see anything that I cannot? Am I missing something here? The very same script works just fine if I run the batch file first, which again runs this very same script. The only thing I can think of is that some DNS server might not be ready or something at the time the script is run.
Turns out, this is "normal behaviour" as described here:
http://pcloadletter.co.uk/tag/launchapp-wsf/
It is worth trying checking the privileges of the script.
I've encountered a lot of network shared mapping issues with scheduled/automatic scripts.
Personally, I use batch's "net use" and it solved many weird issues.

Resources