How to terminate a process if it has specific folder name in its path? - process

I run an application from PowerBuilder and terminate it when i dont need it. But the application when running, it executes other processes from a specific folder.
I want to kill all processes if they run from a specific folder.
How to get the process handles of all those processes that have specif folder name in their path?

Here an example to show how to terminate all running instance of Notepad.exe
OleObject wsh
integer li_rc
wsh = CREATE OleObject
wsh.ConnectToNewObject( "MSScriptControl.ScriptControl" )
wsh.language = "vbscript"
wsh.AddCode('function terminatenotepad() ~n ' + &
'strComputer = "." ~n ' + &
'Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") ~n ' + &
'Set colItems = objWMIService.ExecQuery("Select * from Win32_Process where name = ~'notepad.exe~'") ~n ' + &
'For Each objItem in colItems ~n ' + &
' objItem.Terminate ~n ' + &
'Next ~n ' + &
'end function ~n ' )
wsh.executestatement('terminatenotepad()')
wsh.DisconnectObject()
DESTROY wsh
Try to change the where clause
where name = ~'notepad.exe~'" ...
for
where commandline = ~'" + ls_commandline + "~'" ...
where ls_commandline is the command line used to start your process.
See "Win32_Process class" for more infos.

/// This is simple code example Terminate a Running Process if here is specific
/// folder name in the path of the running program (\EagleGet\)
/// Two variable SelectThis and TheWhere can be changed to get different
/// results. Many things are not dynamic in this script and certainly not the
/// best way of writing code. but its just ok for a little quick work.`
OleObject wsh
Integer li_rc
String LineFeed = ' ~r~n '
String TheComputer = "." //local computer
String TheCode = "no need to set it here"
String FunctionName = "Whatever()" //any name you like
String SelectThis = "?" //only the columns/expressions
String TheWhere = "?" //only the where clause without keyword WHERE
String DoWhat = "?" //the action to perform for example 'Terminate' without quotes
String TheQuery = "no need to set here"
String WMIClass = "Win32_Process" /// The WMI class of running processes
String TheFolderName = "The folder name from which the creapy process is running (path) "
/// You just set DoWhat, SelectThis and TheWhere. Rest of the variables, you dont need to set here
/// SelectThis = is the columns or expressions you want returned by the Query
SelectThis = "*"
/// TheFolderName = set it to the name of the folder that exist in the path
///of the ruuning process you want to terminate
TheFolderName = "EagleGet"
/// TheWhere is the WHERE clause expressions
TheWhere = "ExecutablePath LIKE ~'%\\" + TheFolderName + "\\%~' "
/// DoWhat is the final function call of the WMI Class
DoWhat = "Terminate"
/// There is no need to chage anything from this point onward.
/// without double quotes, and you dont have to change TheQuery here
TheQuery = " SELECT " + SelectThis + " FROM " + WMIClass + " WHERE " + TheWhere
TheCode = "Function " + FunctionName + LineFeed + &
"strComputer = ~"" + TheComputer + "~"" + LineFeed + &
"Set objWMIService = GetObject(~"winmgmts:\\~" & strComputer & ~"\root\cimv2~")" + LineFeed + &
"Set colItems = objWMIService.ExecQuery(~"" + Trim(TheQuery) + "~" )" + LineFeed + &
"For Each objItem in colItems" + LineFeed + &
"objItem." + Trim(DoWhat) + LineFeed + &
"Next " + LineFeed + &
"END Function " + LineFeed
wsh = CREATE OleObject
wsh.ConnectToNewObject("MSScriptControl.ScriptControl")
wsh.Language = "VBScript"
wsh.AddCode(TheCode)
TRY
wsh.ExecuteStatement(FunctionName)
CATCH (RunTimeError Re01)
MessageBox("Query Error", "Following code has some problems.~r~n~r~n" + TheCode, StopSign!)
END TRY
wsh.DisconnectObject()
DESTROY wsh

Related

Dont get returned list of files in temp folder on Domino server via agent

