In a VBS I have which I use in conjunction with SecureCRT to automate some processes on Cisco devices, I have (very much pared down) the following code:
Sub prConnectToHost(strConnectHost)
'If no host is passed into subroutine then we need to prompt for one.
If strConnectHost = "" Then strConnectHost = LCase(crt.Dialog.Prompt("Enter hostname or IP address:", "Connect to a host", strHost, False))
strHost = strConnectHost
'If user hits Cancel or hits Ok with no hostname entered then exit.
If strHost = "" Then
booReconnect = False
Exit Sub
End If
'Write to connection log
Call prWriteToConnectionLog
'Run command capture subroutine.
Call prCommandLoop
Set intWaitString = Nothing: Set strScreenGet = Nothing
Set strLatestScriptVersion = Nothing: Set strConnectHost = Nothing
End Sub
Sub Main has a section like this:
Do While booReconnect = True
Call prConnectToHost("")
Loop
crt.Dialog.Prompt
is the same as MsgBox
, only it centres on the window and not the screen, so it's a little neater. The variable strHost
is the actual hostname string which is global in the script and contains the hostname we want to connect to. It is used in the Prompt
line as a default text, the idea being that if you disconnect and the booReconnect
flag is set, this Sub
is called again, and next time you're prompted for a hostname the old one is there - useful if you spelled it wrong first time, or you're connecting to a bunch of devices with a similar name.
You can see where we call prCommandLoop
at the end of this Sub
, which is a loop which uses a crt Function
called WaitForStrings
which puts the script on hold until it finds a particular string sequence. When it does, it fires off some stuff, then loops back around until it sits waiting again.
One of the automation commands detects for the presence of the connection menu (so therefore we have quit the router session) and prompts the user for another hostname to connect to.
The important bit is in the variable clearup at the end - Set strConnectHost = Nothing
. If I leave this in and immediately exit prCommandLoop
with booReconnect
set, as soon as Set strConnectHost = Nothing
is applied, strHost
dies - if I try to reference it I get an error Object Variable not set
. I experimented with putting a MsgBox strHost
line right at the end of the Sub
, which proved this.
The bizarre thing is that if I choose a different automation command in prCommandLoop
first and then quit the session, the Set strConnectHost = Nothing
doesn't seem to bother anyone.
Can anyone help me explain why this is a problem, as it is baffling me. I can easily work around it (by not issuing Set strConnectHost = Nothing
at the end of the prConnectToHost
Sub), but I just want to understand what the problem is.