Sendkeys "variable" - vbscript

Is it possible to use the SendKeys the type the characters inside a variable.
for example I got characters stored in variable firstname = Regie
Here is my code.
On Error Resume Next
Dim objSysInfo, objUser
Set objSysInfo = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objSysInfo.UserName)
firstname = objUser.givenName
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate "Notepad"
WScript.Sleep 400
WshShell.SendKeys "{& objUser.givenName}"
WScript.Sleep 250
Or is there any way to make this happen?

Sure you can, try this little script on the command line, it will print "test".
Set WshShell = WScript.CreateObject("WScript.Shell")
keys = "test"
WshShell.SendKeys keys

Related

Can't call script more than once

I need to update several Excel workbooks via BEx Analyzer. I have a main script which calls scripts A and B.
Script A will fill out the SAP logon window that pops up every time data is refreshed inside the workbook.
Script B will enter the required date.
The problem I keep encountering is that the code works perfectly for the first workbook. Once the ExcelFileRefresh function is called for the second (third, fourth, etc.) workbook, script A starts to fail. It will not activate the SAP Logon window, but instead send the keystrokes to another window, namely the folder containing the main script.
Strangely, if I then run script A manually by double clicking on it, it will work fine, and script B will do it's thing... Unfortunately I cant figure it out on my own.
List of unsuccessful attempts to fix this issue:
I tried setting WScript.Sleep pauses.
I tried setting SuccessSAPLogon to Nothing at the end of script A.
I tried activating the Excel workbook before calling script A.
I tried fusing script A and B into one file.
Main script
Filepath1 = "X:\ExcelBook1.xlsm"
Filepath2 = "X:\ExcelBook2.xlsm"
ExcelFileRefresh(Filepath1)
ExcelFileRefresh(Filepath2)
Function ExcelFileRefresh(Var)
Set Excel = CreateObject("Excel.Application")
Set objShell = CreateObject("WScript.Shell")
Excel.Visible = True
Excel.Workbooks.Open("C:\Program Files (x86)\Common Files\SAP Shared\BW\BExAnalyzer.xla")
Excel.Run ("BExAnalyzer.xla!SetStart")
Set Connection = Excel.Run("BExAnalyzer.xla!sapBEXgetConnection")
Excel.Run("BExAnalyzer.xla!sapBEXinitConnection")
Set ExcelBook = Excel.Workbooks.Open(Var, 0, False)
'--- Initiate Scripts ---'
Set objShell = CreateObject("WScript.Shell")
objShell.Run "ScriptA.vbs"
objShell.Run "ScriptB.vbs"
Excel.Application.Run ("MenuRefreshVariables")
Excel.Run "CommandButton1"
Excel.Run "retreiveData"
ExcelBook.Save
Excel.Quit
Set ExcelBook = Nothing
Set Excel = Nothing
Set objShell = Nothing
End Function
ScriptA
Set objShell = CreateObject("WScript.Shell")
SuccessSAPLogon = False
Do While SuccessSAPLogon = False
SuccessSAPLogon = objShell.AppActivate("SAP Logon")
Loop
objShell.SendKeys "{TAB 4}"
objShell.SendKeys "{RIGHT}"
objShell.SendKeys "{TAB}"
objShell.SendKeys "myWarehouse"
objShell.SendKeys "{TAB}"
objShell.SendKeys "BW"
objShell.SendKeys "{ENTER 2}"
ScriptB
Set objShell = CreateObject("WScript.Shell")
SuccessVariables = False
Do While SuccessVariables = False
SuccessVariables = objShell.AppActivate("Select Values")
Loop
objShell.SendKeys "{TAB 3}"
objShell.SendKeys "{DOWN}"
objShell.SendKeys "{TAB 14}"
DateA = DateSerial(Year(Date), Month(Date), Day(Date)-3)
objShell.SendKeys DateA
objShell.SendKeys "{ENTER}"

Use VBscript to paste data into a txt file and save

