Place Line from Text File in a Shell CMD. VB.net - vb.net

I am assuming there is a way to have this sub in? I am assuming Do Until Loop is the way to go, I just do not know how to contruct one.
Sub Main()
'Declare Command
Dim sCommand As String
'Declare File where Users are Located
Dim strFile As String = "C:\TestDUsers.txt"
'Running from Admin Comptuer so permissions are fine
'Want to replace the ******** section with each username from text file
sCommand = "pushd \\*********\C$ && whoami.exe >> C:\File.txt"
'Load the File and perform the loop????
Using sr As New StreamReader(File.Open(strFile, FileMode.Open))
End Using
Console.WriteLine()
Console.Clear()
End Sub

Something like this if I understand your question correct:
Sub Main()
HandleJavaInfo()
End Sub
Sub HandleJavaInfo()
Dim strFile As String = "C:\Users\pseal2\Desktop\TestDUsers.txt"
Dim strCommand = "pushd \\*********\C$ && whoami.exe >> C:\Users\pseal2\Desktop\Javainfo."
Dim strLines() As String = IO.File.ReadAllLines(strFile)
For Each strUserName As String In strLines
'execute the command as shell or process
'Example using Shell (run the command whitout showing the window for the user)
Dim ThisCommand As String = strCommand.Replace("*********", strUserName)
Shell(ThisCommand, AppWinStyle.Hide)
'Example using process
Process.Start("pushd", "\\" & strUserName & "\C$ && whoami.exe >> C:\Users\pseal2\Desktop\Javainfo.")
Next
End Sub
Now, you have only told us what you want to DO, not what you want to achieve. If you tell us exactly what the goal is, then it may be some other .Net ways to do what you want, instead of shelling out to a DOS-command, and you can get more accurate answers.

Related

Loop to print text files is skipping some files(randomly, it seems)

