Manually we right click on a file and select the "open with" option to open in other format.
Now i need to do this through vbscript
To open a file using a specific application, use the WshShell.Run methood to run that application and pass the file name as a parameter.
Here's an example that opens the same text file in Notepad, Internet Explorer and Microsoft Word:
strFileName = "c:\myfile.txt"
Set oShell = CreateObject("WScript.Shell")
oShell.Run "notepad " & strFileName
oShell.Run "iexplore " & strFileName
oShell.Run "winword " & strFileName
Note that if the file name includes spaces, you need to enslose it in quotes, like this:
oShell.Run "winword ""c:\my file.txt"""
If you want to create an association script with VBScript, for example when you write click on a file and open it with certain program, you can use this script I had created way back:
'Run Script
InsertContextMenu
Sub InsertContextMenu ()
Dim sText
Dim sExePath
'For executable-only context menu, the key should be created here
'HKEY_CLASSES_ROOT\exefile\shell
sText = InputBox ("Enter the Text for the context menu." & vbNewLine & vbNewLine & "Example" & vbNewLine & "Open with Notepad")
If Len(Trim(sText)) > 0 Then
sExePath = InputBox ("Enter the path of the executable file for the context menu." & vbNewLine & vbNewLine & "Example" & vbNewLine & "C:\Windows\Notepad.exe")
If Len(Trim(sExePath)) > 0 Then
Set SHL = CreateObject ("WScript.Shell")
SHL.RegWrite "HKCR\*\Shell\" & sText & "\",sText
SHL.RegWrite "HKCR\*\Shell\" & sText & "\Command\", sExePath & " %1"
If Len(SHL.RegRead ("HKCR\*\Shell\" & sText & "\Command\")) > 0 Then
MsgBox "The Context Menu successfully created !.",vbInformation
Else
MsgBox "An unknown error has occured !!",vbCritical
End If
End If
End If
Set SHL = Nothing
End Sub
Just copy above code, and paste into a file and give that file .vbs extension.
Related
I'm trying to deploy an application through SCCM 2012 for Windows7 (x86 and x64) that requires to notify the user that his Microsoft Outlook should be closed before to continue with the installation. It could be either with a Timer or a (Yes / No) choice, then if the user press Yes then it will close Outlook and will continue with the installation otherwise it will send a log file saying the the user cancelled the installation but it can be retried at any time.
So far I just have the installation script that works only to install the applications using a command line script. So, it will just execute some MSI's installations and Windows updates, and then it quits.
The script I have that creates the pop up and that can be called by my CMD file is the following VBScript and was taken from a TechNet article.
Const TIMEOUT = 7
Set objShell = WScript.CreateObject("WScript.Shell")
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
strPath = Wscript.FullName
strFileVersion = objFS.GetFileVersion(strPath)
iRetVal = objShell.Popup(Wscript.FullName & vbCrLf & _
"File Version: " & _
strFileVersion & vbCrLf & _
"Would you like to close Outlook application and continue with the installation?" _
,TIMEOUT,"Outlook Validation",vbYesNo + vbQuestion)
Select Case iRetVal
Case vbYes
Set objFile = objFS.GetFile(strPath)
objShell.Popup WScript.FullName & vbCrLf & vbCrLf & _
"File Version: " & strFileVersion & vbCrLf & _
"File Size: " & Round((objFile.Size/1024),2) & _
" KB" & vbCrLf & _
"Date Created: " & objFile.DateCreated & vbCrLf & _
"Date Last Modified: " & objFile.DateLastModified & _
vbCrLf,TIMEOUT
Wscript.Quit
Case vbNo
Wscript.Quit
Case -1
WScript.StdOut.WriteLine "Popup timed out."
Wscript.Quit
End Select
So I don't know if there's any useful example that I can use and customize it from there. I'm clueless, blindfolded, I don't see the light. Well you understand my frustration.
Any ideas, examples or links will be really appreciated!!
Thanks & kind regards.
Joel.
This is one way.
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.name & " " & objItem.CommandLine
If LCase(objItem.name) = "outlook.exe" then
If Msgbox("Close Outlook", 33, "Install") = 1 then
objItem.terminate
End If
End If
Next
VBScript's Help file - https://www.microsoft.com/en-au/download/details.aspx?id=2764
For help with the WMI object use wmic at the command prompt.
wmic process get /? (same as wmic path win32_process get /?) and wmic process call /? list properties and methods.
Here my procedure which closes outlook before modifying the profile.
Is is part of a logon script. The show is a logging and informing procedure.
sub CloseOutlook
on error resume next 'to be able to log and continue
dim objWMIService, colProcessList, objProcess, sResult, oShell
set oShell = WScript.CreateObject("WScript.Shell")
set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'OUTLOOK.EXE'")
for Each objProcess in colProcessList
show "outlook is being closed"
objProcess.Terminate()
if Err <> 0 then
show "Error while closing outlook: " & err.Description
end if
sResult = oShell.Popup("Outlook is being closed, profile is configured")
next
end sub
If you want confirmation from the user you will have to use a MsgBox instead.
I'd recommend not faffing about with warnings and closing Outlook, but instead configure the advert to run when no users are logged in. Less chance for problems or accidentally miss-clicked "oh no you lost my emails" situations.
I'm trying to update the legal caption on our PCs using a VBScript. So far, I've been able to read values but I can't seem to get it to write any values. I don't get an error when I run the script, it just doesn't change anything. It's the first time I'm doing this and I have limited experience; any insight would be appreciated:
Dim objShell
Dim strMessage, strWelcome, strWinLogon
' Set the string values
strWelcome = "legalnoticecaption"
strMessage = "did this work"
strWinLogon = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
' Create the Shell object
Set wshShell = CreateObject("WScript.Shell")
'Display string Values
Wscript.Echo "key to update: " & strWelcome
Wscript.Echo "key value to enter: " & strMessage
Wscript.Echo "Existing key value: " & wshShell.RegRead(strWinLogon & strWelcome)
' the crucial command in this script - rewrite the registry
wshShell.RegWrite strWinLogon & strWelcome, strMessage, "REG_SZ"
' Did it work?
Wscript.Echo "new key value: " & wshShell.RegRead(strWinLogon & strWelcome)
set wshShell = Nothing
NOTE: These are testing values at the moment.
Your script seems to be bug-less. However, launched by cscript 28416995.vbs returns next error (where 22 = WshShell.RegWrite line):
28416995.vbs(22, 1) WshShell.RegWrite: Invalid root in registry key "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\legalnoticecaption".
It's not invalid root, it's something like access denied rather because writing to HKLM requires elevated privileges (or run as administrator).
Note:
You should change LegalNoticeText value together with LegalNoticeCaption one.
Under the HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\ registry key there both values reside as well. For this case (if a computer is not connected to a domain or with group policy disabled) should work next script.
Run as administrator:
option explicit
On Error Goto 0
Dim wshShell
Dim strResult, strMessage, strWelcome, strWinLogon, strWinLog_2, strWinLTxt
strResult=Wscript.ScriptName
' Set the string values
strWinLTxt = "legalnoticetext"
strWelcome = "legalnoticecaption"
strMessage = "did this work"
strWinLogon = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\"
strWinLog_2 = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
' Create the Shell object
Set wshShell = CreateObject("WScript.Shell")
'Display string Values
' continue execution if requested registry values not present
On Error Resume Next
strResult = strResult & vbNewLine & "Existing Caption Policies: " _
& wshShell.RegRead(strWinLog_2 & strWelcome)
strResult = strResult & vbNewLine & "Existing Text Policies: " _
& wshShell.RegRead(strWinLog_2 & strWinLTxt)
On Error Goto 0
strResult = strResult & vbNewLine & "Existing Caption Winlogon: " _
& wshShell.RegRead(strWinLogon & strWelcome)
strResult = strResult & vbNewLine & "Existing Text Winlogon: " _
& wshShell.RegRead(strWinLogon & strWinLTxt)
strResult = strResult & vbNewLine
strResult = strResult & vbNewLine & "key to update: " & strWelcome
strResult = strResult & vbNewLine & "key value to enter: " & strMessage
' the crucial command in this script - rewrite the registry
wshShell.RegWrite strWinLogon & strWelcome, strMessage, "REG_SZ"
wshShell.RegWrite strWinLogon & strWinLTxt, UCase( strMessage), "REG_SZ"
' Did it work?
strResult = strResult & vbNewLine
strResult = strResult & vbNewLine _
& "new key Capt. value: " & wshShell.RegRead(strWinLogon & strWelcome)
strResult = strResult & vbNewLine _
& "new key Text value: " & wshShell.RegRead(strWinLogon & strWinLTxt)
Wscript.Echo strResult
set wshShell = Nothing
For me your code run perfect.
For other user that want details over this i recommend this site: http://ss64.com/vb/regread.html and ss64.com/vb/regwrite.html
Both links detail exactly the procedure that you create.
Make sure to add this:
Function RunAsAdmin()
If WScript.Arguments.length = 0 Then
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" & " RunAsAdministrator",,"runas", 1
WScript.Quit
End If
End Function
It will run as Admin and if it doesnt work then your key is incorrect.
I am Using below code to open autocad file :
Dim DwgName As String
On Error Resume Next
Set acadApp = GetObject(, "AutoCAD.Application")
If Err Then
Set acadApp = CreateObject("AutoCAD .Application")
Err.Clear
End If
Set acadDoc = acadApp.ActiveDocument
If acadDoc.FullName <> DwgName Then
acadDoc.Open DwgName
End If
Dim str As String, str1 As String
str1 = "_-insert" & vbLf & """" & "C:\AZ665.dwg" & """" & vbLf & "0,0,0" & vbLf & vbLf & vbLf & vbLf & "z" & vbLf & "a" & vbLf
acadDoc.SendCommand str1
acadApp.Visible = True
Above code working fine.But everytime I have to create "str1" string in order to make any changes. Hence I am writting scipt in ".scr" file.But unable to call this file.
Please help.
The following code will read a .scr file and create the string you need for your SendCommand
Dim strData as string
x = FreeFile
Open "myscript.scr" For Input As #x
Do
Line Input #x, strData
str1 = str1 & strData & vbNewLine
If EOF(x) Then Exit Do
Loop
Close #x
I found below solution :
acadDoc.SendCommand "_script" & vbCr & ScriptFilePath & vbCr
I need some excel vba examples, where with in the VBA code(Excel Macro) i could call a VBScript and will get some values like filename and directory information from the vbscript and assign it to the variables in VBA code.
Thank you in advance
Some thing like this
VBA macro:
Sub Foo2Script
Dim x As Long
x=2
'Call VBscript here
MsgBox scriptresult
End Sub
VBScript:
Dim x, y ,Z
x = x_from_macro
y = x + 2
Z = X+Y
scriptresult = y,Z
It can be done but I would have to agree with Tomalak and others that it's not the best way to go. However, saying that, VBScript can work wonders occasionally if you use it as a kind of fire and forget mechanism. It can be used quite effectively to simulate multi-threading in VBA whereby you breakdown the payload and farm it out to individual VBScripts to run independently. Eg you could arrange a "swarm" of individual VBScripts to mass download from websites in the background whilst VBA continues with other code.
Below is some VBA code I've simplified to show what can be done and writes a simple VBScript on the fly. Normally I prefer to run it using 'wshShell.Run """" & SFilename & """" which means I can forget about it but I've included in this example this method Set proc = wshShell.exec(strexec) which allows a test of the object for completion
Put this in MODULE1
Option Explicit
Public path As String
Sub writeVBScript()
Dim s As String, SFilename As String
Dim intFileNum As Integer, wshShell As Object, proc As Object
Dim test1 As String
Dim test2 As String
test1 = "VBScriptMsg - Test1 is this variable"
test2 = "VBScriptMsg - Test2 is that variable"
'write VBScript (Writes to Excel Sheet1!A1 & Calls Function Module1.ReturnVBScript)
s = s & "Set objExcel = GetObject( , ""Excel.Application"") " & vbCrLf
s = s & "Set objWorkbook = objExcel.Workbooks(""" & ThisWorkbook.Name & """)" & vbCrLf
s = s & "Set oShell = CreateObject(""WScript.Shell"")" & vbCrLf
s = s & "Msgbox (""" & test1 & """)" & vbCrLf
s = s & "Msgbox (""" & test2 & """)" & vbCrLf
s = s & "Set oFSO = CreateObject(""Scripting.FileSystemObject"")" & vbCrLf
s = s & "oShell.CurrentDirectory = oFSO.GetParentFolderName(Wscript.ScriptFullName)" & vbCrLf
s = s & "objWorkbook.sheets(""Sheet1"").Range(""" & "A1" & """) = oShell.CurrentDirectory" & vbCrLf
s = s & "Set objWMI = objWorkbook.Application.Run(""Module1.ReturnVBScript"", """" & oShell.CurrentDirectory & """") " & vbCrLf
s = s & "msgbox(""VBScriptMsg - "" & oShell.CurrentDirectory)" & vbCrLf
Debug.Print s
' Write VBScript file to disk
SFilename = ActiveWorkbook.path & "\TestVBScript.vbs"
intFileNum = FreeFile
Open SFilename For Output As intFileNum
Print #intFileNum, s
Close intFileNum
DoEvents
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
Set proc = wshShell.exec("cscript " & SFilename & "") ' run VBScript
'could also send some variable
'Set proc = wsh.Exec("cscript VBScript.vbs var1 var2") 'run VBScript passing variables
'Wait for script to end
Do While proc.Status = 0
DoEvents
Loop
MsgBox ("This is in Excel: " & Sheet1.Range("A1"))
MsgBox ("This passed from VBScript: " & path)
'wshShell.Run """" & SFilename & """"
Kill ActiveWorkbook.path & "\TestVBScript.vbs"
End Sub
Public Function ReturnVBScript(strText As String)
path = strText
End Function
This demonstrated several ways that variables can be passed around.
Below is the VBScript code. If the file/s or folder exist I get scripting error, "File already exists".
How to fix that?
How to create folder only if it does not exist and copy files only that are new or do not exist in source path?
How to insert the username (Point 1) after "Welcome" and at (Poin 3) instead of user cancelled?
Can the buttons be changed to Copy,Update,Cancel instead of Yes,No,Cancel? (Point 2)
The code:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
Message = " Welcome to the AVG Update Module" & vbCR '1*
Message = Message & " *****************************" & vbCR & vbCR
Message = Message & " Click Yes to Copy Definition Files" & vbCR & vbCR
Message = Message & " OR " & vbCR & vbCR
Message = Message & " Click No to Update Definition Files." & vbCR & vbCR
Message = Message & " Click Cancel (ESC) to Exit." & vbCR & vbCR
X = MsgBox(Message, vbYesNoCancel, "AVG Update Module") '2*
'Yes Selected Script
If X = 6 then
objFSO.FolderExists("E:\Updates")
if TRUE then objFSO.CreateFolder ("E:\Updates")
objFSO.CopyFile "c:\Docume~1\alluse~1\applic~1\avg8\update\download\*.*",
"E:\Updates\" , OverwriteFiles
MsgBox "Files Copied Succesfully.", vbInformation, "Copy Success"
End If
'No Selected Script
If X = 7 then
objFSO.FolderExists("Updates")
if TRUE then objFSO.CreateFolder("Updates")
objFSO.CopyFile "E:\Updates\*.*", "Updates", OverwriteFiles
Message = "Files Updated Successfully." & vbCR & vbCR
Message = Message & "Click OK to Launch AVG GUI." & vbCR & vbCR
Message = Message & "Click Cancel (ESC) to Exit." & vbCR & vbCR
Y = MsgBox(Message, vbOKCancel, "Update Success")
If Y = 1 then
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Progra~1\avg\avg8\avgui.exe" & Chr(34), 0
Set WshShell = Nothing
End if
If Y = 3 then WScript.Quit
End IF
'Cancel Selection Script
If X = 2 then
MsgBox "No Files have been Copied/Updated.", vbExclamation, "User Cancelled" '3*
End if
How to create folder only if it does not exist
This your code:
objFSO.FolderExists("E:\Updates")
if TRUE then objFSO.CreateFolder ("E:\Updates")
simply calls the FolderExists and CreateFolder methods in sequence (CreateFolder is always called because the if TRUE condition evaluates to True) and is equal to:
objFSO.FolderExists("E:\Updates")
objFSO.CreateFolder ("E:\Updates")
You want to call CreateFolder depending on the return value of the FolderExists method:
If Not objFSO.FolderExists("E:\Updates") Then
objFSO.CreateFolder "E:\Updates"
and copy files only that are new or do not exist in source path?
Neither VBScript nor the FileSystemObject object have this functionality. However, it is possible to call an external tool that can do that, such as xcopy, from your script using the WshShell.Run method. I guess you need something like this:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "xcopy c:\Docume~1\alluse~1\applic~1\avg8\update\download\*.* E:\Updates\ /D", , True
How to insert the username (Point 1)
Concatenate the message text with the strUserName variable value:
Message = " Welcome " & strUserName & " to the AVG Update Module" & vbCR
...
MsgBox "No Files have been Copied/Updated.", vbExclamation, strUserName & " Cancelled"
Can the buttons be changed to Copy,Update,Cancel Instead of Yes,No,Cancel?(Point 2)
No, VBScript's built-in MsgBox function does not support custom buttons. There're workarounds though: you could create your custom message box using an HTA (HTML application) or use the InputBox function to prompt the user for the task they wish to perform. You can find examples here.
I'd also like to note that you can improve your script by using the Select Case statement to check the MsgBox return value instead of multiple If...Then...End If statements. Also, it's a bad practice to use "magic numbers" like 6 or 7 - use the appropriate constants instead. For example:
Select Case X
Case vbYes
...
Case vbNo
...
Case Else ' vbCancel
...
End Select
When you say
"copy files only that are new or do
not exist in source path?"
do you mean you only want to copy files from the source directory to the destination directory if they do not exist in the destination? If so this will accomplish that
Const SourceFolder = "C:\Test1\"
Const DestinationFolder = "C:\Test2\"
Set fso = CreateObject("Scripting.FileSystemObject")
'Get a collection of al the files in the source directory
Set fileCol = fso.GetFolder(SourceFolder).Files
'Loop through each file and check to see if it exists in the destination directory
For Each objFile in fileCol
If NOT fso.FileExists(DestinationFolder & objFile.Name) Then
'If the file does not exist in the destination directory copy it there.
objFile.Copy DestinationFolder
Else
If objFile.DateLastModified > fso.GetFile(DestinationFolder & objFile.Name).DateLastModified Then
'If the file is newer than the destination file copy it there
objFile.Copy DestinationFolder, True
End If
End If
Next
Set fileCol = Nothing
Set fso = Nothing
Added the requested date check.