I need help with my first VBS script. Basically I want to check if outlook is open, if not I want to open the program, if/when it is open I want to send an email.
set service = GetObject ("winmgmts:")
for each Process in Service.InstancesOf ("Win32_Process")
If Process.Name = "outlook.exe"(
goto "send"
) else (
goto "Open"
)
End If
Open:
Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""C:\Program Files (x86)\Microsoft Office\Office16\OUTLOOK.EXE""")
Set objShell = Nothing
GOTO send
send:
wscript.Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Sign in- please reply!"
objMessage.Sender = "test#gmail.com"
objMessage.From = "test#gmail.com"
objMessage.To = "test#gmail.com"
objMessage.TextBody = Test Body Email
'==This section provides the configuration information for the remote SMTP server.
'==Normally you will only change the server name or IP.
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
'==End remote SMTP server configuration section==
objMessage.Send
exit
I do know my email part works as I can run that and send my email. I'm having issues with the "If, ELSE, THEN" statement.
If Process.Name = "outlook.exe" Then
send
Else
open
End If
Will be the correct format for If..Then..Else, but vbscript does not support GoTo statements. If you convert send and open to functions then you will be able to call them as shown above
Related
I'm not overly familiar with VBS and not sure how to best approach this.
I've got this basic code to work whereby when a value from a machine >= 100 it send out an email. The WinCC triggers this script whenever the tag value changes.
Now, I want to utilise this on a number of other values to monitor parts of machinery and equipment and send out some email alerts.
But, is there any need to replicate the whole email settings code in every script or is there a way that the triggered code can call a global script with the email settings in?
So instead of "Triggered VBS - Check Value - If True - Here's email details - Send Email"
Its more like "Triggered VBS - Check Value - If True - Load Email Setting VBS - Send Email"
Hope that makes sense?
Option Explicit
Function action
Dim TagVari1
Dim TagVari2
Set TagVari1 = HMIRuntime.Tags("TestTag1")
TagVari1.Read
TagVari1.Value = TagVari1.Value +1
Set TagVari2 = HMIRuntime.Tags("TestTag2")
TagVari2.Read
TagVari2.Value = TagVari1.Value
TagVari2.Write
If TagVari2.Value >= 100 Then
Dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.mydomain.com"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = "my.email#mydomain.com"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = "30"
objMessage.Configuration.Fields.Update
objMessage.Subject = "WinCC Message"
objMessage.From = "my.email#mydomain.com"
objMessage.To = "recip.email#outlook.com"
objMessage.TextBody = "This is a test message from WinCC......"
objMessage.Send
x=Msgbox("CHP Alarm" ,0, "Tag2 equal or over 100")
End If
End Function
Here's how to include another *.vbs, courtesy of Frank-Peter Schultze
Put this Sub in your main script(s):
'------------------------------------------------------------------------------
'Purpose : Include another VBScript file into the current one.
'Note : Usage: Include("vbsfile.vbs")
'
' Author: Frank-Peter Schultze
' Source: http://www.fpschultze.de/smartfaq+faq.faqid+51.htm
'------------------------------------------------------------------------------
Sub Include(ByVal strFilename)
Dim objFileSys, objFile, strContent
Set objFileSys = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSys.OpenTextFile(strFilename, 1)
strContent = objFile.ReadAll
objFile.Close
Set objFileSys = Nothing
ExecuteGlobal strContent
End Sub
'------------------------------------------------------------------------------
Have your email send routine in another script, e.g. MySendMail.vbs
And then somewhere at the start of your main script call it like
Include("Full\Path\To\MySendMail.vbs")
And that's the one caveat: the included filename must be passed to the Sub with its full path including drive.
I'm trying to execute a a BAT file on a remote server using VBScript. Further requirements:
psexec is not allowed
I need the script to operate under the permissions of another user, not those of my own workstation
I have consulted this article: https://learn.microsoft.com/en-us/windows/desktop/WmiSdk/connecting-to-wmi-remotely-with-vbscript
I see how creating the connection works, but I can't figure out how to then create a process using that same connection.
I believe this solution is really close, the only problem is I think it impersonates the user of the computer it is currently running on:
strCommand = "C:\temp\copyall.bat"
strPath = "C:\temp"
strcomputer="."
process = "winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2"
msgbox process
Set objWMIService = GetObject(process)
Set objProcess = objWMIService.Get("Win32_Process")
errReturn = objProcess.Create(strCommand, strPath, Null, intProcessID)
If errReturn = 0 Then
WScript.Echo "scan success: " & intProcessID
Else
WScript.Echo "scan fail: " & errReturn
End If
This example from Microsoft's site shows how to create the connection properly but I don't know how to then use that connection.
' Full Computer Name
' can be found by right-clicking My Computer,
' then click Properties, then click the Computer Name tab)
' or use the computer's IP address
strComputer = "FullComputerName"
strDomain = "DOMAIN"
Wscript.StdOut.Write "Please enter your user name:"
strUser = Wscript.StdIn.ReadLine
Set objPassword = CreateObject("ScriptPW.Password")
Wscript.StdOut.Write "Please enter your password:"
strPassword = objPassword.GetPassword()
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer(strComputer, _
"Root\CIMv2", _
strUser, _
strPassword, _
"MS_409", _
"ntlmdomain:" + strDomain)
Set colSwbemObjectSet = objSWbemServices.ExecQuery("Select * From Win32_Process")
For Each objProcess in colSWbemObjectSet
Wscript.Echo "Process Name: " & objProcess.Name
Next
The answer is probably staring me in the face but I just can't see it right now. Ideas?
After connecting to the remote server simply get the Win32_Process object and call the Create() method like you'd do locally.
Set objSWbemServices = objSWbemLocator.ConnectServer(...)
Set objProcess = objSWbemServices.Get("Win32_Process")
errReturn = objProcess.Create(strCommand, strPath, Null, intProcessID)
The file you want to run must exist locally on the remote server for this to work.
Also note that this normally requires admin privileges on the remote system.
I search for a Script that pings a List of machines and if a IP has changed send a warning mail. Hope somebody can help me.
Greets Mohrjon
Is the ping sufficient information to know that the IP address has changed? - what if the network goes down for a short period of time whilst the script is running?
Anyhow these are three subs i have which i have bodged together which should do what you need
Firstly i would iterate through a text file (csv) to get my ip address, and in this case the name and email
Sub Open_Master_File()
Do While objTextFile.AtEndOfStream <> True
strLine = objTextFile.ReadLine
'skip if comment line found
If inStr(1,strLine, "'") Then
ElseIf inStr(1,strLine, ",") Then
arrayMasterFile = split(strLine, ",")
strStoreName = arrayMasterFile(0)
strComputerIP = arrayMasterFile(1)
strEmailRecipient = arrayMasterFile(2)
'Call ping function to check for online/offline computers
Call Ping_Computer()
End If
Loop
'Release Memory
objTextFile.Close()
Set objTextFile = Nothing
Set objMasterFSO = Nothing
End Sub
next i ping to each of the ip's (btw this will only show if the ip is offline, can you guarantee that the ip is online all of the time?)
Sub Ping_Computer()
Set wshShell = CreateObject("WScript.Shell")
'Run the ping program 3 times, with a 2000ms delay on each, 0 = don't display cmd prompt
'All three pings must be successful for CBool = true
pingSuccessful = Not CBool(wshShell.run("ping -n 3 -w 2000 " & strComputerIP,0,True))
If pingSuccessful = True Then
Else
Call Send_EMail()
End If
'Release memory
Set wshShell = Nothing
End Sub
Send an email
Sub Send_Email()
Set objEmail = CreateObject("CDO.Message")
strSubject = ""
strEmailFrom = ""
strBody = ""
objEmail.Subject = strSubject
objEmail.From = strEmailFrom
objEmail.To = strEmailRecipient
'Use Microsoft schemas for emails
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoNTLM
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strServer
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = cMailPort
objEmail.Configuration.Fields.Update
objEmail.Textbody = strBody
'Check if an error occurs during the send email process, do not stop program
On Error Resume Next
objEmail.Send
'error on send
If Err.Number <> 0 Then
Else
End If
'clear errors
On Error Goto 0
'Release Memory
Set objEmail = Nothing
End Sub
Salvete!
On my server I am running hMailServer, and that service uses the local system account.
I need to copy a file to another machine. So I have this a script that will use cmdkey.exe to save the credentials and then copy the file.
If I run this function myself (in a standalone vbs file) whilst logged into the server, it works, but I am admin.
However, if I let the hMailServer service run this function, the function runs, but it always says the destination does not exist.
Notice I have commented out the deletion of the credentials. If I go to the server and run cmdkey /list I see that the credentials were never set, which means the command failed. That means the first setting of the credentials probably failed too, which is why 'objFSO' cannot find the directory.
Again, if I put all this in a separate file and run it as test.vbs by double-clicking the file, it works. But if I use it from within hMailServer, it fails.
I suppose this means the hMailServer (local system account) doesn't have rights to set credentials? How do I get this to work?
option explicit
dim SPcopyMessage
SPcopyMessage = CopyFileToRemoteMachine("SERVER", "mydomain\username", "password", "c:\test2.txt", "\\SERVER\somefolder\otherfolder")
MsgBox SPcopyMessage
function CopyFileToRemoteMachine(whatMachine, whatUsername, whatPassword, whatSourceFile, whatDestination)
dim errormessage, CredentialCreate, CredentialDelete
errormessage = "Sharepoint Mail Delivered"
CredentialCreate = "cmd.exe /c cmdkey /add:" & whatMachine & " /user:" & whatUsername & " /pass:" & whatPassword
Dim objShell, objFSO
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
CALL objShell.Run(CredentialCreate, 0, True) 'add username to the credentials list
If objFSO.FileExists(whatSourceFile) Then
If objFSO.FolderExists(whatDestination) Then
If Right(whatDestination, 1) <> "\" Then
whatDestination = whatDestination & "\"
End If
objFSO.CopyFile whatSourceFile, whatDestination, True
Else
errormessage = "Destination does not exist: " & whatDestination
End If
Else
errormessage = "Source file does not exist: " & whatSourceFile
End If
'CredentialDelete = "cmd.exe /c cmdkey /delete:" & whatMachine
'CALL objShell.Run(CredentialDelete, 0, True)
set objFSO = nothing
set objShell = nothing
CopyFileToRemoteMachine = errormessage
end function
Figured out a way! First, I made sure the destination was shared to the right user account on machine2. Then made the script on machine1 to map the network drive and then copy the file. This will work as long as the N drive is never used for anything else on that machine.
Here is the code is if be helpful to anyone!
function CopyFileToRemoteMachine(whatMachine, whatUsername, whatPassword, whatSourceFile, whatDestination)
dim errormessage, mdrive
errormessage = "File successfully copied"
mdrive = "N:"
Dim objFSO, objNetwork
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("Wscript.Network")
If not objFSO.FileExists(mdrive) Then
objNetwork.MapNetworkDrive mdrive, whatDestination, False, whatUsername, whatPassword
End If
If Right(whatDestination, 1) <> "\" Then
whatDestination = whatDestination & "\"
End If
If objFSO.FileExists(whatSourceFile) Then
If objFSO.FolderExists(whatDestination) Then
objFSO.CopyFile whatSourceFile, whatDestination, True
Else
errormessage = "Destination does not exist: " & whatDestination
End If
Else
errormessage = "Source file does not exist: " & whatSourceFile
End If
objNetwork.RemoveNetworkDrive mdrive,TRUE,TRUE
set objFSO = nothing
set objNetwork = nothing
CopyFileToRemoteMachine = errormessage
end function
I'm trying to write an application that sends and receives service calls from a pc to a mobile phone.
I'm using a program called mobile data studio to do most of the work.
Basically the program generates a web-page as its report for a customer and this is mailed to the customer by the system which i have working
The problem is that the system does not wait until the file is generated before it tries to send it as an attachment and i get an error:
CDO.Message1
The system cannot find the file specified.
Position: 58.0
this is the code:
objmessage.Addattachment sFile
Once I click OK on the error the file is then created and if I run the script again it process the mail and the attachment and opens the file if fax is set to "yes" also.
This is all the code:
' Process incoming sessions from Pocket PCs
Function OnIncomingSession (theSession)
' Check if the user indicated a confirmation was desired
If theSession("SendEmail") = "Yes" Then
sendobjMessage theSession
ElseIf theSession("SendFax") = "Yes" Then
sendobjfax theSession
End If
' Set the return value to true to indicate that normal
' processing should continue
OnIncomingSession = True
End Function
Sub sendobjMessage (theSession)
' Get the email address from the session
sEmail = theSession ( "EmailAddress" )
'Get the file name from the session
sFile = "C:\htm\"& theSession("ORN")&"."&"htm"
Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).
Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Our Company - Service Report" & " " & theSession("rdate")
objMessage.From = """Service Department"" <user#mydomain>"
objMessage.To = sEmail
objMessage.TextBody = "Hi " & theSession("sname") & ","
objmessage.Addattachment sFile
Set objfax = CreateObject("WScript.Shell")
objfax.Run sFile
'==This section provides the configuration information for the remote SMTP server.
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.mydomain.com"
'Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = "user#mydomain"
'Your password on the SMTP server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objMessage.Configuration.Fields.Update
'==End remote SMTP server configuration section==
objMessage.Send
End Sub
Option Explicit
Dim retval, fso, file
Set fso = CreateObject ("scripting.filesystemobject")
file = "c:\temp\myfile.txt"
retval = waitTilExists (file, true)
MsgBox "return value: " & retval
Function waitTilExists (ByVal file, withRepeat)
' Sleeps until the file exists
' The polling interval will increase gradually, but never rises above MAX_WAITTIME
' Times out after TIMEOUT msec. Will return false if caused by timeout.
Dim waittime, totalwaittime, rep, doAgain
Const INIT_WAITTIME = 20
Const MAX_WAITTIME = 1000
Const TIMEOUT = 5000
Const SLOPE = 1.1
doAgain = true
Do While doAgain
waittime = INIT_WAITTIME
totalwaittime = 0
Do While totalwaittime < TIMEOUT
waittime = Int (waittime * SLOPE)
If waittime>MAX_WAITTIME Then waittime=MAX_WAITTIME
totalwaittime = totalwaittime + waittime
WScript.sleep waittime
If fso.fileExists (file) Then
waitTilExists = true
Exit Function
End If
Loop
If withRepeat Then
rep = MsgBox ("This file does not exist:" & vbcr & file & vbcr & vbcr & "Keep trying?", vbRetryCancel+vbExclamation, "File not found")
doAgain = (rep = vbRetry)
Else
doAgain = false
End If
Loop
waitTilExists = false
End Function
I might have some helpful tools.
I get the impression that you need:
Routine that creates a delay or pause of a certain period of time
Routine that checks for a file's existence.
Here's a routine for creating a delay or pause:
Sub subSleep(strSeconds) ' subSleep(2)
Dim objShell
Dim strCmd
set objShell = CreateObject("wscript.Shell")
'objShell.Run cmdline,1,False
strCmd = "%COMSPEC% /c ping -n " & strSeconds & " 127.0.0.1>nul"
objShell.Run strCmd,0,1
End Sub
Here's a routine for checking for a file's existence:
Function fnFileExists_Bln(strFULLNamee)
Dim strFULLName
strFULLName = strFULLNamee
Dim objFSO
Set objFSO = CreateObject("scripting.filesystemobject")
fnFileExists_Bln = objFSO.FileExists(strFULLName)
End Function ' Function fnFileExists_Bln(strFULLNamee)
I hope this helps.