Adding Varible to VBScript from Text File - vbscript

Good Morning Guys and Girls,
I'm trying to create a VBscript to automate a function in SAPGUI
But I Am unsure how to get the VBS to read the text file relace the %USERID% and then loop the script.
Currently I have :
If Not IsObject(application) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
Set connection = application.Children(0)
End If
If Not IsObject(session) Then
Set session = connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject application, "on"
End If
session.findById("wnd[0]/usr/radSYSCEN").select
session.findById("wnd[0]/usr/chkORG").selected = true
session.findById("wnd[0]/usr/txtUSRID").text = "%USERID%"
session.findById("wnd[0]/usr/chkORG").setFocus
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]").sendVKey 3
session.findById("wnd[0]").sendVKey 3
session.findById("wnd[0]").sendVKey 3
session.findById("wnd[0]").sendVKey 3
Which will work If I put in a single %userID%.
Any Assistance would be great.
p.s. total noob to VBS.
- Only using it SAP GUI integrates with it easily.

to get the user ID You can use the WScript:
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
MsgBox objNetwork.UserName
or from the shell:
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
or from environment variable (it should work, but when i tested it was wrong!):
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment
MsgBox "USERNAME=" & WshEnv.Item("USERNAME")
Note that all this depends on the OS used.

You can try the following:
'From the shell:
set wshell = createobject("Wscript.Shell")
Set WshEnv = Wshell.Environment("PROCESS")
session.findById("wnd[0]/usr/txtUSRID").text = wshEnv("USERID")
Regards,
ScriptMan

Related

How to set a variable's value to shortcut.arguments using vbs?

I'm trying to set a variable's value to shortcut.argument using VBS. But it doesn't work. Please tell me the solution.
This is my code:
Set WShell = WScript.CreateObject("Wscript.Shell")
Set lnk = WShell.CreateShortcut("test.lnk")
lnk.Arguments = WScript.Arguments(0)
lnk.Save
row 3 doesnt work...
try with :
lnk.Arguments = WScript.Arguments.Item(0)

Why does this small vbscript to change desktop background work intermittently, not all the time?

A small VBscript in order to change the desktop background automatically, practically for demo purposes:
dim wshShell
dim sUserName
Set wshShell = WScript.CreateObject("WScript.Shell")
Set oShell = CreateObject("WScript.Shell")
currWallPaper = oShell.RegRead("HKCU\Software\Microsoft\InternetExplorer\Desktop\General\Wallpap erSource")
If currWallPaper = "C:\Users\Utsav\Pictures\493889.png" Then
msgbox "OK1"
sWallPaper = "C:\Users\Utsav\Pictures\336180.png"
ElseIf currWallPaper = "C:\Users\Utsav\Pictures\336180.png" Then
sWallPaper = "C:\Users\Utsav\Pictures\1920-1080-278658.png"
Else
sWallPaper = "C:\Users\Utsav\Pictures\493889.png"
End If
' update in registry
oShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", sWallPaper
' let the system know about the change
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
msgbox "done"
This script works only intermittently, i.e. on executing from command line it will change the background only once in about 4-5 attempts. Any ideas explaining the reason for this behaviour would be most welcome.

Get errorlevel in bat from vbscript

