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

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.

Related

Issues trying to close a bat file from a vbs script

i'm trying to help my little brother with a vbs script file, i've never used vbs, and i'm having serious issues on finding out how to end a bat file that i've opened with the vbs script after 2 seconds
I've tried terminate but it doesn't work, even running another shell with taskkill and the name of process but nothing
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "C:\\Users\me\Desktop\Samples\t.bat"
Wscript.Sleep 2000`
I would like the bat file to close itself after 2 seconds
Use the Exec command instead of Run.
https://ss64.com/vb/exec.html
"Unlike .Run method, .Exec returns an object which returns additional information about the process started."
This example uses cmd.exe /k (the /k will keep the cmd.exe window open, which will be killed after your 2 second timeout even if your bat script logic finishes before that)
Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("cmd.exe /k C:\Temp\test.bat") : wscript.sleep 2000 :
Rt.Terminate
If you want to return the output of the bat script you will need to read this WScript.Shell.Exec - read output from stdout, and use logic similar to:
Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
strCommand = "C:\Temp\test.bat"
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec(strCommand)
Do While oExec.Status = 0
WScript.Sleep 1000
If Not oExec.StdErr.AtEndOfStream Then
vErrStr = vErrStr & oExec.StdErr.ReadAll
End If
If Not oExec.StdOut.AtEndOfStream Then
vOutStr = vOutStr & oExec.StdOut.ReadAll
End If
Loop
WScript.StdOut.Write(vErrStr)
WScript.Echo(vOutStr)
It all depends on what your bat file is doing really, and the reason you need to kill it after x seconds.
Edit:
Because your batch file is a continuous loop, it may confuse ReadAll of the output stream. You might be best using something such as (note that you will not see real-time output):
Dim strCommand : strCommand = "C:\Temp\test.bat"
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
'execute command
Dim oExec : Set oExec = WshShell.Exec(strCommand)
'wait 2 seconds
WScript.Sleep 2000
'terminate command
oExec.terminate
'get output
wscript.echo oExec.StdOut.ReadAll
Set oExec = Nothing
Set WshShell = Nothing

Hide taskbar with Taskbar Eliminator

With my tiny VBScript I'm trying to execute Taskbar Eliminator and run the key combination 'ALT + T' to hide the taskbar.
The program is being execute correctly but the key combination does not get recognized by the program.
Here's the code:
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim strPath
Dim strKeyCombo
strPath = "C:\Taskbar_Eliminator.exe"
strKeyCombo = "%T"
WshShell.Run strPath, 1, true
WshShell.AppActivate "Taskbar_Eliminator.exe"
WshShell.SendKeys strKeyCombo
Maybe I'm just not seeing an obvious error but I'd be very glad if somebody could just point it out :)

Adding Varible to VBScript from Text File

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

Change Wallpaper in Windows 7

I have written a small vbs script to download and change the registry for the current users wallpaper. however it copies and does the change but the wallpaper does not change... any ideas on errors in the below code?
Option Explicit
Dim WshShell, strValue, sleepTime, oFSO
strValue = "C:\wallpaper.bmp"
sleepTime = 30000
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.CopyFile "\\anspksnms1\OSD\Scripts\wallpaper\wallpaper.bmp", "C:\"
Set WshShell = WScript.CreateObject("Wscript.Shell")
WshShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", strValue
WScript.Sleep sleepTime
WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters", 1, False
Set WshShell = Nothing
I'm not much of a vbscripter, but maybe try this?
wshShell.run "cmd /c RunDll32.exe USER32.DLL,UpdatePerUserSystemParameters", 1, True

Use clipboard from VBScript

I am looking for a method to place some text onto the clipboard with VBScript. The VBScript in question will be deployed as part of our login script. I would like to avoid using anything that isn't available on a clean Windows XP system.
Edit:
In answer to the questions about what this is for.
We wanted to encourage users inside our organization to use the file server to transfer documents instead of constantly sending attachments by email. One of the biggest barriers to this is that it isn't always obvious to people what the correct network path is to a file/folder. We developed a quick script, and attached it to the Windows context menu so that a user can right click on any file/folder, and get a URL that they can email to someone within our organization.
I want the URL displayed in the dialog box to also be placed onto the clipboard.
GetNetworkPath
Another solution I have found that isn't perfect in my opinion, but doesn't have the annoying security warnings is to use clip.exe from a w2k3 server.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo hello world | clip", 0, TRUE
Example with a multiline string as per question below :
Link1
Dim string
String = "text here" &chr(13)& "more text here"
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo " & String & " | clip", 0, TRUE
Using Microsoft's clip.exe is the closest to having a clean Windows XP system solution. However you don't have to call CMD.EXE to host it in order to use it. You can call it directly and write to its input stream in your script code. Once you close the input stream clip.exe will write the contents straight to the clipboard.
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine "Something One"
oIn.WriteLine "Something Two"
oIn.WriteLine "Something Three"
oIn.Close
If you need to wait for clip to be finished before your script can continue processing then add
' loop until we're finished working.
Do While oExec.Status = 0
WScript.Sleep 100
Loop
And don't forget to release your objects
Set oIn = Nothing
Set oExec = Nothing
The closest solution I have found so far is a method to use IE to get and set stuff on the clipboard. The problem with this solution is the user gets security warnings. I am tempted to move 'about:blank' to the local computer security zone so I don't get the warnings, but I am not sure what the security implications of that would be.
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate("about:blank")
objIE.document.parentwindow.clipboardData.SetData "text", "Hello This Is A Test"
objIE.Quit
http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1215.mspx
No security warnings, full let and get access:
'create a clipboard thing
Dim ClipBoard
Set Clipboard = New cClipBoard
ClipBoard.Clear
ClipBoard.Data = "Test"
Class cClipBoard
Private objHTML
Private Sub Class_Initialize
Set objHTML = CreateObject("htmlfile")
End Sub
Public Sub Clear()
objHTML.ParentWindow.ClipboardData.ClearData()
End Sub
Public Property Let Data(Value)
objHTML.ParentWindow.ClipboardData.SetData "Text" , Value
End Property
Public Property Get Data()
Data = objHTML.ParentWindow.ClipboardData.GetData("Text")
End Property
Private Sub Class_Terminate
Set objHTML = Nothing
End Sub
End Class
Example Usage.
' Create scripting object
Dim WShell, lRunUninstall
Set WShell = CreateObject("WScript.Shell")
WShell.sendkeys "^c"
WScript.Sleep 250
bWindowFound = WShell.AppActivate("Microsoft Excel")
WShell.sendkeys ClipBoard.Data
To avoid the security warnings associated with Internet Explorer and clipboard access, I would recommend you use the Word application object and its methods to put your data onto the clipboard. Of course you can only use this on a machine that has MS Word installed, but these days that's most of them. (*In spite of the fact that you asked for stuff on a 'clean' system :) *)
' Set what you want to put in the clipboard '
strMessage = "Imagine that, it works!"
' Declare an object for the word application '
Set objWord = CreateObject("Word.Application")
' Using the object '
With objWord
.Visible = False ' Don't show word '
.Documents.Add ' Create a document '
.Selection.TypeText strMessage ' Put text into it '
.Selection.WholeStory ' Select everything in the doc '
.Selection.Copy ' Copy contents to clipboard '
.Quit False ' Close Word, don't save '
End With
You can find detail on the MS Word application object and its methods here: http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx
Microsoft doesn't give a way for VBScript to directly access the clipboard. If you do a search for 'clipboard'on this site you'll see:
Although Visual Basic for Applications supports the Screen, Printer, App, Debug, Err, and Clipboard objects, VBScript supports only the Err object. Therefore, VBScript does not allow you to access such useful objects as the mouse pointer or the clipboard. You can, however, use the Err object to provide runtime error handling for your applications.
So using notepad indirectly is probably about the best you'll be able to do with just VBScript.
Here's another version of using the "clip" command, which avoids adding a carriage return, line feed to the end of the string:
strA= "some character string"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /C echo . | set /p x=" & strA & "| c:\clip.exe", 2
s = "String: """ & strA & """ is on the clipboard."
Wscript.Echo s
I've only tested this in XP. clip.exe was downloaded from Link and placed in C:\.
I've found a way to copy multi line information to clipboard by vbscript/cmd.
Sequence:
with VBS generate the final "formatted string" that you need copy to clipboard
generate a (txt) file with the "formatted string"
use type command from cmd to paste information to clip by pipe
Example script:
Function CopyToClipboard( sInputString )
Dim oShell: Set oShell = CreateObject("WScript.Shell")
Dim sTempFolder: sTempFolder = oShell.ExpandEnvironmentStrings("%TEMP%")
Dim sFullFilePath: sFullFilePath = sTempFolder & "\" & "temp_file.txt"
Const iForWriting = 2, bCreateFile = True
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
With oFSO.OpenTextFile(sFullFilePath, iForWriting, bCreateFile)
.Write sInputString
.Close
End With
Const iHideWindow = 0, bWaitOnReturnTrue = True
Dim sCommand: sCommand = "CMD /C TYPE " & sFullFilePath & "|CLIP"
oShell.Run sCommand, iHideWindow, bWaitOnReturnTrue
Set oShell = Nothing
Set oFSO = Nothing
End Function
Sub Main
Call CopyToClipboard( "Text1" & vbNewLine & "Text2" )
End Sub
Call Main
The easiest way is to use built-in mshta.exe functionality:
sText = "Text Content"
CreateObject("WScript.Shell").Run "mshta.exe ""javascript:clipboardData.setData('text','" & Replace(Replace(sText, "\", "\\"), "'", "\'") & "');close();""", 0, True
To put to clipboard a string containing double quote char ", use the below code:
sText = "Text Content and double quote "" char"
CreateObject("WScript.Shell").Run "mshta.exe ""javascript:clipboardData.setData('text','" & Replace(Replace(Replace(sText, "\", "\\"), """", """"""), "'", "\'") & "'.replace('""""',String.fromCharCode(34)));close();""", 0, True
Take a look at this post. It describes a hacky approach to read from the clipboard, but I imagine it could be adapted to also write to the clipboard as well, such as changing the Ctrl+V to Ctrl+A then Ctrl+C.
I devised another way to use IE and yet avoid security warnings...
By the way.. this function is in JavaScript.. but u can easily convert it to VBScript..
function CopyText(sTxt) {
var oIe = WScript.CreateObject('InternetExplorer.Application');
oIe.silent = true;
oIe.Navigate('about:blank');
while(oIe.ReadyState!=4) WScript.Sleep(20);
while(oIe.document.readyState!='complete') WSript.Sleep(20);
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>";
var oTb = oIe.document.getElementById('txtArea');
oTb.value = sTxt;
oTb.select();
oTb = null;
oIe.ExecWB(12,0);
oIe.Quit();
oIe = null;
}
Here is Srikanth's method translated into vbs
function SetClipBoard(sTxt)
Set oIe = WScript.CreateObject("InternetExplorer.Application")
oIe.silent = true
oIe.Navigate("about:blank")
do while oIe.ReadyState <> 4
WScript.Sleep 20
loop
do while oIe.document.readyState <> "complete"
WScript.Sleep 20
loop
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>"
set oTb = oIe.document.getElementById("txtArea")
oTb.value = sTxt
oTb.select
set oTb = nothing
oIe.ExecWB 12,0
oIe.Quit
Set oIe = nothing
End function
function GetClipBoard()
set oIe = WScript.CreateObject("InternetExplorer.Application")
oIe.silent = true
oIe.Navigate("about:blank")
do while oIe.ReadyState <> 4
WScript.Sleep 20
loop
do while oIe.document.readyState <> "complete"
WScript.Sleep 20
loop
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>"
set oTb = oIe.document.getElementById("txtArea")
oTb.focus
oIe.ExecWB 13,0
GetClipBoard = oTb.value
oTb.select
set oTb = nothing
oIe.Quit
Set oIe = nothing
End function
In your Class ClipBoard, neither the Clear sub nor the Let Data sub work. I mean they have no effect on Windows Clipboard. Actually, and ironically so, the only sub that works is the one you have not included in your example, that is Get Data! (I have tested this code quite a few times.)
However, it's not your fault. I have tried to copy data to clipboard with ClipboardData.SetData and it's impossible. At least not by creating an "htmlfile" object. Maybe it works by creating an instance of "InternetExplorer.Application" as I have seen in a few cases, but I have not tried it. I hate creating application instances for such simple tasks!
Alkis
If it's just text can't you simply create a text file and read in the contents when you need it?
Another alternative and clearly a kludge, would be to use the SendKeys() method.
No security warnings and no carriage return at the end of line
' value to put in Clipboard
mavaleur = "YEAH"
' current Dir
path = WScript.ScriptFullName
GetPath = Left(path, InStrRev(path, "\"))
' Put the value in a file
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile=GetPath & "fichier.valeur"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write mavaleur
objFile.Close
' Put the file in the Clipboard
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c clip < " & outFile, 0, TRUE
' Erase the file
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile outFile

Resources