How to obtain ip address automatically programmatically - vb.net

Dim args As String
args="netsh wlan interface ip set address """+adptrname+""" dhcp"
Dim proc As New System.Diagnostics.Process()
proc.StartInfo.FileName = "netsh"
proc.StartInfo.Verb="RunAs"
proc.StartInfo.CreateNoWindow = true
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.Arguments = args
proc.StartInfo.UseShellExecute = False
proc.Start()
My.Computer.FileSystem.WriteAllText(MainForm.filePath,proc.StandardOutput.ReadToEnd(), True)
proc.Close()
MsgBox(args)
i wrote the above piece of code to change my wlan adapter to obtain ip address automatically but it still remains on the old ip configuration inspite of the output saying that dhcp is enabled. Can someone please tell where I am going wrong.

OK i tried to do this on the comments, but i kept on finding errors... so here a corrected version of your code:
'Where does your adptrname come from?
Dim adptrname As String = "wlan0" 'i.E.
Dim args As String
' Note that i removed 'netsh' from args
' And the notation to add the addapter name (in VB we use & instead of +)
args="netsh int ipv4 set address name=""" & adptrname & """ source=dhcp"
Dim proc As New System.Diagnostics.Process()
proc.StartInfo.FileName = "netsh"
proc.StartInfo.Verb="RunAs"
proc.StartInfo.CreateNoWindow = true
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.RedirectStandardError = True ' maybe you want to read this, too
proc.StartInfo.Arguments = args
proc.StartInfo.UseShellExecute = False
proc.Start()
' This is still bad, but we keep it for now
My.Computer.FileSystem.WriteAllText(MainForm.filePath, proc.StandardOutput.ReadToEnd(), True)
My.Computer.FileSystem.WriteAllText(MainForm.filePath, proc.StandardError.ReadToEnd(), True)
' Normally not necessery, but no way we do proc.close() here
proc.WaitForExit()
' ok, this shoud have shown you until now that it didn't work...
MsgBox(args)
Read the comments, try the corrections on your own code and see if it runs.
Edit on the Parameters
Also i am thinking it won't work with your arguments...
Try it like this instead:
netsh int ipv4 set address name="Wireless Connection" source=dhcp
I built this from the help and it works on my machine (Win7x64-en_US)

Related

I cannot figure out ProcessStartInfo and to be able to use Process.Start.StandardOutput.ReadToEnd to display what is happening in Command line

I am trying to display what is going on in Command Line Interface without opening up command line. I know Process class has that ability but I am having a hard time with StandardOutput.ReadOnly. I have the process set to one button and then after I click, I want it to show a status that command line is in fact connecting. Thoughts?
Private Sub EstablishConnection_Click(sender As Object, e As EventArgs) Handles EstablishConnection.Click
' One file parameter to the executable
Dim sourceName1 As String = strXFileName
Dim sourceName2 As String = strYFileName
' New ProcessStartInfo created
Dim p As New ProcessStartInfo
' Specify the location of the binary
p.FileName = "C:\Software\John\Doe"
' Use these arguments for the process
p.Arguments = $"-Application -Connect -Example -E"" {stXFileName} "" -S"" {strYFileName} """
' Use a hidden window
p.WindowStyle = ProcessWindowStyle.Hidden
p.UseShellExecute = False
p.RedirectStandardOutput = True
p.RedirectStandardError = True
p.RedirectStandardInput = True
' Start the process
Process.Start(p)
'Dim output As String = p.StandardOutputEncoding
'Open the Status Screen form once connection is established
StatusScreen.Show()
Me.Hide()
End Sub

Get the output of a shell Command in VB.net

I have a VB.net program in which I call the Shell function. I would like to get the text output that is produced from this code in a file. However, this is not the return value of the executed code so I don't really know how to.
This program is a service but has access to the disk no problem as I already log other information. The whole service has multiple threads so I must also make sure that when the file is written it's not already accessed.
You won't be able to capture the output from Shell.
You will need to change this to a process and you will need to capture the the Standard Output (and possibly Error) streams from the process.
Here is an example:
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
Console.WriteLine(sOutput)
To get the standard error:
'Add this next to standard output redirect
oStartInfo.RedirectStandardError = True
'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
sOutput = oStreamReader.ReadToEnd()
End Using
Just pipe the output to a text file?
MyCommand > "c:\file.txt"
Then read the file.
Dim proc As New Process
proc.StartInfo.FileName = "C:\ipconfig.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
RichTextBox1.AppendText(ln & vbNewLine)
lstScan.Items.Add(ln & vbNewLine)
Next
=======================================================================
create a batch file in two lines as shown below:
echo off
ipconfig
' make sure you save this batch file as ipconfig.bat or whatever name u decide to pick but make sure u put dot bat at the end of it.

Use a variable in file path in .vbs