I have a VB.NET program which lists some text files in a directory and loops through them. For each file, the program calls notepad.exe with the /p parameter and the filename to print the file, then copies the file to a history directory, sleeps for 5 seconds(to allow notepad to open and print), and finally deletes the original file.
What's happening is, instead of printing every single text file, it is only printing "random" files from the directory. Every single text file gets copied to the history directory and deleted from the original however, so I know that it is definitely listing all of the files and attempting to process each one. I've tried adding a call to Thread.Sleep for 5000 milliseconds, then changed it to 10000 milliseconds to be sure that the original file wasn't getting deleted before notepad grabbed it to print.
I'm more curious about what is actually happening than anything (a fix would be nice too!). I manually moved some of the files that did not print to the original directory, removing them from the history directory, and reran the program, where they DID print as they should, so I know it shouldn't be the files themselves, but something to do with the code.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim f() As String = ListFiles("l:\", "997")
Dim i As Integer
Try
For i = 0 To f.Length - 1
If Not f(i) = "" Then
System.Diagnostics.Process.Start("Notepad.exe", " /p l:\" & f(i))
My.Computer.FileSystem.CopyFile("l:\" & f(i), "k:\" & f(i))
'Thread.Sleep(5000)
Thread.Sleep(10000)
My.Computer.FileSystem.DeleteFile("l:\" & f(i))
End If
Next
'Thread.Sleep(5000)
Thread.Sleep(10000)
Catch ex As Exception
End Try
End Sub
Public Function ListFiles(ByVal strFilePath As String, ByVal strFileFilter As String) As String()
'finds all files in the strFilePath variable and matches them to the strFileFilter variable
'adds to string array strFiles if filename matches filter
Dim i As Integer = 0
Dim strFileName As String
Dim strFiles(0) As String
Dim strExclude As String = ""
Dim pos As Integer = 0
Dim posinc As Integer = 0
strFileName = Dir(strFilePath)
Do While Len(strFileName) > 0
'check to see if filename matches filter
If InStr(strFileName, strFileFilter) Then
If InStr(strFileName, "997") Then
FileOpen(1, strFilePath & strFileName, OpenMode.Input)
Do Until EOF(1)
strExclude = InputString(1, LOF(1))
Loop
pos = InStr(UCase(strExclude), "MANIFEST")
posinc = posinc + pos
pos = InStr(UCase(strExclude), "INVOICE")
posinc = posinc + pos
FileClose(1)
Else : posinc = 1
End If
If posinc > 0 Then
'add file to array
ReDim Preserve strFiles(i)
strFiles(i) = strFileName
i += 1
Else
My.Computer.FileSystem.MoveFile("l:\" & strFileName, "k:\" & strFileName)
End If
'MsgBox(strFileName & " " & IO.File.GetLastWriteTime(strFileName).ToString)
pos = 0
posinc = 0
End If
'get the next file
strFileName = Dir()
Loop
Return strFiles
End Function
Brief overview of the code above. An automated program fills the "L:\" directory with text files, and this program needs to print out certain files with "997" in the filename (namely files with "997" in the filename and containing the text "INVOICE" or "MANIFEST"). The ListFiles function does exactly this, then back in the Form1_Load() sub it is supposed to print each file, copy it, and delete the original.
Something to note, this code is developed in Visual Studio 2013 on Windows 7. The machine that actually runs this program is still on Windows XP.
I can see a few issues. the first and most obvious is the error handling:
You have a Try.. Catch with no error handling. You may be running in to an error without knowing it!! Add some output here, so you know if that is the case.
The second issue is to do with the way you are handling Process classes.
Instead of just calling System.Diagnostics.Process.Start in a loop and sleeping you should use the inbuilt method of handling execution. You are also not disposing of anything, which makes me die a little inside.
Try something like
Using p As New System.Diagnostics.Process
p.Start("Notepad.exe", " /p l:\" & f(i))
p.WaitForExit()
End Using
With both of these changes in place you should not have any issues. If you do there should at least be errors for you to look at and provide here, if necessary.

Open, Launch or Show a file for the user to read or write in vb.net

It sounds very simple but I have searched and cannot seem to find a way to open a log file which the user just created from my windows form app. The file exits I just want to open it after it is created.
I have a Dim path As String = TextBox1.Text and once the user names and clicks ok on the savefiledialog I have a msgbox that says "Done" and when you hit OK I have tried this
FileOpen(FreeFile, path, OpenMode.Input) but nothing happens. I just want it to open the log and show it to the user so they can edit or save it again or anything.
This is where I got the above code.
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.fileopen.aspx
Searching is difficult because everyone is trying to "Open" a file and process it during runtime. I am just trying to Show a file by Launching it like someone just double clicked it.
Here is the entire Export Button click Sub. It basically writes listbox items to file.
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim sfd As New SaveFileDialog
Dim path As String = TextBox1.Text
Dim arypath() As String = Split(TextBox1.Text, "\")
Dim pathDate As String
Dim foldername As String
foldername = arypath(arypath.Length - 1)
pathDate = Now.ToString("yyyy-MM-dd") & "_" & Now.ToString("hh;mm")
sfd.FileName = "FileScannerResults " & Chr(39) & foldername & Chr(39) & " " & pathDate
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
sfd.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
sfd.ShowDialog()
path = sfd.FileName
Using SW As New IO.StreamWriter(path)
If CkbxFolder.Checked = True Then
SW.WriteLine("Folders")
For Each itm As String In ListBox1.Items
SW.WriteLine(itm)
Next
End If
If CkbxFiles.Checked = True Then
SW.WriteLine("Files")
For Each itm As String In ListBox2.Items
SW.WriteLine(itm)
Next
End If
End Using
MsgBox("Done...")
FileOpen(FreeFile, path, OpenMode.Input) 'Why can't I open a file for you...
End Sub
Do not use the old VB6 methods. They are still here for compatibility reason, the new code should use the more powerful methods in the System.IO namespace.
However, as said in comments, FileOpen don't show anything for you, just opens the file
You coud write
Using sr = new StreamReader(path)
Dim line = sr.ReadLine()
if !string.IsNullOrEmpty(line) Then
textBoxForLog.AppendText(line)
End If
End Using
or simply (if the file is not too big)
Dim myLogText = File.ReadAllText(path)
textBoxForLog.Text = myLogText
As alternative, you could ask the operating system to run the program associated with the file extension and show the file for you
Process.Start(path)
To get the same behavior as if the user double-clicked it, just use System.Diagnostics.Process, and pass the filename to it's Start method:
Process.Start(path)
This will open the file using whatever the default application is for that filename based on its extension, just like Explorer does when you double-click it.

VB Search Domain User for File

I am putting together an old post here with this new one. My main goal is to combine these two portions so that the search does not need to be ran on each and every computer.
'Searching for all computers in the domain
Dim de As New DirectoryEntry()
de.Path = "WinNT://domain.name"
For Each d As DirectoryEntry In de.Children()
Console.WriteLine(d.Name)
Next
I can set the path as WinNT://domain.name/username...and I get a list of something, are they files? i am not sure?
Second portion of code searches the computer for the java.exe to display its version, as well as searching for any indication of a java file on that computer.
'Searching individual computer for Java Information
Dim sdkCommand As String
sdkCommand = "C:\Windows\System32\Java.exe -version 2> C:\Users\Desktop\JavaSDKInfo.txt && C:\Windows\System32\tasklist.exe /FI ""IMAGENAME eq java.exe"" >> C:\Users\Desktop\JavaSDKInfo.txt"
Shell("cmd.exe /c" & sdkCommand)
I am crazy confizzled when it comes to have each domain user run this(or to have me remotely execute it on each machine??). I have been given hints regarding dlls, etc. Any advice regarding how to go about this or what to do would be awesome!
I know its been a while so I will go ahead and list what I did as the answer.
Using replacement in the shell I am able to pull up the list of users that was written using a streamwriter. The command is then performed on each entry in that list.
Sub WriteUserFile()
Dim de As New DirectoryEntry()
de.Path = "WinNT://domain.name"
Using sw as New StreamWriter(File.Open(UserFile, FileMOde.OpenorCreate))
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
End Sub
In order to combine it I then used this next sub and the replacement command to sub in the user names. Push d allowed me to change the directory to each user (pending admin status)
Sub DoWork()
Dim sdkCommand as string = "pushd \\*\C$ && java.exe -version2>> $$$"
For each strUserName as String in strLines
Dim ReplaceCommand as String = sdkCommand.Replace("*", strUserName).Replace("$$$", "C:\InfoReadout.txt")
Shell("cmd.exe /c" & ReplaceCommand, True, -1)
End Sub

VB to run Command for java.exe and output text to txt file

Private Sub Command1_Click()
Dim sCommand as String
Dim oWrite as System.IO.StreamWriter
sCommand = "cmd C:\Windows\System32\java.exe -version2> C:\Users\Desktop\version.txt"
oWrite = IO.File.CreateText(C:\Users\Desktop\version.txt
End Sub
When i run the command in the command prompt it does what it is suppose to do (write to txt file. But when implemented into VB it will run and flash the command prompt but it will not write to a file.
Am I missing a line of something?
I was clearly making things way to complicated...
This ended up working perfectly Fine.
Sub Main()
Dim sdkCommand As String
sdkCommand = "C:\Windows\System32\Java.exe -version 2> C:\Users\Desktop\JavaSDKInfo.txt && C:\Windows\System32\tasklist.exe /FI ""IMAGENAME eq java.exe"" >> C:\Users\Desktop\JavaSDKInfo.txt"
Shell("cmd.exe /c" & sdkCommand)
End Sub

Multiple Commands to same Text File from VB

I have this which is exporting the SDK info to a txt file. I would also like to export the processes that are running to the same text file.
Dim sdkCommand As String
sdkCommand = "C:\Windows\System32\Java.exe -version 2> C:\Users\JavaSDKInfo.txt"
Shell("cmd.exe /c" & sdkCommand)
End Sub
If I try adding this to it, I am only able to still see the output from sdkCommand, but nothing about the tasks that are running. I am assuming I need to combine the shell statements?
Sub Main()
Dim sdkCommand As String
Dim proCommand As String
sdkCommand = "C:\Windows\System32\Java.exe -version 2> C:\Users\Desktop\JavaSDKInfo.txt"
proCommand = "C:\Windows\System32\tasklist.exe > C:\Users\Desktop\JavaSDKInfo.txt"
Shell("cmd.exe /c" & sdkCommand)
Shell("cmd.exe /c" & proCommand)
End Sub
Combining all the commands into one long one using && actually made this work and made it easier. This allowed me to add a ton more command prompt commands.
Sub Main()
Dim sdkcommand as String
'COmbine using && in command prompt
sdkCommand = "java.exe >>C:\text.txt && tasklist.exe >>C:\text.txt"
Shell("cmd.exe /c" and sdkCommand)
End Sub