I’m trying to determine, whether the user clicked NO in the UAC-prompt and if so to not set up the nul-port.
I'm calling this script form a batch-file, which I'd like to exit, if the user clicked no.
The VBScript:
Option Explicit
Main
Sub Main
Dim oShell, objWMIService, servSpooler, objReg, objShellApp, result
Const PrinterPort = "NUL:"
Const HKLM = &h80000002
If Not WScript.Arguments.Named.Exists("elevate") Then
Set objShellApp = CreateObject("Shell.Application")
objShellApp.ShellExecute WScript.FullName, WScript.ScriptFullName & " /elevate", "", "runas", 0
WScript.Quit
End If
result = isElevated()
If result = True Then
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
set servSpooler = objWMIService.Get("Win32_Service.Name='spooler'")
Set objReg = GetObject("winmgmts:root\default:StdRegProv")
servSpooler.StopService
objReg.SetStringValue HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Ports", PrinterPort, ""
servSpooler.StartService
Else
WScript.Quit 1
End If
End Sub
Function isElevated
Dim shell, whoami, whoamiOutput, strWhoamiOutput
Set shell = CreateObject("WScript.Shell")
Set whoami = shell.Exec("whoami /groups")
Set whoamiOutput = whoami.StdOut
strWhoamiOutput = whoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then
isElevated = True
Else
isElevated = False
End If
End Function
The batch:
cscript "set_port.vbs"
IF ERRORLEVEL 1 (
ECHO FAIL
PAUSE
EXIT
)
Now, I looked at this page:
http://www.robvanderwoude.com/errorlevel.php
and some others and I feel like I tried every possible combination. Probably, I just haven’t had the correct combination yet. Some tips and help would be highly appreciated!
The basic goal: Determine, whether the user clicked NO in the UAC-prompt and then end the VBScript and batch-file.
UPDATE:
Okay, thanks for all the answers so far. I'm pretty certain now it's the script. I use the errorlevel again in the batch-file and there it works just fine now.
As for the VBScript:
In Order to have an error code of let's say 1 when the user clicks NO in the UAC prompt (meaning the current file is not elevated), I need to put it like this:
If result = True Then
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
set servSpooler = objWMIService.Get("Win32_Service.Name='spooler'")
Set objReg = GetObject("winmgmts:root\default:StdRegProv")
servSpooler.StopService
objReg.SetStringValue HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Ports", PrinterPort, ""
servSpooler.StartService
WScript.Quit(0)
Else
WScript.Quit(1)
End If
But: in the first WScript.Quit after the ShellExecute, I also need to put WScript.Quit(1), right? Because otherwise I never get an error to be passed to errorlevel (or at least not greater than 0).
So:
objShellApp.ShellExecute WScript.FullName, WScript.ScriptFullName & " /elevate", "", "runas", 0
WScript.Quit(1)
The big problen, I guess, is that clicking NO on the UAC promtp doesnt eally cause an error, so I need to put WSCript.Quit(1) there.
OR i do it the other way round and say: WScript.Quit(1) when the user clicked YES and the script is elevated and put WScript.Quit(0) everyhwere else.
However, in the first case I always get errorlevel 1 and in the second case always errorlevel 0.
----------- UPDATE:
My VBScript file looks like this now:
Option Explicit
Main
Sub Main
Dim objShell, objWMIService, servSpooler, objReg, objShellApp, result, oShell
Dim whoami, strWhoamiOutput, whoamiOutput
Const PrinterPort = "NUL:"
Const HKLM = &h80000002
If Not WScript.Arguments.Named.Exists("elevate") Then
Set objShellApp = CreateObject("Shell.Application")
objShellApp.ShellExecute WScript.FullName, WScript.ScriptFullName & " /elevate", "", "runas", 0
WScript.Quit 10
WScript.Echo("Done")
Else
Set oShell = CreateObject("WScript.Shell")
Set whoami = oShell.Exec("whoami /groups")
Set whoamiOutput = whoami.StdOut
strWhoamiOutput = whoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then
Wscript.Echo("ADMIN")
WScript.Echo("Port")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
set servSpooler = objWMIService.Get("Win32_Service.Name='spooler'")
Set objReg = GetObject("winmgmts:root\default:StdRegProv")
servSpooler.StopService
objReg.SetStringValue HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Ports", PrinterPort, ""
servSpooler.StartService
WScript.Quit 1
End if
WScript.Echo("Done 2")
End If
End Sub
And a test batch:
#echo off
cscript "test.vbs"
ECHO %errorlevel%
PAUSE
The errorlevel output is 10 and not 1, although the script is quit as intended and the message "Done" is never shown.
Debugging technique:
Write a VBS script that just sets the errorlevel and quits - and get that working with your batch script.
Then you can massage your full vbs script.

Check if folder is there, if not create it on current user logged in VBS

