cmd call opening multiple cmd's - vb.net

i have the following lines in a vb.net project im making
Private Sub yesButton_Click() Handles yesButton.Click
Shell("CMD.exe", AppWinStyle.NormalFocus)
SendKeys.SendWait("start firefox")
SendKeys.Send("{ENTER}")
Close()
End Sub
i want the button click to open Firefox using cmd then close, it works however it opens 20-30 cmd windows and about 5 fireofx's in the process, why? and more important how can i prevent this?
i am running visual-studio-2012. this is not the same as my other question.
--edit--
the same result is with this code
Private Sub yesButton_Click() Handles yesButton.Click
Shell("CMD.exe", AppWinStyle.NormalFocus)
SendKeys.Send("start firefox {ENTER}")
End Sub

Simply use this
Shell("CMD.EXE /C start firefox")
this will open a cmd command window and start firefox. the /C parameter is used to execute the command string following /C and then terminates.
type Run -> cmd -> cmd /? to see full list of cmd parameters available.

Related

Disappearing Command Prompt VB Script

Problem: Simple GUI with a button which triggers a batch file to run via cmd. Works for simple and fast scripts (ie mkdir foo), but more advanced scripts which need time to finish, it fails. The problem seems to surround cmd closing before the script can finish. I have included a WaitForExit() clause, but it seems to be ignored.
Private Sub RunButton_Click(sender As Object, e As EventArgs) Handles RunButton.Click
Dim foo as String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Foo\Scripts\foo.bat")
Dim p As New Process
Application.DoEvents()
p.StartInfo.FileName = foo
p.Start()
p.WaitForExit()
End Sub
Any ideas how to correct this issue? I see lots of posts about WScript and creating a shell object; do I really need to do it like that? This process seems to work, but it just closes out before the process finishes.

Import-Module not working from within WinForms Application