I need to paste data from clipboard (Ctrl+V) into a text file and save it.
I already did some research and it seems that a text file doesn't have a method like SaveAs.
With code below, I could create a new text file and paste data into it, but I can't Save it:
Set WShshell = CreateObject("WScript.Shell")
WShshell.run "c:\WINDOWS\system32\notepad.exe",1
WshShell.AppActivate "notepad"
WShshell.SendKeys "^V"
I understand there is a method called CreateTextFile, but seems I can't perform paste with it.
I also tried to combine those two:
Set WShshell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile "c:\1.txt",true
WshShell.AppActivate "notepad"
WShshell.SendKeys "^V"
But nothing happened...
UFT has its own clipboard access methods you could use. Here I've created an instance of the clipboard, and extracted its content into sText, then created a text file in C:\temp and written the data from the clipboard directly into it. oFile.Close closes the file and saves it at the same time.
Dim oClipboard : Set oClipboard = CreateObject("Mercury.Clipboard")
sText = oClipboard.GetText ' gets the current content of the clipboard
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.CreateTextFile("C:\temp\myTextFile.Txt", True)
oFile.Write sText
oFile.Close
I took a stab at it... This was my successful result.
I also noted that this script got really angry when another notepad was already opened.
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set WShshell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
'Gets user profile variable with CMD
UserProfile = CreateObject("WScript.Shell").Exec("cmd /c echo.%USERPROFILE%").Stdout.ReadAll
'Creates temporary files in appdata\local\temp
'--------------------------------------------------------------------------------------
tmpfilename = fso.GetTempName
tmpfile = Replace(UserProfile & "\AppData\Local\Temp\" & tmpfilename, vbcrlf, "")
Set CreateTempFile = FSO.OpenTextFile(tmpfile, forwriting, true) : CreateTempFile.Close
'Creates a new file for the pasted content
'--------------------------------------------------------------------------------------
MyFile = ThisFolder & "ClipBoard_Extract_" & _
Replace(FormatDateTime(Cdate(now),2), "/", "-") & "_" & _
Hour(now) & Minute(Now) & Second(now) & ".txt"
'Execute's the Main Sub but you could get along without it.
' I usually build my scripts to scale and do logging and other magical things.
'--------------------------------------------------------------------------------------
MainScript
Sub MainScript()
CaptureClipboardText
ExtractTempFile
End Sub
Sub CaptureClipboardText
WShshell.run "c:\WINDOWS\system32\notepad.exe " & tmpfile, 1
WshShell.AppActivate "Notepad"
wscript.sleep 1000
WShshell.SendKeys "^V"
WShshell.SendKeys "^S"
Wshshell.SendKeys "%F"
Wshshell.SendKeys "x"
Wshshell.SendKeys "s"
wscript.sleep 1000
End Sub
Sub ExtractTempFile
Set Extract = fso.OpenTextFile(tmpfile, ForReading)
Set Output = fso.OpenTextFile(MyFile, ForWriting, True) 'True on this syntax means - Create the file if it doesn't exist.
Do Until Extract.AtEndofSTream
line = Extract.Readline
Output.Writeline Line
Loop
Extract.Close : Set Extract = Nothing
fso.DeleteFile tmpfile, true
End Sub
Function ThisFolder
ThisFolder = Left(Wscript.ScriptFullName, Len(Wscript.ScriptFullName) - Len(Wscript.ScriptName))
End Function
Cheers!

Set Proxy authentication for ie using Vbscript

I want to auto fill proxy authentication value of username and password for ie using vbscript.
After I added the proxy ip and port to Tools>Internet Option>Connection Tab>LAN Settings. I am prompted with the following dialog
Is there anyways using VBS OR VB to auto fill this ?
So, far i have got the code like so
'begin script
Option Explicit
Dim valUserIn
Dim objShell, RegLocate
Set objShell = WScript.CreateObject("WScript.Shell")
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"0","REG_DWORD"
WScript.Sleep(1000)
valUserIn = Inputbox("Enter the Proxy server you want to use.","Proxy Server Required","proxygate.mydomain.com:8080")
if valUserIn = "" then
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"0","REG_DWORD"
'MsgBox "No proxy mode"
else
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer"
objShell.RegWrite RegLocate,valUserIn,"REG_SZ"
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"1","REG_DWORD"
'MsgBox "Proxy mode: " & valUserIn
end if
WScript.Quit
'end script
But this only set's the proxy ip and port.
Thanks in advance..
You can utilize the Sendkeys shell command which will type in and activate keyboard commands for you once it has allocated the correct screen. However, this is assuming you are running the script while it is open. If you are looking for something that prefills that data before hand. I'm afraid I cannot assist in that realm.
Dim WshShell, Success
Set WshShell = WScript.CreateObject("WScript.Shell")
'Wait for window to popup....
'if this doesn't activate it directly, try clicking on the window.
Do Until Success = True
Success = objShell.AppActivate("Windows Security")
Wscript.Sleep 1000
Loop
WScript.Sleep 500
WshShell.SendKeys "Username"
wscript.sleep 500 'allow program to have time to type it in.
WshShell.SendKeys "{TAB}" 'tab for password field
WshShell.SendKeys "Password"
wscript.sleep 500 'allow program to have time to type it in.
WshShell.SendKeys "%o" 'Alt + O for hitting "OK"
wscript.sleep 500

How to output Command prompt to a log file using VBScript

I'm not a programmer so I don't want to overly irritate the fine folk in this forum. My issue is that I would like to use VBScript to Telnet into a Linux device, issue a DF command and output all response to a log file which I can parse later. I originally found a method to successfully Telnet but I have have been experimenting without success regarding the text file output requirement. The following code certainly does not work but I am wondering if I am even close to the correct method?
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("cmd /c dir")
WshShell.run"cmd" '*** open command window ***
WScript.Sleep 250
WshShell.SendKeys("{Enter}")
WshShell.SendKeys"telnet 10.13.2.2"
WshShell.SendKeys("{Enter}")
WScript.Sleep 2000
WshShell.SendKeys"root"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
WshShell.SendKeys"password"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("C:\VBSmemSize.txt", 2, True)
WshShell.SendKeys"df /mnt/cf"
WshShell.SendKeys("{Enter}")
Do
strFromProc = oExec.Stdout.Readline()
WScript.Echo strFromProc
Loop While Not objLogFile.StdOut.atEndOfStream
You can capture output from external commands but not at the same time interact with them like you do with sendkeys. Here an example of what works
Function ExecPing(strTarget)
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "antwoord van") Then '"reply from" in E
WScript.Echo VbCrLf & strTarget & " responded to ping."
ExecPing = True
Else
WScript.Echo VbCrLf & strTarget & " did not respond to ping."
ExecPing = False
End If
End Function
ExecPing pcname

Error while sending ( character with sendkeys in vbscript

I am getting the following error when I try to send to send a "(" or ")" character using SendKeys .In my vbscript.
Invalid procedure call or argument
My script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Sleep 100
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Documents and Settings\Administrator\Desktop\readme.txt", 1)
Wshshell.SendKeys "!##$%^&*()"
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
WshShell.SendKeys strCharacters
Loop
It does not send the "(" and ")" when I try to send them before the loop but shows no error and continues till a little further where it encounters another "(" character and stops with the error.
Parenthesis are considered a special character and need to be surrounded in braces. See this link for more details.
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Sleep 100
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Documents and Settings\Administrator\Desktop\readme.txt", 1)
Wshshell.SendKeys "!##$%^&*{(}{)}"
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
WshShell.SendKeys strCharacters
Loop

Resources