Is it possible to usa variable in a path in .vbs. My basic situation is I have a vbs script that will often be run on a computer with one person logged in and run by an admin with a completely different user name (assume the file will be right clicked and "Run As").
The script edits an ini file that is located in the user directory for the person logged in. I know in batch I could simply insert the variable "C:\Users\%Logger%\AppData\Local\stat.ini" and the variable would be replaced. But I can't do this in .vbs. My script thus far. Or look at the bulk of it in an answer here.
Dim blnRes: blnRes = 0
Dim strOld, strNew, logger
strOld = "frogg"
strNew = "frog"
logger = Inputbox("What is your Domain ID exactly as entered when you log into this machine?","Domain ID")
On Error Resume Next
Call update("C:\Users\logger\AppData\Local\stat.ini", strOld, strNew)
blnRes = blnRes Or (Err.Number = 0): Err.Clear
Is there some way I can flag logger as a variable, or is there an easier way to do this?
I guess you meant a script variable. Try this:
logger = Inputbox("What is ID?","Domain ID")
Call update("C:\Users\"& logger &"\AppData\Local\stat.ini", strOld, strNew)
You can use command line arguments with vbs. See the following technet site:
http://technet.microsoft.com/en-us/library/ee156618.aspx
using the example vbs at the bottom, you can have Ping.vbs reply based on the computer name entered after the script name when its called (C:\scripts\Ping.vbs Hostname)
Here's more info on WScript.Aurguments
https://www.google.com/search?q=WScript.Arguments&sourceid=ie7&rls=com.microsoft:en-us:IE-Address&ie=&oe=
'Ping.vbs:
Dim arArguments, strArgument
Set arArguments = WScript.Arguments
WScript.Echo WScript.Arguments.Count
For Each strArgument in arArguments
If Ping(strArgument) Then
WScript.Echo strArgument & " is available."
Else
WScript.Echo strArgument & " is not available."
End If
Next
Function Ping( myHostName )
Dim colPingResults, objPingResult, strQuery
strQuery = "SELECT * FROM Win32_PingStatus WHERE Address = '" & myHostName & "'"
Set colPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery )
For Each objPingResult In colPingResults
If Not IsObject( objPingResult ) Then
Ping = False
ElseIf objPingResult.StatusCode = 0 Then
Ping = True
Else
Ping = False
End If
Next
Set colPingResults = Nothing
End Function
If I understand what you're after correctly, you're either going to need to do a string concatenation where you build a string like "string part 1" & logger & "string part 2" or use the replace function to replace %Logger% (e.g. Replace(templateString, "%Logger%", logger)) with your logger variable. There's not a direct equivalent to the %1 sort of format used in batch files.
This worked for me:
Dim fs, ws, Path
Set ws = CreateObject( "WScript.Shell" )
Path = ws.ExpandEnvironmentStrings( "%UserProfile%\testfile.txt" )
ws = Nothing
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile (Path, True)
f.WriteLine("This is a test")
f.Close()
f = Nothing
Don't assume "C:\Users" will be valid on every system. There are times when you may want to use a different location for user profiles. I also looked at the %AppData% environment variable, but in my case that pointed to AppData\Roaming, and you want AppData\Local.

VB.NET read standard output

From my application I need to run a command and parse the output. I can do this with no problem but I don't want the command to be displayed. I hoped WindowStyle = ProcessWindowStyle.Hidden would work but it doesn't. Take the sample code below for example. It works fine but the command window still visibly opens and closes very quickly and I need it to never show its ugly face. How can I fix this?
Dim myprocess As New Process
Dim lines As String = ""
With myprocess
.StartInfo.FileName = "C:\Windows\System32\cmd.exe"
.StartInfo.Arguments = "/c ipconfig"
.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
.StartInfo.RedirectStandardOutput = True
.StartInfo.UseShellExecute = False
.Start()
End With
lines = myprocess.StandardOutput.ReadToEnd
MsgBox(lines)
Try setting CreateNoWindow to True too.
If what you are trying to achieve is to find the IP address(es) of the local machine, there are more direct ways of doing it.
Include
.StartInfo.CreateNoWindow = True
Try these settings in tandem:
.CreateNoWindow = True
.UseShellExecute = False
See http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx for more details.

If, Then Statement to let User Know Command Could Not execute?

Lets just say we have this as Command1
Dim Command1 = "whoami.exe >> C:\Hello.Txt"
The program will read a list of users from a text file and then perform the action on each of them. If the user does not exist, or they are part of a password protected computer, I would like to see that in my printout.
I have this but am Unsure how to write the If Then Statement (If that is the ebst route to take)
For Each strUserName as String in strLines
Shell("cmd.exe /c" & Command1)
If Command1 = fail??
Then msgbox("Oops") ???
If you want to redirect the output of 'whoami.exe' to your own console, you can do the following:
Dim startInfo As New ProcessStartInfo()
startInfo.Arguments = "c:\Hello.txt"
startInfo.FileName = "c:\whoami.exe"
startInfo.RedirectStandardOutput = True
startInfo.UseShellExecute = False
Using process As Process = Process.Start(startInfo)
Using stream As StreamReader = process.StandardOutput
Console.Write(stream.ReadToEnd())
End Using
End Using
You will need to import the System.Diagnostics namespace. If 'whoami.exe' returns an exit code you can use, you can also use the Process class to check it by calling:
process.WaitForExit()
Dim code As Integer = process.ExitCode
If code = 1 Then
' success
Else
' other
End If
Hope this helps.
You need to write the If Then statement in either one line or multiple lines ending with an End If
If Command1 = fail Then msgbox("Oops")
or
If Command1 = fail Then
msgbox("Oops")
End If
Here is the msdn documentation for the if statement.