VBScript: Getting desktop shortcuts to perform special actions - vbscript

Truth: I am completely new to this scripting thing and have reached an end-pass. I am trying to write a script that will not only create a shortcut on the user's desktop, but when the user clicks on the icon, I want them to be asked if they really want to shut down the computer and given the option to cancel the shutdown or proceed with the shutdown. So far I have searched to the end of my textbook and google. I can achieve creating an icon and having it perform a Windows native shutdown but not with my special intervening actions. I just don't know how to make the icon call back into the script for the select case routine... Sorry if it is a bit messy See below:
result = MsgBox ("Would you really like to Shutdown?", vbYesNo, "Shutdown?")
Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
' Add Shutdown link to the desktop
Set linkShutdown = Shell.CreateShortcut(DesktopPath & "\Shutdown.lnk")
linkShutdown.Description = "Shutdown the computer"
linkShutdown.IconLocation = ("%SystemRoot%\system32\SHELL32.dll,27")
linkShutdown.TargetPath = "shutdown"
linkShutdown.WindowStyle = 1
linkShutdown.WorkingDirectory = "%windir%"
linkShutdown.Save
Select Case result
Case vbYes
MsgBox("Shutting down ...")
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 0"
Case vbNo
MsgBox("Ok")
End Select

Try this Vbscript : Ask2Shutdown.vbs
Option Explicit
Dim MyScriptPath
MyScriptPath = WScript.ScriptFullName
Call Shortcut(MyScriptPath,"Shutdown the computer")
Call AskQuestion()
'**********************************************************************************************
Sub Shortcut(PathApplication,Name)
Dim objShell,DesktopPath,objShortCut,MyTab
Set objShell = CreateObject("WScript.Shell")
MyTab = Split(PathApplication,"\")
If Name = "" Then
Name = MyTab(UBound(MyTab))
End if
DesktopPath = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(DesktopPath & "\" & Name & ".lnk")
objShortCut.TargetPath = Dblquote(PathApplication)
ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,-28"
objShortCut.Save
End Sub
'**********************************************************************************************
Sub AskQuestion()
Dim Question,Msg,Title
Title = "Shutdown the computer"
Msg = "Are you sure to shutdown the computer now ?"& Vbcr &_
"If yes, then click [YES] button "& Vbcr &_
"If not, then click [NO] button"
Question = MsgBox (Msg,VbYesNo+VbQuestion,Title)
If Question = VbYes then
Call Run_Shutdown(30)
else
WScript.Quit()
End if
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
Sub Run_Shutdown(N)
Dim ws,Command,Execution
Set ws = CreateObject("wscript.Shell")
Command = "Cmd /c Shutdown -s -t "& N &" -c "& DblQuote("Save your work because your PC will shut down in "& N &" seconds")
Execution = ws.run(Command,0,True)
End sub
'**********************************************************************************************

Set x = CreateObject("Shell.Application")
x.ShutdownWindows
Gives you the Windows' Shutdown dialog.
You have two scripts in one file that you run sequentally. Put them into two files.

Related

How to close a specific folder with VBScript?

I am trying to make a simple program with VBScript that closes a specific folder every time it gets opened, thus denying access to that folder. I've successfully used this code right here for many folders, but for some reason it doesn't work with C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp.
Do
WindowTitle = "FOLDERNAME"
Set shell = CreateObject("WScript.Shell")
success = shell.AppActivate(WindowTitle)
If success Then shell.SendKeys "%{F4}"
Loop
Is there any way that I can deny access to that specific folder using .vbs files?
You can try like this :
myfolder = "C:\temp"
Set sh = CreateObject("shell.application")
For Each w In sh.Windows
If w.document.folder.self.Path = myfolder Then w.Quit
Next
And here is a complete example to close your temporary folder :
Option Explicit
If AppPrevInstance() Then
MsgBox "There is an existing proceeding !" & VbCrLF &_
CommandLineLike(WScript.ScriptName),VbExclamation,"There is an existing proceeding !"
WScript.Quit
Else
Dim MyFolder,ws
Set ws = CreateObject("wscript.shell")
Myfolder = ws.ExpandEnvironmentStrings("%temp%")
Do
Call CloseThis(MyFolder)
wscript.sleep 1000
Loop
End If
'*********************************************************************************************
Sub CloseThis(Folder)
Dim sh,w
Set sh = CreateObject("shell.application")
For Each w In sh.Windows
If w.document.folder.self.Path = Folder Then w.Quit
Next
End Sub
'*********************************************************************************************
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'*********************************************************************************************
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'*********************************************************************************************

Launching application using VBScript

I am trying to launch an application from the Windows shell using VBScript. The application runs without errors when run from QtCreator. However, it crashes when run from VBScript and exits with error code 255.
Here's the script:
Set objShell = WScript.CreateObject("WScript.Shell")
rv = objShell.Run("path\to\application.exe", 1 , True)
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
WScript.Sleep 120000
objShell.Run "taskkill /im path\to\application.exe"
Set objShell = Nothing
Could someone please point out what I am missing?
Give a try for this vbscript and tell me the result :
Option Explicit
Dim Title,objShell,rv,ProcessPath,ProcessName
Title = "Launching and killing application using Vbcript"
Set objShell = CreateObject("WScript.Shell")
ProcessPath = "C:\Windows\system32\Calc.exe"
rv = objShell.Run(DblQuote(ProcessPath),1,False)
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
Set objShell = Nothing
WScript.Sleep 12000
ProcessPath = Split(ProcessPath,"\")
ProcessName = ProcessPath(UBound(ProcessPath))
Msgbox "The Process named "& DblQuote(ProcessName) &" is being to be killed now !",_
vbExclamation,Title
Call Kill(ProcessName)
'****************************************************
Sub Kill(ProcessName)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "& DblQuote(ProcessName) &""
Execution = Ws.Run(Command,0,True)
Set Ws = Nothing
End Sub
'****************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************
Try This way :
Set objShell = WScript.CreateObject("WScript.Shell")
rv = objShell.Run(chr(34)&"c:\windows\system32\Mspaint.exe"&chr(34), 1 , False)
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
WScript.Sleep 2000
objShell.Run "taskkill /f /im ""Mspaint.exe"" ",0,False
Set objShell = Nothing
I was able to find the error. I set the current directory to the folder that contains the .exe file.This is the modified script:
Option Explicit
Dim Title,objShell,rv,ProcessPath,ProcessName
Title = "Launching and killing application using Vbcript"
Set objShell = CreateObject("WScript.Shell")
objShell.CurrentDirectory = "path\to\folder\containing\.exe"
ProcessPath = "path\to\application.exe"
objShell.Run DblQuote(ProcessPath),1,False
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
Set objShell = Nothing
WScript.Sleep 12000
ProcessPath = Split(ProcessPath,"\")
ProcessName = ProcessPath(UBound(ProcessPath))
Msgbox "The Process named "& DblQuote(ProcessName) &" is being to be killed now !",_
vbExclamation,Title
Call Kill(ProcessName)
Sub Kill(ProcessName)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "& DblQuote(ProcessName) &""
Execution = Ws.Run(Command,0,True)
Set Ws = Nothing
End Sub
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function

Can anyone help me close this program in VBScript?

MsgBox ("Do you want to start the autoclicker?", vbOkOnly, "Autoclicker")
CreateObject("WScript.Shell").Run("""C:\Users\Henry\Desktop\Fun.vbs""")
MsgBox ("Do you want to stop the autoclicker?", vbOkOnly, "Autoclicker")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.ProcessID & " " & objItem.CommandLine
If objItem.name = "Calculator.exe" then objItem.terminate
Next
This kills calculator.exe. Change it to wscript.exe. You might want to check command line if you just want to kill fun.vbs.
The following routine kills all processes whose command lines contain a specified string. The 3 lines below the routine are for testing it. We pause the routine by showing a message box and when you dismiss the message box, we kill the script instance, so the second message box doesn't show up. When you use it, you want to replace the last 3 lines with
KillProcesses "Fun.vbs"
I'd be careful using this and specify as much of the command line as possible to make sure I absolutely, positively match only the processes I want to terminate. You can modify the Task Manager and add a column to show the command line for every running process. In the routine below, the search in command line is case-insensitive.
Option Explicit
Sub KillProcesses(strPartOfCommandLine)
Dim colProcesses
Dim objProcess
Dim lReturn
' Get list of running processes using WMI
Set colProcesses = GetObject("winmgmts:\\.\root\cimv2").ExecQuery("Select * From Win32_Process")
For Each objProcess in colProcesses
If (Instr(1, objProcess.Commandline, strPartOfCommandLine, vbTextCompare) <> 0) Then
lReturn = objProcess.Terminate(0)
End If
Next
End Sub
Msgbox "Before being killed"
KillProcesses "KillProcesses.vbs"
Msgbox "After being killed"
I made before a script that ask you what vbscript did you want to kill and log the result into file.
So just, give a try :
Option Explicit
Dim Titre,Copyright,fso,ws,NomFichierLog,temp,PathNomFichierLog,OutPut,Count,strComputer
Copyright = "[© Hackoo © 2014 ]"
Titre = " Process "& DblQuote("Wscript.exe") &" running "
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject( "Wscript.Shell" )
NomFichierLog="Process_WScript.txt"
temp = ws.ExpandEnvironmentStrings("%temp%")
PathNomFichierLog = temp & "\" & NomFichierLog
Set OutPut = fso.CreateTextFile(temp & "\" & NomFichierLog,1)
Count = 0
strComputer = "."
Call Find("wscript.exe")
Call Explorer(PathNomFichierLog)
'***************************************************************************************************
Function Explorer(File)
Dim ws
Set ws = CreateObject("wscript.shell")
ws.run "Explorer "& File & "\",1,True
end Function
'***************************************************************************************************
Sub Find(MyProcess)
Dim colItems,objItem,Processus,Question
Set colItems = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process " _
& "Where Name like '%"& MyProcess &"%' AND NOT commandline like '%" & wsh.scriptname & "%'",,48)
For Each objItem in colItems
Count= Count + 1
Processus = Mid(objItem.CommandLine,InStr(objItem.CommandLine,""" """) + 2) 'Extraction of the commandline script path
Processus = Replace(Processus,chr(34),"")
Question = MsgBox ("Did you want to stop this script : "& DblQuote(Processus) &" ?" ,VBYesNO+VbQuestion,Titre+Copyright)
If Question = VbYes then
objItem.Terminate(0)'Kill this process
OutPut.WriteLine DblQuote(Processus)
else
Count= Count - 1 'decrement the counter -1
End if
Next
OutPut.WriteLine String(100,"*")
OutPut.WriteLine count & Titre & " were stopped !"
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

VBSript Shutdown Message Confusion

I am currently learning how to write commands in Visual Basic and decided to make a simple shutdown message. The code worked perfectly: when the user clicked 'yes' it shutdown and 'no', 'cancel' and the 'X' button closed the message.
However, I decided to try a make a prank message aswell, where the computer would shutdown whatever option was chosen. I ran the script, however when I clicked the 'X' icon (I did not fancy the idea of shutting down my computer!), my computer shutdown anyway :(
Is there a way to stop this happening, or, even better, is there a way to grey out the 'X' icon so the user cannot close the message?
Here is the code:
Option Explicit
Dim result
result = MsgBox ("Do you want to shutdown?", 3+48,"Warning")
Dim objShell
Select Case result
Case vbYes
MsgBox("shuting down ...")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 20"
Case vbNo
MsgBox("shuting down ...")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 20"
Case vbCancel
MsgBox("shuting down ...")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 20"
End Select
Cheers in advance! :D
-r : for reboot
-s : for shutdown
This Vbscript can create a shortcut on your desktop asking you if you want to shutdown the computer or not.
Option Explicit
Dim MyScriptPath
MyScriptPath = WScript.ScriptFullName
Call Shortcut(MyScriptPath,"Shutdown the computer")
Call AskQuestion()
'**********************************************************************************************
Sub Shortcut(PathApplication,Name)
Dim objShell,DesktopPath,objShortCut,MyTab
Set objShell = CreateObject("WScript.Shell")
MyTab = Split(PathApplication,"\")
If Name = "" Then
Name = MyTab(UBound(MyTab))
End if
DesktopPath = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(DesktopPath & "\" & Name & ".lnk")
objShortCut.TargetPath = Dblquote(PathApplication)
ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,-28"
objShortCut.Save
End Sub
'**********************************************************************************************
Sub AskQuestion()
Dim Question,Msg,Title
Title = "Shutdown the computer"
Msg = "Are you sure to shutdown the computer now ?"& Vbcr &_
"If yes, then click [YES] button "& Vbcr &_
"If not, then click [NO] button"
Question = MsgBox (Msg,VbYesNo+VbQuestion,Title)
If Question = VbYes then
Call Run_Shutdown(30)
else
WScript.Quit()
End if
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
Sub Run_Shutdown(N)
Dim ws,Command,Execution
Set ws = CreateObject("wscript.Shell")
Command = "Cmd /c Shutdown -s -t "& N &" -c "& DblQuote("Save your work because your PC will shut down in "& N &" seconds")
Execution = ws.run(Command,0,True)
End sub
'**********************************************************************************************
Ok, is there a reason for trying to remove/disable the X? I ask because it will be kinda difficult though it can be done.
Not all button combinations on the msgbox enable the X. Try vbAbortRetryIgnore and also try vbYesNo.
If a Cancel button is provided (all other combinations except vbOkOnly) then X is enabled
If only one button is displayed then X is enabled
This really makes it almost pointless to disable the button once you are aware of these things. Here's what happens when the above scenarios are displayed an user hits X vs clicking on a button
N/A. X button not enabled
MsgBox returns vbCancel
MsgBox returns value of only button
By the way, it is not just clicking X. When X is enabled, ESC will trigger same results.

Create a shortcut on the desktop that prompts before shutdown

I need to create a shortcut in which I can be prompted if I would like to shut down windows (Action to shutdown when clicking ok). Any ideas?
So far the working shutdown shortcut that I have does not issue the prompt a message asking if I truly want to shutdown or cancel the shortcut request.
Here it is:
Dim shellApp, answer
'Creates Shortcut with a Path to the desktop.
Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
'Establishes and names the shortcut "Shutdown".
Set linkShutdown = Shell.CreateShortcut(DesktopPath & "\Shutdown.lnk")
'Adds shutdown code to the shortcut.
linkShutdown.Arguments = "-s -t 01"
'Adds Description to shortcut that displays message on link over.
linkShutdown.Description = "Shutdown this Computer"
'Creates Icon for shortcut using system shutdown icon.
linkShutdown.IconLocation = ("%SystemRoot%\system32\SHELL32.dll,27")
'Retrieves shutdown target path for shortcut.
linkShutdown.TargetPath = "shutdown"
'Saves the Script.
linkShutdown.Save
'Prompts the user if they want to shutdown their computer,
'displays ok and cancel buttons for the user to choose.
Set shellApp = CreateObject("Shell.Application")
answer = MsgBox("Do you really want to shut down the computer?", 1, _
"Turn off Computer Script!")
If answer = 1 then
Initiate_Logoff()
End if
'Function that shuts computer down.
Function Initiate_Logoff()
'Adds shutdown code to the shortcut.
End Function
Try this code :
Option Explicit
Dim MyScriptPath
MyScriptPath = WScript.ScriptFullName
Call Shortcut(MyScriptPath,"Shutdown the computer")
Call AskQuestion()
'**********************************************************************************************
Sub Shortcut(PathApplication,Name)
Dim objShell,DesktopPath,objShortCut,MyTab
Set objShell = CreateObject("WScript.Shell")
MyTab = Split(PathApplication,"\")
If Name = "" Then
Name = MyTab(UBound(MyTab))
End if
DesktopPath = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(DesktopPath & "\" & Name & ".lnk")
objShortCut.TargetPath = Dblquote(PathApplication)
ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,-28"
objShortCut.Save
End Sub
'**********************************************************************************************
Sub AskQuestion()
Dim Question,Msg,Title
Title = "Shutdown the computer"
Msg = "Are you sure to shutdown the computer now ?"& Vbcr &_
"If yes, then click [YES] button "& Vbcr &_
"If not, then click [NO] button"
Question = MsgBox (Msg,VbYesNo+VbQuestion,Title)
If Question = VbYes then
Call Run_Shutdown(30)
else
WScript.Quit()
End if
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
Sub Run_Shutdown(N)
Dim ws,Command,Execution
Set ws = CreateObject("wscript.Shell")
Command = "Cmd /c Shutdown -s -t "& N &" -c "& DblQuote("Save your work because your PC will shut down in "& N &" seconds")
Execution = ws.run(Command,0,True)
End sub
'**********************************************************************************************

Resources