Delete application executable on exit - vb.net

So I am trying to get my application to delete itself on exit.
I am currently using this (found here):
Process.Start("cmd.exe",
"/C choice /C Y /N /D Y /T 3 & Del " + Application.ExecutablePath);
Application.Exit();
The CMD window comes up, but will not remove the application. Any ideas why not?
EDIT:
So it works sometimes... other times it does not... ideas?

I think the problem is that you cannot delete an application while it's running.
You could introduce some delay in the cmd command(I don't know how), or you could simply make another application with a timer set on 5 sec. And insert the code:
System.IO.File.Delete(Application.ExecutablePath)
Me.Close
Then just use the Process.Start("your/Delete/App/Path.exe") in the first app.

Related

Shell hitting Run-Time error '5' trying to call R script in Access VBA

I made a simplified version of my code that directly highlights the issue.
I have read dozens of similar issues/solution.
Part of my workflow in VBA in Microsoft Access involves calling an R script that does some logic and returns information to a table in the same database.
It was working until we moved the location of the R installation to a new drive. Changing the path to this new install location does not work. No other code is changed.
cmd = "C:\R\bin\i386\Rscript.exe C:\R\test.R"
Debug.Print cmd
Shell cmd
I get
runtime error '5'
I am using the immediate window to check the paths are correct and copying them into RUN to verify that they do work.
The above outputs:
C:\R\bin\i386\Rscript.exe C:\R\test.R
It works in RUN.
The first thing I found when searching online is to add more (") as shell can handle them weirdly:
cmd = """C:\R\bin\i386\Rscript.exe""" & " " & """C:\R\test.R"""
Or any iterations of using "s in different places, output:
"C:\R\bin\i386\Rscript.exe" "C:\R\test.R"
Same error but works in RUN. I also tried them all successfully in CMD.
It seems just Shell refuses to launch R from that path. I have moved it elsewhere on my C drive with same effect.
I cannot recreate the original R installation path as that shared drive is now completely dead.
EDIT:
I changed to using ShellExecute simply to try and make Notepad ++ open, again works in cmd.
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "C:\N\notepad++.exe", "C:\R\test_in.csv", "", "open", 1
This time I hit a "suspicious macro error" that leads me to believe that it may be an antivirus setting (macros are enabled in Access) blocking Shell from calling anything.
After days of testing I have found the solution, hopefully this can help anyone else in a similar situation. Windows Defender only blocks shell calls to non-Microsoft products, so I nested a call to PowerShell within the call to Shell:
Shell ("powershell.exe C:\R\bin\i386\Rscript.exe C:\R\test.R")
Take note you need to play around with the "s a lot ot get it working, my actual pipeline has more arguments and I had to enclose them in 5 sets of "s for it to pass through to powershell properly. IE:
Dim codePath As String: codePath = """""\\example\example"""""
Try these variations using Start or a second Command:
cmd = "Start C:\R\bin\i386\Rscript.exe C:\R\test.R"
or:
cmd = "cmd /c ""C:\R\bin\i386\Rscript.exe C:\R\test.R"""

Batch file hold shift key to hightlight

we run WinSQL with DB2's begin and end statements. We have multiple scripts in one file. I was wondering if there was a way to hold down shift with SendKeys to use the right arrow/down arrows to highlight the text I want to run. Does it need a loop? And how do I do a 5 second delay before it starts so I can switch the windows when I run it? I tried:
set /P "=Wait and send a command: " < NUL
ping -n 1 -w 1 127.0.0.1 > NUL
%SendKeys% "^{RIGHT}"
for the highlighting, multiple times, but it forgets about the shift key and just moves right multiple times.
Thanks
Try this for your sendkeys.
Example
%SendKeys% "+{right}"
^ is for CTRL key rather than shift.
Then for delay try cmd command timeout /t 5
On another note since you're using vbs also, you can use that to switch your windows as well.
Dim ObjShell :Set ObjShell = CreateObject("Wscript.Shell")
ObjShell.AppActivate("Notepad")

Command line to kill Adobe Reader process only if it was not already running

I am trying some cmd.exe coding for the first time. I created a registry key, which contains a command called by a custom protocol handler­. What I'm trying to accomplish : Call Adobe Reader which will automatically print a pdf to a given printer. This part already works. I'm using powershell to download the pdf locally from a URL. I also want to kill the Acrobat process once i'm done, but only if it was already opened BEFORE calling my command, so I don't kill the process if the user already has a pdf opened when calling the protocol handler via Chrome.
Excuse the more than ugly formatting, a one-line command is a must in my case, I can't make a batch file or .ps1 file.
cmd /V /C set exists="0" & (tasklist | find "AcroRd32.exe" > nul) & if
(%%ERRORLEVEL%%==0 set exists="1") & set myvar=%1 & call set
myvar=%%myvar:ie:=%% & call set printer=%%myvar:*###=%% & call set
printer=^"%%printer%%^" & call set printer=%%printer:'=%% & call start
powershell.exe -ExecutionPolicy Bypass -Command $url=%%myvar%%; $pdf =
$url.split('#'); md -Force c:\TempPdf "| Out-Null"; (New-Object
System.Net.WebClient).DownloadFile($pdf,'C:/TempPdf/PatientLabel.pdf'); &
timeout /t 2 & call start acrord32.exe /n /t C:/TempPdf/PatientLabel.pdf
%%printer%% & timeout /t 2 & (if !exists!=="1" taskkill /f /im acrord32.exe)
The part which does not work is the tasklist/taskkill. I want to set the %%exists%% variable to 1 if I can find the process running before starting AcroRd32.exe and kill it after printing if %%exists%%=1. I think this might just not be working because of the execution time/parse, but I don't really know how to use /V and !var! anyway. The exists and ERRORLEVEL variables don't seem to expand.
Thanks for the help !

wshshell.popup not being displayed to other user when using task scheduler

I've got a tricky thing to do here.
I'm using task scheduler to auto-reboot all the computer during the weekend by calling a simple .bat file containing a shutdown command.
I wanted to give the user the possiblilty to cancel that reboot by displaying them a popup saying "Computer is about to restart, do you wish to continue ? Ok or Cancel". I have done that with VB using the popupbox method, it works perfectly.
Here is the problem i'm facing: The task is running under the System account and unless the task is set to run with the current logged on user, the popup box won't appear. I could change the account set in the task but I've got hundreds of users so impossible.
I've done some kind of a workaround, calling the VBS from Psexec... Works, but it's not perfect.
Here is my Psexec command that calls the VB:
Psexec -accepteula -s -i cmd /c C:\Windows\System32\Weekly_Reboot.vbs
Here is my VB:
Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")
BtnCode = WshShell.Popup("Computer is about to restart, do you wish to continue?", 30, "/!\ Weekly Restart /!\", 4 + 32)
Select Case BtnCode
case 6
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "c:\Windows\System32\Weekly_Reboot.bat"
case 7
WScript.Echo "No prob - the computer won't restart"
case -1
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "c:\Windows\System32\Weekly_Reboot.bat"
End Select
And here is the actual reboot command:
Shutdown /f /r /c "This is the weekly reboot"
Any idea would be really awesome ! I really tried googling it, but no luck.
Here is the problem i'm facing: The task is running under the System account and unless the task is set to run with the current logged on user, the popup box won't appear. I could change the account set in the task but I've got hundreds of users so impossible.
Change the task to run under the group called Users. It will make the task run for any logged in user.
I'm not certain if this is needed: but you might want to run it using the highest privileges.

Sending console commands / using windows variables

A two-part question but they tie in together. - I'm experimenting with VB.net console applications and I'm wandering how I send command line commands to the console window. Take the below Sub.
Sub initialLoad()
Console.WriteLine("Started # " + %date% %time%)
Console.WriteLine("Test")
End Sub
I'm trying to add the equivalent of echo. which would add a line break, I tried using the string Console.WriteLine("Test", vbCrLf) but the vbCrLF made no difference and did not add a line break after the text.
The %date% and %time% variables when used on a Batch script for example will give the current date and time and is recognised and defined automatically within the CMD window. Am I able to send these CMD commands to the console or must I use VB.net equivalents to achieve this.
I found that instead of pause>nul I had to use Console.ReadLine() to make the console window pause.
Am I incorrect in assuming I can use CMD commands? I know in C++ I can send all the commands but is there something similar in VB.net? Thanks.
For environment variables use Environment.GetEnvironmentVariable
For new line use Environment.NewLine
For commands see here: How To: Execute command line in C#, get STD OUT results - this is in C# but you can use the same objects in VB.NET.