I have a VB.net app where I invoke Import-Module on a PowerShell from within my vb.net Window Application but the error says it could not find the module. Error as below.
Import-Module : The specified module 'MSOnline' was not loaded because no valid module file was found in any module directory.
When I load the same Module by launching the PowerShell externally in the usual way it works fine. Image as below.
The VB script is as below
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim procStartInfo As New ProcessStartInfo
Dim procExecuting As New Process
With procStartInfo
.UseShellExecute = True
.FileName = "powershell.exe"
.WindowStyle = ProcessWindowStyle.Normal
.Verb = "runas" 'add this to prompt for elevation
Dim psscript As String = My.Resources.mymsolPS
procStartInfo.Arguments = psscript
procExecuting = Process.Start(procStartInfo)
End With
End Sub
My PowerShell Script is saved in my.resource as a txt file. My PowerShell Script is as below.
Import-Module Msonline
Connect-msolService
I replaced the PowerShell script to Get-Help and that works only it dosnt work when I use Import-Module Msonline.
One more information that can be shared is the module is stored in the below location.
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MSOnline\MSOnline.psd1
Any Help is greatly appreciated.
Thanks in Advance
Update 2:
More fiddling with it found some thing which i am not sure if is relevant.
If I launch the powershell from within my VB.net and run the below command I cant see the MSOnline module.
PS C:\windows\system32>> cd $env:WINDIR\System32\WindowsPowerShell\v1.0\Modules\
PS C:\windows\System32\WindowsPowerShell\v1.0\Modules>> dir
If I run the PowerShell directly from my system and run the above script I can see the Module
d----- 11/22/2017 2:59 PM MSOnline
Still a mystery for me which I cant crack. :(
A difference I notice is when launching from your app, or locally, the directory is either your user, or system.. so maybe the way PS is being loaded it can't find the module.
What about if you provide a full path to the module?
I've had much better luck using RunSpace - I use it to pass any powershell commands - here are a snippet from one of the sites and some examples to look at:
'Create the runspace.
Using R As System.Management.Automation.Runspaces.Runspace = _
System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
'Create the pipeline
Using P As System.Management.Automation.Runspaces.Pipeline = R.CreatePipeline()
'Open the runspace.
R.Open()
'Create each command (in this case just one)...
Dim Cmd As New System.Management.Automation.Runspaces.Command("C:\script.ps1", True)
'...and add it to the pipeline.
P.Commands.Add(Cmd)
'Execute the commands and get the response.
Dim Result As System.Collections.ObjectModel.Collection(Of _
System.Management.Automation.PSObject) = P.Invoke()
'Close the runspace.
R.Close()
'Display the result in the console window.
For Each O As System.Management.Automation.PSObject In Result
Console.WriteLine(O.ToString())
Next
End Using
End Using
http://www.winsoft.se/2009/08/execute-a-cmdlet-or-ps1-script-from-visual-basic/
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5d2279c8-e02c-45eb-a631-951c56067bb5/run-powershell-script-from-vbnet?forum=vbgeneral
https://code.msdn.microsoft.com/windowsdesktop/VBPowerShell-6b4f83ea
The last one provides a pretty solid breakdown of what it's doing. Let me know if you can't get it to work, I can try to see if this import works on an app.
I actually found the solution after hours of pain. This is pretty silly solution.
Went I went to my application Properties I found that the Preferred run was set to 32 bit hence when my PowerShell was launched from within it was looking for the module under SYSWOW where its suppose to look it under System32. I unchecked the "Preferred 32 BIT" and not it imports the module from system 32.
Thought I should share this silly miss so that others should not suffer the same.

Executing multiple bat files with Visual basics

I'm working on a program created with Visual Studio 2013. The program does a few things and I'm nearly complete, but one last issue appears.
Within the program I have three buttons. One "Force restart", "manual start" and one "force stop". The "force stop" stops a bunch of programs, and the "force restart" stops them and then starts them again. The "manual start" starts all the programs. I will use "manual start" as example further down.
What happens behind these buttons is that it launches a bunch of bat-files that does the job. The batfiles contains tasskill /f /im program.exe and start "c:\program.exe". Then a second with timeout and exits.
The issue:
So far so good. The issue is that when the batch starts a program, VB program doesnt move on the the next bat file. It leaves a cmd.exe running. Even tho I have exit in the batch. Now If I'd go in and manually close the program or cmd.exe, then it would start on the next bat file.
It basically goes like this now: VB button -> batch starts -> batch runs program -> batch doesn't close AKA VB doesn't move to the next batch.
It should be like this: VB button -> batch starts -> batch runs program -> batch exits -> next batch starts -> batch runs program -> batch exits ->...
Here is what I got so far in that section of VB script:
Private Sub btnManualStart_Click(sender As Object, e As EventArgs) Handles btnManualStart.Click
If MessageBox.Show("Do you want to manually start all programs and services?", "OBS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
Timer2.Start()
Dim FileNum As Integer = FreeFile()
FileClose(FileNum)
TextBox1.Text &= Environment.NewLine & TimeOfDay & (" Manual start made")
Dim shell
shell = CreateObject("wscript.shell")
shell.run("C:\RestartApps\Scripts\Start_program1.bat", 0, True)
shell.run("C:\RestartApps\Scripts\Start_program2.bat", 0, True)
shell.run("C:\RestartApps\Scripts\Start_program3.bat", 0, True)
shell.run("C:\RestartApps\Scripts\Start_program4.bat", 0, True)
shell = Nothing
end if
Hopefully this was understandable.
I do not know exactly what your batches are doing, but it seems to me that you can simply use the Shell shortcut:
Dim commands As String() = {
"C:\RestartApps\Scripts\Start_program1.bat",
"C:\RestartApps\Scripts\Start_program2.bat",
"C:\RestartApps\Scripts\Start_program3.bat",
"C:\RestartApps\Scripts\Start_program4.bat"
}
For Each cmd As String In commands
Shell(cmd, AppWinStyle.Hide, False)
Next
Make sure that you set the third argument to FALSE on the overload (String,AppWinStyle,Boolean). This boolean ensures that the execution is set to "fire and forget". (which is the same as the one you're already passing, as TRUE (will wait for exit code)).
EDIT: Changed the AppWinStyle to Hide, which will run your batches silently
You need to improve start used in your batch script(s) as follows:
start "" /B "c:\program.exe"
Start command: start a program, command or batch script (opens in a new window). Note:
"" always include a TITLE this can be a simple string or just a pair of empty quotes "";
/B start application without creating a new window.
Another approach: use call instead of start "" as follows:
call "c:\program.exe"

Autorun of vb.net program with command line parameters does not work

I am writing an application that needs admin rights to run in VB.NET (VS2012,framework 4)
It is an app to protect the Hosts file from modification.
I want the app to start automatically with windows with the command line argument "autorun".
So I have made a check box with the following code:
Private Sub CheckBox_autoupdate_Click(sender As Object, e As EventArgs) Handles CheckBox_autoupdate.Click
Dim oreg As RegistryKey = Registry.CurrentUser
Dim okey As RegistryKey = oreg.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
If CheckBox_autoupdate.Checked = True Then
okey.SetValue("HostProtect", Application.ExecutablePath & " /autoupdate")
Else
okey.DeleteValue("HostProtect")
End If
My.Settings.Save()
End Sub
When I open regedit, the value is present but when I restart my system the program is not executed at all!
Is it because the app needs admin priviledges? How can I make it start AND correctly pass the command line argument?
Anticipating your answers!
HKey_CurrentUser entries don't run when Windows starts. They run when the user logs in and the user's registry hive is loaded. If you want it to run when Windows starts, you'll need to use HKey_LocalMachine. Or even better, write this as a Windows Service.
Application.ExecutablePath will get the .exe link, not the path, so it should be:
Application.StartupPath & " \autoupdate.exe"

dos cmd \cmd prompt vb.net 2010

i used this example to open a command prompt from within vb.net 2010
lnk to stackoverflow document
the command prompt opens as expected and i can do directories open commands like regedit etc. without an issue
but what i really want is tftp.exe when i look for it it does not show up, when doing a dir it is not listed when type tftp at command prompt i get the to recognzed command
when comparing to a normal command prompt by type cmd at the run line i can see it in the windows\system32 folder
also when i do a dir from normal command prompt and compare to dir from the cmd prompt opened by vb.net there is a 400+ number of files difference out of close to 3000 files
trying to find out why i cant see all the files here is the actul code i used
Private Sub Button30_Click(sender As System.Object, e As System.EventArgs) Handles Button30.Click
Dim command As String = "tftp -i 192.168.10.177 put test1.bin"
Dim arguments As String = ""
Dim permanent As Boolean = True
Dim p As Process = New Process()
Dim pi As ProcessStartInfo = New ProcessStartInfo()
pi.Arguments = " " + If(permanent = True, "/K", "/C") + " " + command + " " + arguments
pi.FileName = "cmd.exe"
p.StartInfo = pi
p.Start()
End Sub
This seems like a very convuluted approch you are taking, but to answer your question directly, you probably need to set the working directory like so:
pi.WorkingDirectory = "c:\windows\system32"
I have to say though, you might want to reconsider the whole approach of opening a DOS window for the user to type commands. Doesn't see very user friendly.
ok found the answer, it is becuase i am running 64bit windows and when its looking for the tftp.exe it is actually looking in the syswow64 directory and tftp.exe is not in that directory.
since i have this running and compiled for x86 and not 64bit here is the work around
Public Declare Function Wow64DisableWow64FsRedirection Lib "kernel32" (ByRef oldvalue As Long) As Boolean
then
Wow64DisableWow64FsRedirection(0)
after adding tthis to my code the tftp upload works flawlessly