I have a LotusScript agent, signed with proper ID to have full access rights on server. The agent should return a list of files in the temporary folder. Ultimately I would this agent to clean a specific folder here.
The problem is that the agent does not return a list of files although I know that files are there!
I wondering if I am dealing with some form of restriction (and how to pass by it) or if my code is incorrect (how to correct it).
The code is mostly inspired by in IBM support note.
https://www.ibm.com/support/pages/using-dir-function-recursive-lotusscript
Here is the code
Comment: [Not Assigned]
Shared Agent: Yes
Type: LotusScript
State: Disabled
Trigger: Scheduled
Interval: On Schedule More Than Once A Day
Acts On: None
LotusScript Code:
%REM
Agent cleanupTempCatalogAlt2
Created Sep 13, 2019 by §Patrick §Kwinten/Designer/ACME
Description: Comments for Agent
%END REM
Option Public
Option Declare
Dim sess As NotesSession
Dim agent As NotesAgent
Sub Initialize
Dim sess As New NotesSession
Set agent = sess.CurrentAgent
Print("### PK " + agent.Name + " - Starting ")
ScanDirs("D:\IBM\Domino\Temp\notes53F5BD\xspupload")
End Sub
Sub ScanDirs(path As String)
Print("### PK " + agent.Name + " - Start ScanDirs")
Dim sess As New NotesSession
Dim DirList As Variant
Dim filename As String
Dim filepath As String
Dim sep As String
If path <> "" Then
If InStr(sess.Platform, "Windows") > 0 Then
sep = "\"
Else
sep = "/"
End If
ReDim DirList(0)
If InStr(path, sep) > 0 Then
filepath = StrLeftBack(path, sep)
End If
Print("### PK " + agent.Name + " filepath - " + filepath)
Print("### PK " + agent.Name + " path - " + path)
filename = Dir(path, 16)
While filename <> ""
Print("### PK " + agent.Name + " filename - " + filename)
If filename <> "." And filename <> ".." Then
Print("### PK " + agent.Name + " filepath & sep & filename - " + filepath & sep & filename)
If (GetFileAttr(filepath & sep & filename) And 16) > 0 Then
DirList = ArrayAppend(DirList,filepath & sep & filename & sep)
Else
Print("### PK " + agent.Name + " - Got file?")
' PERFORM DESIRED CHECK/OPERATION
' ON filepath & sep & filename
' OR filename (as desired)
End If
End If
filename = Dir
Wend
Print("### PK " + agent.Name + " DirList - " + DirList(0))
DirList = FullTrim(DirList)
ForAll dirpath In DirList
ScanDirs(dirpath)
End ForAll
End If
End Sub
Try setting "Runtime security level" to 2 or 3 in agent properties.
Which version of Domino you are running and what platform?
Could the problem be here:
https://www-01.ibm.com/support/docview.wss?uid=swg1LO78281
upgrading to SLES11, the "dir$" function in LotusScript does
not see
directories and files within mounted shares anymore.
We didn't have chance to change linux-version so the problem was solved by syncing folder to server. Thereby we could remove files, and syncing takes care of the rest.

Remote desktop connection using process.startinfo

