Multiple Commands to same Text File from VB - vb.net

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

Related

manual entry in cmd window works, VBA executing CMD works, but not VBA when I use run (so I can hide the window)

SECOND EDIT/UPDATE: tried the path change recommendations, did not see any changes to the command string, still does not work. I re-wrote the code to use a fixed text file instead of a random temp file so I could monitor the contents of the file during execution. Able to conclusively show it is the
oShellObject.Run sCommandStringToExecute & " > " & sShellRndTmpFile, 0, True
code line that doesn't behave as expected. Still works with the w32tm command line, but not with the ntpq command line. With ntpq command, no changes made to the file, no error flags. I also tried out (again) the exec version of this problem where the window is supposed to flash a bit before it gets hidden programmatically. I get the expected reslut using exactly the same command string, cut and pasted into the other code. So the same command line works with manual entry into CMD, into PowerShell, and in the .exec code version, not the .run code version.
End of second edit. -------------------
EDIT: more debugging... ntpq -p works if I do .exec instead of .run, but then of course can't hid the cmd window. Extra test code at the end.
This Works: If I run these two commands in manually opened cmd window, or PowerShell window, both give the expected results.
w32tm /stripchart /computer:time.nist.gov /dataonly /samples:3 /rdtsc /period:1
ntpq -p
The second, ntpq -p, is bundled with NTP windows software from the home of the Network Time Protocol project that gives similar information to windows' w32tm when NTP is set up to look at the same time service computer as in the w32tm command.
This Doesn't work:
When I try to use these two command string when running CMD functions hidden using the classic "write to file" method shown in SO here and other places, the w32tm version gives the same results as the manual version, but the ntpq version just returns "error".
I read every single one of the recommended links for this question as well as searching OS and Google, and have not found an answer.
I am stuck on next step to troubleshoot the problem...only thing I could think of was to run the commands manually to confirm they work there. I can't imagine it being a administrator privileges issue since I can run them both in CMD line or PowerShell windows opened at normal rights level.
What should I look at next?
Here is the test code.
Option Explicit
Sub TestShellRun()
Dim sCmd As String, sReturnNTP As String
sCmd = "w32tm /stripchart /computer:time.nist.gov /dataonly /samples:3 /rdtsc /period:1 " ' /packetinfo"
sCmd = "%ComSpec% /C %SystemRoot%\system32\" & sCmd
sReturnNTP = fShellRun(sCmd) 'good return value, same as manual cmd line
Debug.Print sReturnNTP
sCmd = "ntpq -p"
sCmd = "%ComSpec% /C %SystemRoot%\system32\" & sCmd
sReturnNTP = fShellRun(sCmd) 'ERROR return value, even though manual cmd line has good values
Debug.Print sReturnNTP
End Sub
Public Function fShellRun(sCommandStringToExecute) As String
' This function will accept a string as a DOS command to execute.
' It will then execute the command in a shell, and capture the output into a file.
' That file is then read in and its contents are returned as the value the function returns.
' "myIP" is a user-selected global variable
Dim oShellObject, oFileSystemObject, sShellRndTmpFile
Dim oShellOutputFileToRead
Dim iErr As Long
Set oShellObject = CreateObject("Wscript.Shell")
Set oFileSystemObject = CreateObject("Scripting.FileSystemObject")
sShellRndTmpFile = oShellObject.ExpandEnvironmentStrings("%temp%") & oFileSystemObject.GetTempName
On Error Resume Next
oShellObject.Run sCommandStringToExecute & " > " & sShellRndTmpFile, 0, True
iErr = Err.Number
On Error GoTo 0
If iErr <> 0 Then
fShellRun = "error"
Exit Function
End If
On Error GoTo err_skip
fShellRun = oFileSystemObject.OpenTextFile(sShellRndTmpFile, 1).ReadAll
oFileSystemObject.DeleteFile sShellRndTmpFile, True
Exit Function
err_skip:
fShellRun = "error"
oFileSystemObject.DeleteFile sShellRndTmpFile, True
End Function
sCommand = "ntpq.exe -p"
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(sCommand)
strOutput = WshShellExec.StdOut.ReadAll
Debug.Print strOutput
Your fShellRun function didn't work due to error in temporary file path. Here is fixed version.
Function fShellRun(sCommandStringToExecute) As String
...
'invalid file path without path separator between directory path and filename!
sShellRndTmpFile = oShellObject.ExpandEnvironmentStrings("%temp%") & _
oFileSystemObject.GetTempName
'valid path with path separator between directory path and filename
sShellRndTmpFile = oFileSystemObject.BuildPath( _
Environ("temp"), oFileSystemObject.GetTempName)
...
End Function

vba shell command executing but no output

I am having some problems running a shell command and checking the output of the data. I wish to check using vba if the current remote user of the DB is Active. In
command prompt =
for /f "tokens=1-8" %a in ('quser') do #if "%d"== "Active" echo %COMPUTERNAME% %a %d
returns the users logged on and their state I wish to check that none of them are disconnected ("Disc"). I used this function to check the shell and return the pipe value as a string in a message box
Public Function ShellRun(sCmd As String) As String
'Run a shell command, returning the output as a string'
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec(sCmd)
Set oOutput = oExec.StdOut
Debug.Print sCmd
'handle the results as they are written to and read from the StdOut object'
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend
ShellRun = s
'example MsgBox ShellRun("cmd.exe /c" & "dir c:\")
End Function
Call Command used on click event
Dim CMDLineCommand As String
CMDLineCommand = "for /f ""tokens=1-8"" %a in ('quser') do #if ""%d""== ""Active"" echo %COMPUTERNAME% %a %d"
'(CMDLineCommand = "dir c:\")<------ THIS WORKS FINE
MsgBox ShellRun("cmd.exe /c " & CMDLineCommand)
This works fine for loads of command line commands I have tested it with but not query and therefore query user. The query user command works fine from command line but does not return anything when issued through a VBA Shell commands.
Any thoughts would be appreciated.
because shell does not know the path of the query.exe(quesr) it does not continue where as command prompt can use system variables to find exe's. solution find the query.exe and copy it to a working directory then run the shell command. mine was located in a hashed folder within C:\Windows\WinSxS be careful as here are 64bit versions and 32 bit.

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

Place Line from Text File in a Shell CMD. 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.