Currently this is my script
Set oWS = WScript.CreateObject("WScript.Shell")
' Get the %userprofile% in a variable, or else it won't be recognized
userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )
What I am trying to do is grab the current user logged in, I want it to check the directory D:\"personsuser"\Appdata\Roaming\Local to see if the folder "Local" is created, if it isn't created I want to create one via createobject in vbs. The script above from what i know grabs the current logged on user, however i'm not sure how to use this variable to create a folder.
I know i will have to incorporate something along these lines:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder("C:\FSO")
And or something along these lines:
Dim objNetwork
Dim userName
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.userName
If fso.driveExists("D:\" & userName & "\AppData\Local\") Then
FSO.CreateDirectory ("D:\" & userName & "\AppData\Local\")
End If
Thanks in advance, not very familiar with VBS however that is the only platform I can operate from in the environment that i'm using it.
Set oWS = WScript.CreateObject("WScript.Shell")
' Get the %userprofile% in a variable, or else it won't be recognized
userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )
Dim objNetwork
Dim userName
Dim FSO
Dim Folder
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.userName
If NOT (FSO.FolderExists(userProfile + "\AppData\Roaming\Local")) Then
' Delete this if you don't want the MsgBox to show
MsgBox("Local folder doesn't exists, creating...")
splitString = Split(userProfile, "\")
' Create folder
MsgBox("D:\" + splitString(2) + "\AppData\Roaming\Local")
'FSO.CreateFolder(splitString(2) + "\AppData\Roaming\Local")
End If
Here you go man, this should work perfect, regards Daniel.
Here is code part from my utilty for FSO:
dim ffso
Function GetFSO
if not IsValidObject(ffso) then set ffso = CreateObject("Scripting.FileSystemObject")
Set GetFSO = ffso
End Function
sub SureDirectoryExists(ADir)
if ADir="" then exit sub
if not GetFSO().FolderExists(ADir) then
SureDirectoryExists ffso.GetParentFolderName(ADir)
ffso.CreateFolder ADir
end if
end sub
This function will create all folders in the path parameter (string).
Public Function CheckCreateFolder(path)
Dim TempPath As String
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
pos = 0
While pos < Len(path)
pos = InStr(pos + 1, path, "\")
TempPath = Left(path, pos)
If Not (FSO.FolderExists(TempPath)) Then
FSO.CreateFolder (TempPath)
End If
Wend
End Function

How to write to a text file in VBScript, without overwriting?

I am currently writing a script which parses the ServiceTage, Computername and Username from a computer and outputs it to a text file on a share, but it seems that it always overwrites the data there rather than adding to it.
The code is as follows:
'Get Dell Service Tag Info
set ProSet = GetObject("winmgmts:").InstancesOf("Win32_BIOS")
Set ProSet1 = GetObject("winmgmts:").InstancesOf("Win32_SystemEnclosure")
For each Pro in ProSet
For each Pro1 in ProSet1
ServiceTag=Pro.SerialNumber
exit for
Next
exit for
Next
'get username and computername, could also be asked in a batch
Set oShell = WScript.CreateObject("WScript.Shell")
Set oShellEnv = oShell.Environment("Process")
sComputerName = oShellEnv("ComputerName")
sUsername = oShellEnv("username")
dim filesys, filetxt, getname, path
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("\\xx.xx.xx.xx\Support\DataLog.txt", 8, True)
path = filesys.GetAbsolutePathName("\\xx.xx.xx.xx\Support\DataLog.txt")
getname = filesys.GetFileName(path)
filetxt.WriteLine sUsername & ", " & sComputerName & ", " & ServiceTag
filetxt.Close
Thank you!
Straight from the VBScript Docs:
object.CreateTextFile(filename[, overwrite[, unicode]])
object.OpenTextFile(filename[, iomode[, create[, format]]])
From your code:
Set filetxt = filesys.CreateTextFile(filename, 8, True)
Diagnosis:
You call .CreateTextFile() with the parameters of .OpenTextFile()
Remedy:
Use .OpenTextFile():
Set filetxt = filesys.OpenTextFile(filename, 8, True)

Resources