AUTOIT GUI Management Pause Script when in Background - user-interface

Hi all im currently writing a script to more easily manage (kill/delete) broken WTS Profiles. So in an attempt to make it easier for our support guys i came up with an autoit script to manage that.
I've got everything running smoothly except that my script is listening in on the "Enter" Key and if this is pressed he calls functions an so on.
But he also does this when my script is running in the background and the user wants to google something or anything, he always registers the Enter Key.
So my Question now, how can i fix this because if it is a complex search (with asterisk and so on) it generats unneceserry I/O on the netshares where the Profiles are stored.
The Code in Question:
While 1
$nMsg = GUIGetMsg()
Switch $nMsg
Case $GUI_EVENT_CLOSE
Exit
Case $SearchButton
$sSearchString = GUICtrlRead($SubmitField) & "*"
If $sSearchString = "*" Then ;
_OutputConsole_Updater()
GUICtrlSetData($ConsoleOutput, "[" & #HOUR & ":" & #MIN & ":" & #SEC & "] -" & " Keine Eingabe getätigt, bitte Suchbegriff eingeben")
Else
_ReloadBox()
_SearchAll()
EndIf
Case $DeleteButton
_DeleteSelection()
Case $DeleteAll
_DeleteAllCheck()
Case $nMsg = _IsPressed("0D")
$sSearchString = GUICtrlRead($SubmitField) & "*" ;
If $sSearchString = "*" Then ;
_OutputConsole_Updater()
GUICtrlSetData($ConsoleOutput, "[" & #HOUR & ":" & #MIN & ":" & #SEC & "] -" & " Keine Eingabe getätigt, bitte Suchbegriff eingeben")
Else
_ReloadBox()
_SearchAll()
EndIf
EndSwitch
WEnd

Do you operate with HotkeySet? Then activate the function only when your script is active
If WinActive($scriptTitle) = 0 Then
_setHotKeys()
Endif
Func _setHotKeys($state = 1)
If $state = 1 Then
HotKeySet('!1')
HotKeySet('!2')
HotKeySet('!3')
HotKeySet('!4')
HotKeySet('!5')
HotKeySet('!6')
HotKeySet('!7')
HotKeySet('!8')
ElseIf $state = 0 Then
HotKeySet('!1', '_setTab0')
HotKeySet('!2', '_setTab1')
HotKeySet('!3', '_setTab2')
HotKeySet('!4', '_setTab3')
HotKeySet('!5', '_setTab4')
HotKeySet('!6', '_setTab5')
HotKeySet('!7', '_setTab6')
HotKeySet('!8', '_setTab7')
EndIf
EndFunc ;==>_setHotKeys

Related

Expected statement error at Line 1 Char 1 for example script

I'm completely new to scripting and am trying to mess around with it and start learning. I've done a couple WScript.Echo commands displaying a message or adding two numbers. I copied the below code from a MS article I was reading on the Echo method.
It seems it is having issues with <package>. Is this an unacceptable way to start a script? What else would I need to do to get this example code to work on my machine?
Also, can't get the code to post in my question. Indenting 4 spaces doesn't do anything.
The sample code in that article is for .wsf files, not for .vbs files. If you want to use the latter: strip the XML tags from the sample code and it should work.
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
WScript.Echo
WScript.Echo "Network drive mappings:"
For i = 0 to oDrives.Count - 1 Step 2
WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
Next
WScript.Echo
WScript.Echo "Network printer mappings:"
For i = 0 to oPrinters.Count - 1 Step 2
WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
Next

How to Exit a For Each Loop within a Function?

I've got the following Function that is designed to recursively read all WMI namespaces on a machine depending on the namespace that's been passed (by default the script calls for ReadWMI("root"). If a WMI namespace contains the name sms or ccm, I want to test writing to that namespace to validate writing works. If Writing to WMI fails in that function, I want to exit the For Loop and completely exit the function.
What I'm noticing is that when I exit the for or exit the function (using either Exit For or Exit Function) I go back to Next instead of exiting the function completely. This causes a number of issues where other namespaces can successfully be written to.
Function ReadWMI(strNameSpace)
Dim oWMI, colNameSpaces, objNameSpace, sFullNamespace
'ReadWMI = "True"
WMI_ReadRepository = "Healthy"
On Error Resume Next
'Verify all namespaces
Set oWMI = GetObject("winmgmts:\\" & sComputer & "\" & strNameSpace)
If Err.Number <> 0 Then
ReadWMI = "False"
WMI_ReadRepository = "Unhealthy"
oLog.WriteLine Now()& " - " & "ReadWMI(): Failed to bind to WMI namespace " & strNamespace & ". Stopping WMI Verification"
oLog.WriteLine Now()& " - " & "ReadWMI(): Error Code: " & Err.Number
'oLog.WriteLine Now()& " - " & "ReadWMI(): Error Description: " & Err.Description
Err.Clear
Exit Function
Else
oLog.WriteLine Now()& " - " & "ReadWMI(): Successfully connected to WMI namespace " & strNamespace
End If
Set colNameSpaces = oWMI.InstancesOf("__NAMESPACE")
For Each objNameSpace In colNameSpaces
sFullNamespace = LCase(strNamespace & "\" & objNamespace.Name)
If InStr(sFullNamespace,"ccm") Or InStr(sFullNamespace,"sms") > 0 Then
oLog.WriteLine Now()& " - " & "ReadWMI(): Writing to " & sFullNamespace & " WMI Namespace if WMIWriteRepository set to TRUE"
If WMIWriteRepository = True Then
If WriteWMI(sFullNamespace) = "False" Then
oLog.WriteLine Now()& " - " & "ReadWMI(): Failed to write to namespace " & sFullNamespace
WMI_ReadRepository = "Unhealthy"
'ReadWMI = "False"
Exit Function
End If
Else
oLog.WriteLine Now()& " - " & "ReadWMI(): WMIWriteRepository set to False or OS is a Server. Will not write to repository."
End If
End If
'Call VerifyWMI again to run through the next namespace
Call ReadWMI(sFullNamespace)
Next
'ReadWMI = "True"
'WMI_ReadRepository = "Healthy"
Set oWMI = Nothing
On Error Goto 0
End Function
If something goes wrong and you want to jump out of the recursive function call, make the return value False (uncomment the 'ReadWMI = "False" in your script).
Your last statement before the next must test if the reading of the WMI was correct, so instead of
Call ReadWMI(sFullNamespace)
use
If ReadWMI(sFullNamespace) = "False" Then
Exit For
End If
Protip: Stop using "string booleans", they are slow and errors are luring around the corner to bite you in the back ("True" <> "true" <> "Treu" <> "True "). Just use True and False. Whenever you want to output a boolean to a string, it is automatically converted to the correct string value:
MsgBox True & " / " & False
' Output: "True / False"

VBSCRIPT MsgBox VbYesNo countdown

Tried searching for the answer, all were too simple, or didn't match what I need. I have a message box, and I have it displaying information correctly. I have a Yes and No button. I want a timer, so when the timer runs out, it continues. If someone hits yes, it continues down the code, if they hit no, then it returns the user elsewhere. This is what I have, please help.
akey = MsgBox ("Image OS = " & ImageType & vbcrlf & _
"ComputerName = " & ComputerName & vbcrlf & _
"TimeZone = " & TZone & vbcrlf & _
"Ghost Server = " & Server & vbcrlf & _
"Broadcast Method = " & BMethod & vbcrlf & _
"Ghost Session = " & GhostSession _
, vbyesno + vbquestion,VN & " Please Confirm")
You can use Popup instead of Msgbox...
http://ss64.com/vb/popup.html
Set objShell = CreateObject("WScript.Shell")
X = objShell.Popup("You have 3 Seconds to answer", 3, "Test", vbYesNo)
Select Case X
Case vbYes
Msgbox "You pressed YES"
Case vbNo
Msgbox "You pressed NO"
Case Else
MsgBox "You pressed NOTHING"
End Select
Otherwise, you can try to manipulate an HTA or Internet Explorer window to do something similar.

Faster Way To Examine Text in AutoIt?

I'm attempting to use AutoIt to examine a text file and output select lines into a CSV. The problem I keep running into is that it takes forever. The current method examines a single line at a time. It can burn through 5-10 lines per second, but I'm looking for something much faster within the AutoIt framework.
Code:
#include <File.au3>
$xnConfirm = False
$xnConfirmMsg = 0
while $xnConfirm = False
$xnFile = FileOpenDialog("File to Examine...","%userprofile%","All (*.*)") ;InputBox("File???", "Which file do you want to review?","C:\")
If FileExists($xnFile) = True Then
$xnConfirm = True
Else
$xnConfirmMsg = msgbox(1,"File Not Found...",$xnFile & " does not exist." & #crlf & "Please select another file.")
EndIf
WEnd
$xnConfirm = False
$xnConfirmMsg = 0
while $xnConfirm = False
$xnTargetFile = FileOpenDialog("Location to Save to...",$xnFile & " - output.csv","All (*.*)");"%userprofile%\Documents\output.csv"
;FileSaveDialog("Location to Save to...","%userprofile%","All (*.*)",16,"output - " & $xnFile & " - output.csv") ;
Consolewrite("Outputting to " & $xnTargetFile & #crlf)
if fileexists($xnTargetFile) then
$xnConfirmMsg = msgbox(4,"Overwrite?","Are you sure you want to overwrite " & #crlf & $xnTargetFile)
if $xnConfirmMsg = 6 Then
$xnConfirm = True
filedelete($xnTargetFile)
EndIf
Else
$xnConfirm = True
EndIf
WEnd
progresson("Line count","Verifying the number of lines in " & $xnFile)
$xnFileLine = _FileCountLines($xnFile) ;InputBox("Number of lines","How many lines are in this document?",10000)
consolewrite("Loading "& $xnFile & " with " & $xnFileLine & " total lines." & #crlf)
progressoff()
local $hfl = FileOpen($xnFile,0)
FileWrite($xnTargetFile,"")
FileOpen($xnTargetFile, 1)
$i = 1
ProgressOn("Creating CSV","Extracting matching data.","",0,0,16)
$xnTargetLine = 1
FileWriteLine($xnTargetFile,"Timestamp,Message,Category,Priority,EventId,Severity,Title,Machine,App Domain,ProcessID,Process Name,Thread Name,Win32 ThreadId")
While $i < $xnFileLine
;$xnCurrentLine = FileReadLine($xnFile,$i) ;Old Settings
$xnCurrentLine = FileReadLine($hfl,$i)
;MsgBox(1,"",$xnCurrentLine)
Select
Case stringinstr($xnCurrentLine,"Timestamp:")
$xnTargetLine = stringmid($xnCurrentLine,12,stringlen($xnCurrentLine) - 12 + 1) & ","
Case stringinstr($xnCurrentLine,"Message:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,10,stringlen($xnCurrentLine) - 10 + 1) & ","
Case stringinstr($xnCurrentLine,"Category:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,11,stringlen($xnCurrentLine) - 11 + 1) & ","
Case stringinstr($xnCurrentLine,"Win32 ThreadId:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,16,stringlen($xnCurrentLine) - 16 + 1) & #crlf
FileWriteLine($xnTargetFile,$xnTargetLine)
case Else
consolewrite("Nothing on line " & $i & #crlf)
EndSelect
$i = $i + 1
ProgressSet(round($i/$xnFileLine * 100,1),$i & " of " & $xnFileLine & " lines examined." & #cr & "Thank you for your patience.")
WEnd
ProgressOff()
To address the question of what this is doing, I'm reading a log file similar to a trace log. I want the events to output to a CSV so I can examine trends. The format in the log file looks like this:
Timestamp: 9/26/2013 3:33:23 AM
Message: Log Event Received
Category: Transaction
Win32 ThreadId:2872
I know that's the code format, but I hope it's easier to read.
(I wanted to add a comment asking for a sampling of the data being read in, however I don't have enough points yet...)
Depending on the size of the input file I recommend reading the entire file into an array in one swoop using _FileReadToArray() and then looping through the array in memory (instead of keeping access to the file open during the entire process). In addition, I wouldn't write to the output file each time either - I'd write to a string and then save the string when completed.
Something like:
$outputFileData = ""
$inputFileData = _FileReadToArray($xnFile)
For $Counter = 1 to $inputFileData[0]
$tmpLine = $inputFileData[$Counter]
Select
Case stringinstr($tmpLine,"Timestamp:")
$outputFileData = stringmid($tmpLine,12,stringlen($tmpLine) - 12 + 1) & ","
Case stringinstr($tmpLine,"Message:")
$outputFileData &= stringmid($tmpLine,10,stringlen($tmpLine) - 10 + 1) & ","
Case stringinstr($xnCurrentLine,"Category:")
$outputFileData &= stringmid($tmpLine,11,stringlen($tmpLine) - 11 + 1) & ","
Case stringinstr($xnCurrentLine,"Win32 ThreadId:")
$outputFileData &= stringmid($tmpLine,16,stringlen($tmpLine) - 16 + 1) & #CRLF
case Else
ConsoleWrite("Nothing on line " & $i & #crlf)
EndSelect
Next
FileWriteLine($xnTargetFile, $outputFileData)
(Please note I didn't include any error checking nor did I check it for errors :)
Im not sure if it would be really faster but, you could use Regexp.
If you could tell me a little bit more what the rules are here:
Case stringinstr($xnCurrentLine,"Timestamp:")
$xnTargetLine = stringmid($xnCurrentLine,12,stringlen($xnCurrentLine) - 12 + 1) & ","
Case stringinstr($xnCurrentLine,"Message:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,10,stringlen($xnCurrentLine) - 10 + 1) & ","
Case stringinstr($xnCurrentLine,"Category:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,11,stringlen($xnCurrentLine) - 11 + 1) & ","
Case stringinstr($xnCurrentLine,"Win32 ThreadId:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,16,stringlen($xnCurrentLine) - 16 + 1) & #crlf
FileWriteLine($xnTargetFile,$xnTargetLine)
case Else
consolewrite("Nothing on line " & $i & #crlf)
and if you could give me 2 or 3 example lines i could try to make you a, Regexp function wich i think will be much faster.
Edit:
I Made an example Script.
If the Input File looks something like this:
Timestamp: 9/26/2013 3:33:23 AM
Message: Log Event Received
Category: Transaction
Win32 ThreadId:2872
Then This Script works just fine
#include <Array.au3>
Local $file = FileOpen("InputFile.txt", 0)
$sText = FileRead($file)
$aSnippets = StringRegExp($sText,"(?:Timestamp:|Message:|Category:|Win32 ThreadId:)(?: )?(.+)",3)
_ArrayDisplay($aSnippets)
The result is an array Containing the Following things:
[0] = 9/26/2013 3:33:23 AM
[1] = Log Event Received
[2] = Transaction
[3] = 2872
etc.
If you want to combine these 4 lines in one, try to use a for loop (if you want to, i can make you one)
For 100 Lines he Needs 0.490570878768441 Miliseconds to store every Value in one array.
There is an other possible idea.
You could copy the Input File, rename it, and then Delete every useles Data out of it.
That would be very easy with RegularExpressions and probably even faster.
If you show me a example of the Input File and how the Output file should look like i could try :)

How can I start an interactive console for VBS?

Very similar to this question:
How can I start an interactive console for Perl?
I just want to be able to start entering VBS statements, one at a time, and have them evaluated straight away, like Python's IDLE.
I wrote this a couple years ago. It's based on this blog post (archived here), but with a couple enhancements. Essentially it's a REPL (Read, Execute, Print, Loop) using the Execute statement:
If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
For Each Arg In WScript.Arguments
If InStr( Arg, " " ) Then Arg = """" & Arg & """"
Str = Str & " " & Arg
Next
WshShell.Run "cscript """ & WScript.ScriptFullName & """" & Str, 1
WScript.Quit
End If
Do While True
WScript.StdOut.Write(">>> ")
line = Trim(WScript.StdIn.ReadLine)
If LCase(line) = "exit" Then Exit Do
On Error Resume Next
Execute line
If Err.Number <> 0 Then
WScript.StdErr.WriteLine Err.Description
End If
On Error Goto 0
Loop
I usually start it with a batch file of the same name (i.e. "vbs.vbs" and "vbs.bat"), like this:
#cscript.exe //NoLogo %~dpn0.vbs
You may try to make a debugger (cscript //X your.vbs) work for you, or to start a project of your own - perhaps based on these (first 3?) proposals

Resources