I have created an asp.net webpage and from the webpage I am using the code below to establish a remote desktop connection.
rdp.exe is a external file
Here is my code
Protected Sub BtnRemote_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnRemote.Click
Dim Process As New System.Diagnostics.Process
Dim startinfo As New System.Diagnostics.ProcessStartInfo
startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
startinfo.FileName = "C:\WINDOWS\system32\cmd.exe"
Dim path = "D:\rdp.exe"
startinfo.Arguments = path + "/v:" + txtTerminal.Text + " " + "/u:" + txtTerUser.Text + " " + "/p:" + txtTerPassword.Text
startinfo.UseShellExecute = False
Process.Start(startinfo)
End Sub
Everything is fine when I debug, but the system will not establish a remote connection.
But if I use the following command from command prompt, I am able to establish a remote connection.
E:\rdp /v:"IPAddress" /domain:"domain" /u:"username" /p:"password"
A problem i can see with this is within this line (Also Notice its got the Path, User, Password, and IP, BUT is missing the Domain Argument):
startinfo.Arguments = path + "/v:" + txtTerminal.Text + " " + "/u:" + txtTerUser.Text + " " + "/p:" + txtTerPassword.Text
as stated in your CMD arguments it needs to fit this format:
E:\rdp /v:"IPAddress" /domain:"domain" /u:"username" /p:"password"
However if you notice your startinfo.arguments doesn't contain a space in between the Directory and the IP Address Line so instead of reading it like this:
E:\rdp /v:"IPAddress" /u:"username" /p:"password"
it's reading it like this:
E:\rdp/v:"IPAddress" /u:"username" /p:"password"
just simply fix the line like this:
startinfo.Arguments = path + " /v:" + txtTerminal.Text + " /u:""" + txtTerUser.Text + """ /p:" + txtTerPassword.Text
I Also removed the Concatenations of + " " + because all you really need is a
space before the /'s and it will still work properly. Also notice that i have added extra quotes, because if the username supports spaces then when it goes to set the argument if the username contains a space then it will count them as two separate arguments quotes around it prevents it from being split into two different arguments
also instead of using CMD why not start the exe directly by
Dim p As Process
p.startinfo.FileName = "D:\rdp.exe"
p.StartInfo.WorkingDirectory = "D:\"
startinfo.Arguments = path + " /v:" + txtTerminal.Text + " /u:""" + txtTerUser.Text + """ /p:" + txtTerPassword.Text
p.Start()

Capture 7-Zip output and exit code from a process in VB

I have the following VB.NET 4.0 console application that runs 7z.exe in a process and successfully completes with a zipped file:
Public Sub CompressFiles(sZipFileName As String, sDriveLetter As String)
Dim s7ZipCmdArgs As String = ""
Dim myProcess As New Process
Console.WriteLine()
Console.WriteLine("Scanning files...")
'Compress files
s7ZipCmdArgs = " a -r -y -xr!windows\ -xr!$Recycle.Bin\ " + sZipFileName _
+ " " + sDriveLetter + "\*.txt" _
+ " " + sDriveLetter + "\*.doc" _
+ " " + sDriveLetter + "\*.xls" _
+ " " + sDriveLetter + "\*.ppt" _
+ " " + sDriveLetter + "\*.url" _
+ " " + sDriveLetter + "\*.docx" _
+ " " + sDriveLetter + "\*.xlsx" _
+ " " + sDriveLetter + "\*.pptx" _
+ " " + sDriveLetter + "\*.pdf" _
+ " " + sDriveLetter + "\*.wav" _
+ "> C:\test\zipresults.txt"
myProcess.StartInfo.FileName = "C:\test\7-Zip\7z.exe"
myProcess.StartInfo.Arguments = s7ZipCmdArgs
myProcess.StartInfo.WorkingDirectory = "C:\test"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
myProcess.WaitForExit()
End Sub
The code executes fine except for the redirect to a text file: "> C:\test\zipresults.txt" in the s7ZipCmdArgs string variable. I'm not sure why that's not working, I've tried different sets of double and triple quotes without success. It does work in a batch file using the same string.
My second question is: How do I capture the 7Zip exit code so that I can determine if it completed successfully? It returns the following integers: 0 (No errors), 1 (Non fatal error), 2 (Fatal error), 7 (Command line error), 8 (Memory error), and 255 (User error). I'm not sure how to capture the integer so that I can decode it.
For the first part, have you tried adding a space before the > in your command args? You could also check out this answer for capturing the output in code.
For the first part, per this answer you can't redirect the standard output using > when using Process.Start(). So, you will need to remove the redirect from the arguments, set StartInfo.RedirectStandardOutput to true, and then write the output to a file in the OutputDataReceived event. Something like this:
Dim pgm = "C:\Program Files\7-Zip\7z.exe"
Dim args = "l C:\Dev\Test.zip"
Dim myProcess = New Process()
With myProcess.StartInfo
.FileName = pgm
.Arguments = args
.WorkingDirectory = "C:\Dev"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardOutput = True
End With
Using out = New StreamWriter("C:\Dev\test.txt")
AddHandler myProcess.OutputDataReceived,
Sub(sender, e)
out.WriteLine(e.Data)
End Sub
myProcess.Start()
myProcess.BeginOutputReadLine()
myProcess.WaitForExit()
End Using
For the second, myProcess.ExitCode will have the result after the WaitForExit() call.

vb.net How to pass a string with spaces to the command line

I am trying to call an external program using Process:
Dim strExe As String = "E:\Projects\Common Files\mktorrent.exe"
Dim p As New Process
Dim pinfo As New ProcessStartInfo
pinfo.UseShellExecute = False
pinfo.RedirectStandardOutput = True
pinfo.Arguments = " -a http://blah.com/announce.php -l " & FileSizeMarker & " " & fn
pinfo.FileName = strExe
pinfo.WorkingDirectory = fn.Substring(0, fn.LastIndexOf("\"))
pinfo.WindowStyle = ProcessWindowStyle.Normal
pinfo.CreateNoWindow = True
p.StartInfo = pinfo
p.Start()
The problem is with the filename (variable fn above). If it has spaces, the command chokes - without spaces, it works fine. I have tried adding 1, 2 or3 quotes, like this:
fn = Chr(34) & Chr(34) & Chr(34) & fn & Chr(34) & Chr(34) & Chr(34)
and also
fn = "\") & Chr(34) & fn & "\"& Chr(34)
and many other combinations, but it still gives me an error. Any thoughts on how I can get this to work?
TIA
It's really an old - but unsolved - problem.
My 2 cents of contribution.
Use CHR(34) before-and-after the string, delimiting it like:
Arg = "Name=" & chr(34) & "John Doe da Silva" & chr(34)
Just it!
Please check the below link, its in C#, may be its helpful to you
Word command-line-arguments space issues
Windows does not provide a common way of keeping arguments with spaces as single arguments. However there are a number of relatively common standards that you've tried.
So it comes down to either determining what argument processing mktorrent.exe uses or, as you're trying to pass a filename, using "MSDOS" 8.3 format for the path which will have no spaces.
For the latter, this answer points to the Win32API GetShortPathName.
Of course, 8.3 filenames can be disabled with modern Windows (all Windows NT-based systems I believe -- not that it often is). So your only full solution is to determine what argument processing mktorrent supplies.
Since your comment suggesting the quotes are not being passed through I confirmed I see 'testing' 'testing' '1 2 3' in the MsgBox output of this vbscript:
Option Explicit
Dim arg
Dim line
For Each arg in WScript.Arguments
line = line & " '" & arg & "'"
Next
MsgBox Trim(line)
when executed using:
Dim strExe As String = "C:\Windows\System32\wscript.exe"
Dim p As New Process
Dim pinfo As New ProcessStartInfo
pinfo.UseShellExecute = False
pinfo.RedirectStandardOutput = True
pinfo.Arguments = " G:\Utils\Arguments.vbs testing ""testing"" ""1 2 3"""
pinfo.FileName = strExe
pinfo.WorkingDirectory = "G:\Utils"
pinfo.WindowStyle = ProcessWindowStyle.Normal
pinfo.CreateNoWindow = True
p.StartInfo = pinfo
p.Start()
So wscript is seeing the quotes and is accumulating three arguments for the script.
BTW I just noticed your example attempts at getting quotes around the filename modify the fn variable. Did you cater for this with the .WorkingDirectory line, which should be using the unmodified filename?
This allows me to pass spaces to cmd. Hours of research turned up nothing; this thread came up constantly, hopefully this will help someone else.
Dim startprgm As New ProcessStartInfo("cmd.exe", "/C """"C:\Program Files (x86)\Folder\File""""" + strArguments)
note that the 4 double quotes lead the path, this part is important. leading the argument (/C) with 5 quotes doesn't work, but the trailing five can be divided into 4 and 1; and structured as such:
Dim startprgm As New ProcessStartInfo("cmd.exe", "/C """"C:\Program Files (x86)""""\Folder\File" + strArguments)
If you open cmd.exe and just send a command, you just need the first quote on the path (it doesn't need to be closed) but VB needs the trailing ones to "close" the quotes out.
best of luck, guys.
This WORKS:
Dim current_path, current_rulename, cmd1 as STRING
current_path = "C:\this folder\file name.exe"
current_rulename = "file name.exe"
cmd1 = "netsh advfirewall firewall add rule name = """ + current_rulename + """ dir = in action = block program = """ + current_path + """"
cmd1 &= " & "
cmd1 &= "netsh advfirewall firewall add rule name = """ + current_rulename + """ dir = out action = block program = """ + current_path + """"
cmd1 &= " & pause"
Process.Start("cmd", "/c " + cmd1)
Basically, the variables with spaces need to be enclosed like this:
""" + string_with_spaces + """
Broken into parts:
cmd1 =
"
netsh advfirewall firewall add rule name =
""" + current_rulename + """
dir=in action=block
program=
""" + current_path + """
"
This code joins two separate commands that use STRINGS with spaces.
Be simple:
Process.Start("c:\Your exe file", """" & "string with space" & """")

How to get text and a variable in a messagebox

I just need to know how to have plain text and a variable in a messagebox.
For example:
I can do this: MsgBox(variable)
And I can do this: MsgBox("Variable = ")
But I can't do this: MsgBox("Variable = " + variable)
As has been suggested, using the string.format method is nice and simple and very readable.
In vb.net the " + " is used for addition and the " & " is used for string concatenation.
In your example:
MsgBox("Variable = " + variable)
becomes:
MsgBox("Variable = " & variable)
I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx
maybe call
variable.ToString()
update:
Use string interpolation (vs2015 onwards I believe):
MsgBox($"Variable = {variable}")
Why not use:
Dim msg as String = String.Format("Variable = {0}", variable)
More info on String.Format
I kind of run into the same issue. I wanted my message box to display the message and the vendorcontractexpiration. This is what I did:
Dim ab As String
Dim cd As String
ab = "THE CONTRACT FOR THIS VENDOR WILL EXPIRE ON "
cd = VendorContractExpiration
If InvoiceDate >= VendorContractExpiration - 120 And InvoiceDate < VendorContractExpiration Then
MsgBox [ab] & [cd], vbCritical, "WARNING"
End If
MsgBox("Variable {0} " , variable)
I wanto to display the count of rows in the excel sheet after the filter option has been applied.
So I declared the count of last rows as a variable that can be added to the Msgbox
Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox ("Number of test results between the selected dates " + lngStart + "
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue
Analysis")
End Sub